本文整理汇总了Python中django.contrib.gis.gdal.GDALException方法的典型用法代码示例。如果您正苦于以下问题:Python gdal.GDALException方法的具体用法?Python gdal.GDALException怎么用?Python gdal.GDALException使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.contrib.gis.gdal
的用法示例。
在下文中一共展示了gdal.GDALException方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: to_python
# 需要导入模块: from django.contrib.gis import gdal [as 别名]
# 或者: from django.contrib.gis.gdal import GDALException [as 别名]
def to_python(self, value):
if value in self.empty_values:
return None
sref = None
# Work with a single GeoJSON geometry or a Feature.
value = json.loads(value) if '"Feature"' in value else value
if isinstance(value, collections.Mapping):
feat = sc.as_feature(value)
value = json.dumps(feat.get('geometry') or value)
sref = feat.srs
# Handle a comma delimited extent.
elif list(value).count(',') == 3:
value = Envelope(value.split(',')).polygon.ExportToWkt()
try:
geom = gdal.OGRGeometry(value, srs=getattr(sref, 'wkt', None))
except (gdal.GDALException, TypeError, ValueError):
raise forms.ValidationError(self.error_messages['invalid_geom'],
code='invalid_geom')
if not geom.srs:
geom.srid = self.srid or self.widget.map_srid
return geom
示例2: test01_init
# 需要导入模块: from django.contrib.gis import gdal [as 别名]
# 或者: from django.contrib.gis.gdal import GDALException [as 别名]
def test01_init(self):
"Testing Envelope initialization."
e1 = Envelope((0, 0, 5, 5))
Envelope(0, 0, 5, 5)
Envelope(0, '0', '5', 5) # Thanks to ww for this
Envelope(e1._envelope)
with self.assertRaises(GDALException):
Envelope((5, 5, 0, 0))
with self.assertRaises(GDALException):
Envelope(5, 5, 0, 0)
with self.assertRaises(GDALException):
Envelope((0, 0, 5, 5, 3))
with self.assertRaises(GDALException):
Envelope(())
with self.assertRaises(ValueError):
Envelope(0, 'a', 5, 5)
with self.assertRaises(TypeError):
Envelope('foo')
with self.assertRaises(GDALException):
Envelope((1, 1, 0, 0))
# Shouldn't raise an exception for min_x == max_x or min_y == max_y
Envelope(0, 0, 0, 0)
示例3: render
# 需要导入模块: from django.contrib.gis import gdal [as 别名]
# 或者: from django.contrib.gis.gdal import GDALException [as 别名]
def render(self, name, value, attrs=None):
# If a string reaches here (via a validation error on another
# field) then just reconstruct the Geometry.
if isinstance(value, six.string_types):
value = self.deserialize(value)
if value:
# Check that srid of value and map match
if value.srid != self.map_srid:
try:
ogr = value.ogr
ogr.transform(self.map_srid)
value = ogr
except gdal.GDALException as err:
logger.error(
"Error transforming geometry from srid '%s' to srid '%s' (%s)" % (
value.srid, self.map_srid, err)
)
context = self.build_attrs(
attrs,
name=name,
module='geodjango_%s' % name.replace('-', '_'), # JS-safe
serialized=self.serialize(value),
geom_type=gdal.OGRGeomType(self.attrs['geom_type']),
STATIC_URL=settings.STATIC_URL,
LANGUAGE_BIDI=translation.get_language_bidi(),
)
return loader.render_to_string(self.template_name, context)
示例4: handle
# 需要导入模块: from django.contrib.gis import gdal [as 别名]
# 或者: from django.contrib.gis.gdal import GDALException [as 别名]
def handle(self, *args, **options):
data_source, model_name = options.pop('data_source'), options.pop('model_name')
if not gdal.HAS_GDAL:
raise CommandError('GDAL is required to inspect geospatial data sources.')
# Getting the OGR DataSource from the string parameter.
try:
ds = gdal.DataSource(data_source)
except gdal.GDALException as msg:
raise CommandError(msg)
# Returning the output of ogrinspect with the given arguments
# and options.
from django.contrib.gis.utils.ogrinspect import _ogrinspect, mapping
# Filter options to params accepted by `_ogrinspect`
ogr_options = {k: v for k, v in options.items()
if k in inspect.getargspec(_ogrinspect).args and v is not None}
output = [s for s in _ogrinspect(ds, model_name, **ogr_options)]
if options['mapping']:
# Constructing the keyword arguments for `mapping`, and
# calling it on the data source.
kwargs = {'geom_name': options['geom_name'],
'layer_key': options['layer_key'],
'multi_geom': options['multi_geom'],
}
mapping_dict = mapping(ds, **kwargs)
# This extra legwork is so that the dictionary definition comes
# out in the same order as the fields in the model definition.
rev_mapping = {v: k for k, v in mapping_dict.items()}
output.extend(['', '# Auto-generated `LayerMapping` dictionary for %s model' % model_name,
'%s_mapping = {' % model_name.lower()])
output.extend(" '%s' : '%s'," % (
rev_mapping[ogr_fld], ogr_fld) for ogr_fld in ds[options['layer_key']].fields
)
output.extend([" '%s' : '%s'," % (options['geom_name'], mapping_dict[options['geom_name']]), '}'])
return '\n'.join(output) + '\n'
示例5: get_context
# 需要导入模块: from django.contrib.gis import gdal [as 别名]
# 或者: from django.contrib.gis.gdal import GDALException [as 别名]
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
# If a string reaches here (via a validation error on another
# field) then just reconstruct the Geometry.
if value and isinstance(value, str):
value = self.deserialize(value)
if value:
# Check that srid of value and map match
if value.srid and value.srid != self.map_srid:
try:
ogr = value.ogr
ogr.transform(self.map_srid)
value = ogr
except gdal.GDALException as err:
logger.error(
"Error transforming geometry from srid '%s' to srid '%s' (%s)",
value.srid, self.map_srid, err
)
if attrs is None:
attrs = {}
build_attrs_kwargs = {
'name': name,
'module': 'geodjango_%s' % name.replace('-', '_'), # JS-safe
'serialized': self.serialize(value),
'geom_type': gdal.OGRGeomType(self.attrs['geom_type']),
'STATIC_URL': settings.STATIC_URL,
'LANGUAGE_BIDI': translation.get_language_bidi(),
}
build_attrs_kwargs.update(attrs)
context.update(self.build_attrs(self.attrs, build_attrs_kwargs))
return context
示例6: _from_file
# 需要导入模块: from django.contrib.gis import gdal [as 别名]
# 或者: from django.contrib.gis.gdal import GDALException [as 别名]
def _from_file(self, fileobj, tmpdir):
if zipfile.is_zipfile(fileobj):
with zipfile.ZipFile(fileobj) as zf:
extracted = []
for item in zf.infolist():
fname = os.path.abspath(os.path.join(tmpdir, item.filename))
if fname.startswith(tmpdir):
zf.extract(item, tmpdir)
extracted.append(fname)
for path in extracted:
if path.endswith('.shp'):
fname = path
else:
# NOTE: is_zipfile() seeks to end of file or at least 110 bytes.
fileobj.seek(0)
with tempfile.NamedTemporaryFile(dir=tmpdir, delete=False) as fp:
shutil.copyfileobj(fileobj, fp)
fname = fp.name
# Attempt to union all geometries from GDAL data source.
try:
geoms = gdal.DataSource(fname)[0].get_geoms()
geom = reduce(lambda g1, g2: g1.union(g2), geoms)
if not geom.srs:
raise gdal.GDALException('Cannot determine SRS')
except (gdal.GDALException, IndexError):
raise forms.ValidationError(
GeometryField.default_error_messages['invalid_geom'],
code='invalid_geom')
return geom
示例7: zoom_bbox
# 需要导入模块: from django.contrib.gis import gdal [as 别名]
# 或者: from django.contrib.gis.gdal import GDALException [as 别名]
def zoom_bbox(self, bbox):
"""Zoom map to geometry extent.
Arguments:
bbox -- OGRGeometry polygon to zoom map extent
"""
try:
bbox.transform(self.map.srs)
except gdal.GDALException:
pass
else:
self.map.zoom_to_box(mapnik.Box2d(*bbox.extent))
示例8: handle
# 需要导入模块: from django.contrib.gis import gdal [as 别名]
# 或者: from django.contrib.gis.gdal import GDALException [as 别名]
def handle(self, *args, **options):
data_source, model_name = options.pop('data_source'), options.pop('model_name')
if not gdal.HAS_GDAL:
raise CommandError('GDAL is required to inspect geospatial data sources.')
# Getting the OGR DataSource from the string parameter.
try:
ds = gdal.DataSource(data_source)
except gdal.GDALException as msg:
raise CommandError(msg)
# Returning the output of ogrinspect with the given arguments
# and options.
from django.contrib.gis.utils.ogrinspect import _ogrinspect, mapping
# Filter options to params accepted by `_ogrinspect`
ogr_options = {k: v for k, v in options.items()
if k in get_func_args(_ogrinspect) and v is not None}
output = [s for s in _ogrinspect(ds, model_name, **ogr_options)]
if options['mapping']:
# Constructing the keyword arguments for `mapping`, and
# calling it on the data source.
kwargs = {'geom_name': options['geom_name'],
'layer_key': options['layer_key'],
'multi_geom': options['multi_geom'],
}
mapping_dict = mapping(ds, **kwargs)
# This extra legwork is so that the dictionary definition comes
# out in the same order as the fields in the model definition.
rev_mapping = {v: k for k, v in mapping_dict.items()}
output.extend(['', '# Auto-generated `LayerMapping` dictionary for %s model' % model_name,
'%s_mapping = {' % model_name.lower()])
output.extend(" '%s' : '%s'," % (
rev_mapping[ogr_fld], ogr_fld) for ogr_fld in ds[options['layer_key']].fields
)
output.extend([" '%s' : '%s'," % (options['geom_name'], mapping_dict[options['geom_name']]), '}'])
return '\n'.join(output) + '\n'
示例9: test02_invalid_driver
# 需要导入模块: from django.contrib.gis import gdal [as 别名]
# 或者: from django.contrib.gis.gdal import GDALException [as 别名]
def test02_invalid_driver(self):
"Testing invalid GDAL/OGR Data Source Drivers."
for i in invalid_drivers:
with self.assertRaises(GDALException):
Driver(i)
示例10: test_time_field
# 需要导入模块: from django.contrib.gis import gdal [as 别名]
# 或者: from django.contrib.gis.gdal import GDALException [as 别名]
def test_time_field(self):
# Getting the database identifier used by OGR, if None returned
# GDAL does not have the support compiled in.
ogr_db = get_ogr_db_string()
if not ogr_db:
self.skipTest("Unable to setup an OGR connection to your database")
try:
# Writing shapefiles via GDAL currently does not support writing OGRTime
# fields, so we need to actually use a database
model_def = ogrinspect(ogr_db, 'Measurement',
layer_key=AllOGRFields._meta.db_table,
decimal=['f_decimal'])
except GDALException:
self.skipTest("Unable to setup an OGR connection to your database")
self.assertTrue(model_def.startswith(
'# This is an auto-generated Django model module created by ogrinspect.\n'
'from django.contrib.gis.db import models\n'
'\n'
'\n'
'class Measurement(models.Model):\n'
))
# The ordering of model fields might vary depending on several factors (version of GDAL, etc.)
if connection.vendor == 'sqlite':
# SpatiaLite introspection is somewhat lacking (#29461).
self.assertIn(' f_decimal = models.CharField(max_length=0)', model_def)
else:
self.assertIn(' f_decimal = models.DecimalField(max_digits=0, decimal_places=0)', model_def)
self.assertIn(' f_int = models.IntegerField()', model_def)
self.assertIn(' f_datetime = models.DateTimeField()', model_def)
self.assertIn(' f_time = models.TimeField()', model_def)
if connection.vendor == 'sqlite':
self.assertIn(' f_float = models.CharField(max_length=0)', model_def)
else:
self.assertIn(' f_float = models.FloatField()', model_def)
max_length = 0 if connection.vendor == 'sqlite' else 10
self.assertIn(' f_char = models.CharField(max_length=%s)' % max_length, model_def)
self.assertIn(' f_date = models.DateField()', model_def)
# Some backends may have srid=-1
self.assertIsNotNone(re.search(r' geom = models.PolygonField\(([^\)])*\)', model_def))
示例11: get_ogr_db_string
# 需要导入模块: from django.contrib.gis import gdal [as 别名]
# 或者: from django.contrib.gis.gdal import GDALException [as 别名]
def get_ogr_db_string():
"""
Construct the DB string that GDAL will use to inspect the database.
GDAL will create its own connection to the database, so we re-use the
connection settings from the Django test.
"""
db = connections.databases['default']
# Map from the django backend into the OGR driver name and database identifier
# https://www.gdal.org/ogr/ogr_formats.html
#
# TODO: Support Oracle (OCI).
drivers = {
'django.contrib.gis.db.backends.postgis': ('PostgreSQL', "PG:dbname='%(db_name)s'", ' '),
'django.contrib.gis.db.backends.mysql': ('MySQL', 'MYSQL:"%(db_name)s"', ','),
'django.contrib.gis.db.backends.spatialite': ('SQLite', '%(db_name)s', '')
}
db_engine = db['ENGINE']
if db_engine not in drivers:
return None
drv_name, db_str, param_sep = drivers[db_engine]
# Ensure that GDAL library has driver support for the database.
try:
Driver(drv_name)
except GDALException:
return None
# SQLite/SpatiaLite in-memory databases
if db['NAME'] == ":memory:":
return None
# Build the params of the OGR database connection string
params = [db_str % {'db_name': db['NAME']}]
def add(key, template):
value = db.get(key, None)
# Don't add the parameter if it is not in django's settings
if value:
params.append(template % value)
add('HOST', "host='%s'")
add('PORT', "port='%s'")
add('USER', "user='%s'")
add('PASSWORD', "password='%s'")
return param_sep.join(params)
示例12: test_time_field
# 需要导入模块: from django.contrib.gis import gdal [as 别名]
# 或者: from django.contrib.gis.gdal import GDALException [as 别名]
def test_time_field(self):
# Getting the database identifier used by OGR, if None returned
# GDAL does not have the support compiled in.
ogr_db = get_ogr_db_string()
if not ogr_db:
self.skipTest("Unable to setup an OGR connection to your database")
try:
# Writing shapefiles via GDAL currently does not support writing OGRTime
# fields, so we need to actually use a database
model_def = ogrinspect(ogr_db, 'Measurement',
layer_key=AllOGRFields._meta.db_table,
decimal=['f_decimal'])
except GDALException:
self.skipTest("Unable to setup an OGR connection to your database")
self.assertTrue(model_def.startswith(
'# This is an auto-generated Django model module created by ogrinspect.\n'
'from django.contrib.gis.db import models\n'
'\n'
'\n'
'class Measurement(models.Model):\n'
))
# The ordering of model fields might vary depending on several factors (version of GDAL, etc.)
if connection.vendor == 'sqlite':
# SpatiaLite introspection is somewhat lacking (#29461).
self.assertIn(' f_decimal = models.CharField(max_length=0)', model_def)
else:
self.assertIn(' f_decimal = models.DecimalField(max_digits=0, decimal_places=0)', model_def)
self.assertIn(' f_int = models.IntegerField()', model_def)
if connection.vendor != 'mysql' or not connection.mysql_is_mariadb:
# Probably a bug between GDAL and MariaDB on time fields.
self.assertIn(' f_datetime = models.DateTimeField()', model_def)
self.assertIn(' f_time = models.TimeField()', model_def)
if connection.vendor == 'sqlite':
self.assertIn(' f_float = models.CharField(max_length=0)', model_def)
else:
self.assertIn(' f_float = models.FloatField()', model_def)
max_length = 0 if connection.vendor == 'sqlite' else 10
self.assertIn(' f_char = models.CharField(max_length=%s)' % max_length, model_def)
self.assertIn(' f_date = models.DateField()', model_def)
# Some backends may have srid=-1
self.assertIsNotNone(re.search(r' geom = models.PolygonField\(([^\)])*\)', model_def))