当前位置: 首页>>代码示例>>Python>>正文


Python gdal.GDALException方法代码示例

本文整理汇总了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 
开发者ID:bkg,项目名称:django-spillway,代码行数:23,代码来源:fields.py

示例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) 
开发者ID:nesdis,项目名称:djongo,代码行数:24,代码来源:test_envelope.py

示例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) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:31,代码来源:widgets.py

示例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' 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:39,代码来源:ogrinspect.py

示例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 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:36,代码来源:widgets.py

示例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 
开发者ID:bkg,项目名称:django-spillway,代码行数:31,代码来源:fields.py

示例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)) 
开发者ID:bkg,项目名称:django-spillway,代码行数:14,代码来源:carto.py

示例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' 
开发者ID:drexly,项目名称:openhgsenti,代码行数:39,代码来源:ogrinspect.py

示例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) 
开发者ID:nesdis,项目名称:djongo,代码行数:7,代码来源:test_driver.py

示例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)) 
开发者ID:nesdis,项目名称:djongo,代码行数:45,代码来源:tests.py

示例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) 
开发者ID:nesdis,项目名称:djongo,代码行数:50,代码来源:tests.py

示例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)) 
开发者ID:nesdis,项目名称:djongo,代码行数:47,代码来源:tests.py


注:本文中的django.contrib.gis.gdal.GDALException方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。