Fixed #24014 -- Unified OGRException and GDALException

Thanks Tim Graham for the review.
This commit is contained in:
Claude Paroz 2014-12-17 22:00:05 +01:00
parent 4fb38b7307
commit 9c1f501d7b
23 changed files with 98 additions and 94 deletions

View File

@ -5,7 +5,7 @@ from django.template import loader, Context
from django.utils import six from django.utils import six
from django.utils import translation from django.utils import translation
from django.contrib.gis.gdal import OGRException from django.contrib.gis.gdal import GDALException
from django.contrib.gis.geos import GEOSGeometry, GEOSException from django.contrib.gis.geos import GEOSGeometry, GEOSException
# Creating a template context that contains Django settings # Creating a template context that contains Django settings
@ -68,7 +68,7 @@ class OpenLayersWidget(Textarea):
ogr = value.ogr ogr = value.ogr
ogr.transform(srid) ogr.transform(srid)
wkt = ogr.wkt wkt = ogr.wkt
except OGRException as err: except GDALException as err:
logger.error( logger.error(
"Error transforming geometry from srid '%s' to srid '%s' (%s)" % ( "Error transforming geometry from srid '%s' to srid '%s' (%s)" % (
value.srid, srid, err) value.srid, srid, err)

View File

@ -60,7 +60,7 @@ class BaseGeometryWidget(Widget):
ogr = value.ogr ogr = value.ogr
ogr.transform(self.map_srid) ogr.transform(self.map_srid)
value = ogr value = ogr
except gdal.OGRException as err: except gdal.GDALException as err:
logger.error( logger.error(
"Error transforming geometry from srid '%s' to srid '%s' (%s)" % ( "Error transforming geometry from srid '%s' to srid '%s' (%s)" % (
value.srid, self.map_srid, err) value.srid, self.map_srid, err)

View File

@ -31,12 +31,13 @@
to a non-existent file location (e.g., `GDAL_LIBRARY_PATH='/null/path'`; to a non-existent file location (e.g., `GDAL_LIBRARY_PATH='/null/path'`;
setting to None/False/'' will not work as a string must be given). setting to None/False/'' will not work as a string must be given).
""" """
from django.contrib.gis.gdal.error import check_err, OGRException, OGRIndexError, SRSException # NOQA from django.contrib.gis.gdal.error import (check_err, GDALException,
OGRException, OGRIndexError, SRSException) # NOQA
from django.contrib.gis.gdal.geomtype import OGRGeomType # NOQA from django.contrib.gis.gdal.geomtype import OGRGeomType # NOQA
__all__ = [ __all__ = [
'check_err', 'OGRException', 'OGRIndexError', 'SRSException', 'OGRGeomType', 'check_err', 'GDALException', 'OGRException', 'OGRIndexError',
'HAS_GDAL', 'SRSException', 'OGRGeomType', 'HAS_GDAL',
] ]
# Attempting to import objects that depend on the GDAL library. The # Attempting to import objects that depend on the GDAL library. The
@ -53,7 +54,7 @@ try:
'Driver', 'DataSource', 'gdal_version', 'gdal_full_version', 'Driver', 'DataSource', 'gdal_version', 'gdal_full_version',
'GDAL_VERSION', 'SpatialReference', 'CoordTransform', 'OGRGeometry', 'GDAL_VERSION', 'SpatialReference', 'CoordTransform', 'OGRGeometry',
] ]
except OGRException: except GDALException:
HAS_GDAL = False HAS_GDAL = False
try: try:

View File

@ -39,7 +39,7 @@ from ctypes import byref
# The GDAL C library, OGR exceptions, and the Layer object. # The GDAL C library, OGR exceptions, and the Layer object.
from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.driver import Driver from django.contrib.gis.gdal.driver import Driver
from django.contrib.gis.gdal.error import OGRException, OGRIndexError from django.contrib.gis.gdal.error import GDALException, OGRIndexError
from django.contrib.gis.gdal.layer import Layer from django.contrib.gis.gdal.layer import Layer
# Getting the ctypes prototypes for the DataSource. # Getting the ctypes prototypes for the DataSource.
@ -75,21 +75,21 @@ class DataSource(GDALBase):
try: try:
# OGROpen will auto-detect the data source type. # OGROpen will auto-detect the data source type.
ds = capi.open_ds(force_bytes(ds_input), self._write, byref(ds_driver)) ds = capi.open_ds(force_bytes(ds_input), self._write, byref(ds_driver))
except OGRException: except GDALException:
# Making the error message more clear rather than something # Making the error message more clear rather than something
# like "Invalid pointer returned from OGROpen". # like "Invalid pointer returned from OGROpen".
raise OGRException('Could not open the datasource at "%s"' % ds_input) raise GDALException('Could not open the datasource at "%s"' % ds_input)
elif isinstance(ds_input, self.ptr_type) and isinstance(ds_driver, Driver.ptr_type): elif isinstance(ds_input, self.ptr_type) and isinstance(ds_driver, Driver.ptr_type):
ds = ds_input ds = ds_input
else: else:
raise OGRException('Invalid data source input type: %s' % type(ds_input)) raise GDALException('Invalid data source input type: %s' % type(ds_input))
if ds: if ds:
self.ptr = ds self.ptr = ds
self.driver = Driver(ds_driver) self.driver = Driver(ds_driver)
else: else:
# Raise an exception if the returned pointer is NULL # Raise an exception if the returned pointer is NULL
raise OGRException('Invalid data source file "%s"' % ds_input) raise GDALException('Invalid data source file "%s"' % ds_input)
def __del__(self): def __del__(self):
"Destroys this DataStructure object." "Destroys this DataStructure object."

View File

@ -1,6 +1,6 @@
from ctypes import c_void_p from ctypes import c_void_p
from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.error import OGRException from django.contrib.gis.gdal.error import GDALException
from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi
from django.utils import six from django.utils import six
@ -61,11 +61,11 @@ class Driver(GDALBase):
elif isinstance(dr_input, c_void_p): elif isinstance(dr_input, c_void_p):
driver = dr_input driver = dr_input
else: else:
raise OGRException('Unrecognized input type for GDAL/OGR Driver: %s' % str(type(dr_input))) raise GDALException('Unrecognized input type for GDAL/OGR Driver: %s' % str(type(dr_input)))
# Making sure we get a valid pointer to the OGR Driver # Making sure we get a valid pointer to the OGR Driver
if not driver: if not driver:
raise OGRException('Could not initialize GDAL/OGR Driver on input: %s' % str(dr_input)) raise GDALException('Could not initialize GDAL/OGR Driver on input: %s' % str(dr_input))
self.ptr = driver self.ptr = driver
def __str__(self): def __str__(self):

View File

@ -11,7 +11,7 @@
Lower left (min_x, min_y) o----------+ Lower left (min_x, min_y) o----------+
""" """
from ctypes import Structure, c_double from ctypes import Structure, c_double
from django.contrib.gis.gdal.error import OGRException from django.contrib.gis.gdal.error import GDALException
# The OGR definition of an Envelope is a C structure containing four doubles. # The OGR definition of an Envelope is a C structure containing four doubles.
@ -46,7 +46,7 @@ class Envelope(object):
elif isinstance(args[0], (tuple, list)): elif isinstance(args[0], (tuple, list)):
# A tuple was passed in. # A tuple was passed in.
if len(args[0]) != 4: if len(args[0]) != 4:
raise OGRException('Incorrect number of tuple elements (%d).' % len(args[0])) raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0]))
else: else:
self._from_sequence(args[0]) self._from_sequence(args[0])
else: else:
@ -56,13 +56,13 @@ class Envelope(object):
# Thanks to ww for the help # Thanks to ww for the help
self._from_sequence([float(a) for a in args]) self._from_sequence([float(a) for a in args])
else: else:
raise OGRException('Incorrect number (%d) of arguments.' % len(args)) raise GDALException('Incorrect number (%d) of arguments.' % len(args))
# Checking the x,y coordinates # Checking the x,y coordinates
if self.min_x > self.max_x: if self.min_x > self.max_x:
raise OGRException('Envelope minimum X > maximum X.') raise GDALException('Envelope minimum X > maximum X.')
if self.min_y > self.max_y: if self.min_y > self.max_y:
raise OGRException('Envelope minimum Y > maximum Y.') raise GDALException('Envelope minimum Y > maximum Y.')
def __eq__(self, other): def __eq__(self, other):
""" """
@ -76,7 +76,7 @@ class Envelope(object):
return (self.min_x == other[0]) and (self.min_y == other[1]) and \ return (self.min_x == other[0]) and (self.min_y == other[1]) and \
(self.max_x == other[2]) and (self.max_y == other[3]) (self.max_x == other[2]) and (self.max_y == other[3])
else: else:
raise OGRException('Equivalence testing only works with other Envelopes.') raise GDALException('Equivalence testing only works with other Envelopes.')
def __str__(self): def __str__(self):
"Returns a string representation of the tuple." "Returns a string representation of the tuple."
@ -120,7 +120,7 @@ class Envelope(object):
if maxy > self._envelope.MaxY: if maxy > self._envelope.MaxY:
self._envelope.MaxY = maxy self._envelope.MaxY = maxy
else: else:
raise OGRException('Incorrect number of tuple elements (%d).' % len(args[0])) raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0]))
else: else:
raise TypeError('Incorrect type of argument: %s' % str(type(args[0]))) raise TypeError('Incorrect type of argument: %s' % str(type(args[0])))
elif len(args) == 2: elif len(args) == 2:
@ -130,7 +130,7 @@ class Envelope(object):
# Individual parameters passed in. # Individual parameters passed in.
return self.expand_to_include(args) return self.expand_to_include(args)
else: else:
raise OGRException('Incorrect number (%d) of arguments.' % len(args[0])) raise GDALException('Incorrect number (%d) of arguments.' % len(args[0]))
@property @property
def min_x(self): def min_x(self):

View File

@ -1,24 +1,24 @@
""" """
This module houses the OGR & SRS Exception objects, and the This module houses the GDAL & SRS Exception objects, and the
check_err() routine which checks the status code returned by check_err() routine which checks the status code returned by
OGR methods. GDAL/OGR methods.
""" """
#### OGR & SRS Exceptions #### #### GDAL & SRS Exceptions ####
class GDALException(Exception): class GDALException(Exception):
pass pass
class OGRException(Exception): # Legacy name
pass OGRException = GDALException
class SRSException(Exception): class SRSException(Exception):
pass pass
class OGRIndexError(OGRException, KeyError): class OGRIndexError(GDALException, KeyError):
""" """
This exception is raised when an invalid index is encountered, and has This exception is raised when an invalid index is encountered, and has
the 'silent_variable_feature' attribute set to true. This ensures that the 'silent_variable_feature' attribute set to true. This ensures that
@ -27,20 +27,19 @@ class OGRIndexError(OGRException, KeyError):
""" """
silent_variable_failure = True silent_variable_failure = True
#### OGR error checking codes and routine #### #### GDAL/OGR error checking codes and routine ####
# OGR Error Codes # OGR Error Codes
OGRERR_DICT = { OGRERR_DICT = {
1: (OGRException, 'Not enough data.'), 1: (GDALException, 'Not enough data.'),
2: (OGRException, 'Not enough memory.'), 2: (GDALException, 'Not enough memory.'),
3: (OGRException, 'Unsupported geometry type.'), 3: (GDALException, 'Unsupported geometry type.'),
4: (OGRException, 'Unsupported operation.'), 4: (GDALException, 'Unsupported operation.'),
5: (OGRException, 'Corrupt data.'), 5: (GDALException, 'Corrupt data.'),
6: (OGRException, 'OGR failure.'), 6: (GDALException, 'OGR failure.'),
7: (SRSException, 'Unsupported SRS.'), 7: (SRSException, 'Unsupported SRS.'),
8: (OGRException, 'Invalid handle.'), 8: (GDALException, 'Invalid handle.'),
} }
OGRERR_NONE = 0
# CPL Error Codes # CPL Error Codes
# http://www.gdal.org/cpl__error_8h.html # http://www.gdal.org/cpl__error_8h.html
@ -56,17 +55,17 @@ CPLERR_DICT = {
9: (GDALException, 'UserInterrupt'), 9: (GDALException, 'UserInterrupt'),
10: (GDALException, 'ObjectNull'), 10: (GDALException, 'ObjectNull'),
} }
CPLERR_NONE = 0
ERR_NONE = 0
def check_err(code, cpl=False): def check_err(code, cpl=False):
""" """
Checks the given CPL/OGRERR, and raises an exception where appropriate. Checks the given CPL/OGRERR, and raises an exception where appropriate.
""" """
err_none = CPLERR_NONE if cpl else OGRERR_NONE
err_dict = CPLERR_DICT if cpl else OGRERR_DICT err_dict = CPLERR_DICT if cpl else OGRERR_DICT
if code == err_none: if code == ERR_NONE:
return return
elif code in err_dict: elif code in err_dict:
e, msg = err_dict[code] e, msg = err_dict[code]

View File

@ -1,6 +1,6 @@
# The GDAL C library, OGR exception, and the Field object # The GDAL C library, OGR exception, and the Field object
from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.error import OGRException, OGRIndexError from django.contrib.gis.gdal.error import GDALException, OGRIndexError
from django.contrib.gis.gdal.field import Field from django.contrib.gis.gdal.field import Field
from django.contrib.gis.gdal.geometries import OGRGeometry, OGRGeomType from django.contrib.gis.gdal.geometries import OGRGeometry, OGRGeomType
@ -28,7 +28,7 @@ class Feature(GDALBase):
Initializes Feature from a pointer and its Layer object. Initializes Feature from a pointer and its Layer object.
""" """
if not feat: if not feat:
raise OGRException('Cannot create OGR Feature, invalid pointer given.') raise GDALException('Cannot create OGR Feature, invalid pointer given.')
self.ptr = feat self.ptr = feat
self._layer = layer self._layer = layer

View File

@ -1,7 +1,7 @@
from ctypes import byref, c_int from ctypes import byref, c_int
from datetime import date, datetime, time from datetime import date, datetime, time
from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.error import OGRException from django.contrib.gis.gdal.error import GDALException
from django.contrib.gis.gdal.prototypes import ds as capi from django.contrib.gis.gdal.prototypes import ds as capi
from django.utils.encoding import force_text from django.utils.encoding import force_text
@ -29,7 +29,7 @@ class Field(GDALBase):
# Getting the pointer for this field. # Getting the pointer for this field.
fld_ptr = capi.get_feat_field_defn(feat.ptr, index) fld_ptr = capi.get_feat_field_defn(feat.ptr, index)
if not fld_ptr: if not fld_ptr:
raise OGRException('Cannot create OGR Field, invalid pointer given.') raise GDALException('Cannot create OGR Field, invalid pointer given.')
self.ptr = fld_ptr self.ptr = fld_ptr
# Setting the class depending upon the OGR Field Type (OFT) # Setting the class depending upon the OGR Field Type (OFT)
@ -67,7 +67,7 @@ class Field(GDALBase):
if status: if status:
return (yy, mm, dd, hh, mn, ss, tz) return (yy, mm, dd, hh, mn, ss, tz)
else: else:
raise OGRException('Unable to retrieve date & time information from the field.') raise GDALException('Unable to retrieve date & time information from the field.')
#### Field Properties #### #### Field Properties ####
@property @property
@ -155,7 +155,7 @@ class OFTDate(Field):
try: try:
yy, mm, dd, hh, mn, ss, tz = self.as_datetime() yy, mm, dd, hh, mn, ss, tz = self.as_datetime()
return date(yy.value, mm.value, dd.value) return date(yy.value, mm.value, dd.value)
except (ValueError, OGRException): except (ValueError, GDALException):
return None return None
@ -170,7 +170,7 @@ class OFTDateTime(Field):
try: try:
yy, mm, dd, hh, mn, ss, tz = self.as_datetime() yy, mm, dd, hh, mn, ss, tz = self.as_datetime()
return datetime(yy.value, mm.value, dd.value, hh.value, mn.value, ss.value) return datetime(yy.value, mm.value, dd.value, hh.value, mn.value, ss.value)
except (ValueError, OGRException): except (ValueError, GDALException):
return None return None
@ -181,7 +181,7 @@ class OFTTime(Field):
try: try:
yy, mm, dd, hh, mn, ss, tz = self.as_datetime() yy, mm, dd, hh, mn, ss, tz = self.as_datetime()
return time(hh.value, mn.value, ss.value) return time(hh.value, mn.value, ss.value)
except (ValueError, OGRException): except (ValueError, GDALException):
return None return None

View File

@ -46,7 +46,7 @@ from ctypes import byref, string_at, c_char_p, c_double, c_ubyte, c_void_p
# Getting GDAL prerequisites # Getting GDAL prerequisites
from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope
from django.contrib.gis.gdal.error import OGRException, OGRIndexError, SRSException from django.contrib.gis.gdal.error import GDALException, OGRIndexError, SRSException
from django.contrib.gis.gdal.geomtype import OGRGeomType from django.contrib.gis.gdal.geomtype import OGRGeomType
from django.contrib.gis.gdal.srs import SpatialReference, CoordTransform from django.contrib.gis.gdal.srs import SpatialReference, CoordTransform
@ -110,12 +110,12 @@ class OGRGeometry(GDALBase):
# OGR pointer (c_void_p) was the input. # OGR pointer (c_void_p) was the input.
g = geom_input g = geom_input
else: else:
raise OGRException('Invalid input type for OGR Geometry construction: %s' % type(geom_input)) raise GDALException('Invalid input type for OGR Geometry construction: %s' % type(geom_input))
# Now checking the Geometry pointer before finishing initialization # Now checking the Geometry pointer before finishing initialization
# by setting the pointer for the object. # by setting the pointer for the object.
if not g: if not g:
raise OGRException('Cannot create OGR Geometry from input: %s' % str(geom_input)) raise GDALException('Cannot create OGR Geometry from input: %s' % str(geom_input))
self.ptr = g self.ptr = g
# Assigning the SpatialReference object to the geometry, if valid. # Assigning the SpatialReference object to the geometry, if valid.
@ -143,7 +143,7 @@ class OGRGeometry(GDALBase):
wkb, srs = state wkb, srs = state
ptr = capi.from_wkb(wkb, None, byref(c_void_p()), len(wkb)) ptr = capi.from_wkb(wkb, None, byref(c_void_p()), len(wkb))
if not ptr: if not ptr:
raise OGRException('Invalid OGRGeometry loaded from pickled state.') raise GDALException('Invalid OGRGeometry loaded from pickled state.')
self.ptr = ptr self.ptr = ptr
self.srs = srs self.srs = srs
@ -666,7 +666,7 @@ class GeometryCollection(OGRGeometry):
tmp = OGRGeometry(geom) tmp = OGRGeometry(geom)
capi.add_geom(self.ptr, tmp.ptr) capi.add_geom(self.ptr, tmp.ptr)
else: else:
raise OGRException('Must add an OGRGeometry.') raise GDALException('Must add an OGRGeometry.')
@property @property
def point_count(self): def point_count(self):

View File

@ -1,4 +1,4 @@
from django.contrib.gis.gdal.error import OGRException from django.contrib.gis.gdal.error import GDALException
from django.utils import six from django.utils import six
@ -40,10 +40,10 @@ class OGRGeomType(object):
type_input = 'unknown' type_input = 'unknown'
num = self._str_types.get(type_input, None) num = self._str_types.get(type_input, None)
if num is None: if num is None:
raise OGRException('Invalid OGR String Type "%s"' % type_input) raise GDALException('Invalid OGR String Type "%s"' % type_input)
elif isinstance(type_input, int): elif isinstance(type_input, int):
if type_input not in self._types: if type_input not in self._types:
raise OGRException('Invalid OGR Integer Type: %d' % type_input) raise GDALException('Invalid OGR Integer Type: %d' % type_input)
num = type_input num = type_input
else: else:
raise TypeError('Invalid OGR input type given.') raise TypeError('Invalid OGR input type given.')

View File

@ -4,7 +4,7 @@ from ctypes import c_double, byref
# Other GDAL imports. # Other GDAL imports.
from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope
from django.contrib.gis.gdal.error import OGRException, OGRIndexError, SRSException from django.contrib.gis.gdal.error import GDALException, OGRIndexError, SRSException
from django.contrib.gis.gdal.feature import Feature from django.contrib.gis.gdal.feature import Feature
from django.contrib.gis.gdal.field import OGRFieldTypes from django.contrib.gis.gdal.field import OGRFieldTypes
from django.contrib.gis.gdal.geomtype import OGRGeomType from django.contrib.gis.gdal.geomtype import OGRGeomType
@ -35,7 +35,7 @@ class Layer(GDALBase):
collection of the `DataSource` while this Layer is still active. collection of the `DataSource` while this Layer is still active.
""" """
if not layer_ptr: if not layer_ptr:
raise OGRException('Cannot create Layer, invalid pointer given') raise GDALException('Cannot create Layer, invalid pointer given')
self.ptr = layer_ptr self.ptr = layer_ptr
self._ds = ds self._ds = ds
self._ldefn = capi.get_layer_defn(self._ptr) self._ldefn = capi.get_layer_defn(self._ptr)
@ -84,7 +84,7 @@ class Layer(GDALBase):
# If the Layer supports random reading, return. # If the Layer supports random reading, return.
try: try:
return Feature(capi.get_feature(self.ptr, feat_id), self) return Feature(capi.get_feature(self.ptr, feat_id), self)
except OGRException: except GDALException:
pass pass
else: else:
# Random access isn't supported, have to increment through # Random access isn't supported, have to increment through
@ -169,7 +169,7 @@ class Layer(GDALBase):
def _get_spatial_filter(self): def _get_spatial_filter(self):
try: try:
return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr))) return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))
except OGRException: except GDALException:
return None return None
def _set_spatial_filter(self, filter): def _set_spatial_filter(self, filter):
@ -196,7 +196,7 @@ class Layer(GDALBase):
in the Layer. in the Layer.
""" """
if field_name not in self.fields: if field_name not in self.fields:
raise OGRException('invalid field name: %s' % field_name) raise GDALException('invalid field name: %s' % field_name)
return [feat.get(field_name) for feat in self] return [feat.get(field_name) for feat in self]
def get_geoms(self, geos=False): def get_geoms(self, geos=False):

View File

@ -6,7 +6,7 @@ import re
from ctypes import c_char_p, c_int, CDLL, CFUNCTYPE from ctypes import c_char_p, c_int, CDLL, CFUNCTYPE
from ctypes.util import find_library from ctypes.util import find_library
from django.contrib.gis.gdal.error import OGRException from django.contrib.gis.gdal.error import GDALException
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
logger = logging.getLogger('django.contrib.gis') logger = logging.getLogger('django.contrib.gis')
@ -29,7 +29,7 @@ elif os.name == 'posix':
lib_names = ['gdal', 'GDAL', 'gdal1.11.0', 'gdal1.10.0', 'gdal1.9.0', lib_names = ['gdal', 'GDAL', 'gdal1.11.0', 'gdal1.10.0', 'gdal1.9.0',
'gdal1.8.0', 'gdal1.7.0'] 'gdal1.8.0', 'gdal1.7.0']
else: else:
raise OGRException('Unsupported OS "%s"' % os.name) raise GDALException('Unsupported OS "%s"' % os.name)
# Using the ctypes `find_library` utility to find the # Using the ctypes `find_library` utility to find the
# path to the GDAL library from the list of library names. # path to the GDAL library from the list of library names.
@ -40,7 +40,7 @@ if lib_names:
break break
if lib_path is None: if lib_path is None:
raise OGRException('Could not find the GDAL library (tried "%s"). ' raise GDALException('Could not find the GDAL library (tried "%s"). '
'Try setting GDAL_LIBRARY_PATH in your settings.' % 'Try setting GDAL_LIBRARY_PATH in your settings.' %
'", "'.join(lib_names)) '", "'.join(lib_names))
@ -90,7 +90,7 @@ def gdal_version_info():
ver = gdal_version().decode() ver = gdal_version().decode()
m = version_regex.match(ver) m = version_regex.match(ver)
if not m: if not m:
raise OGRException('Could not parse GDAL version string "%s"' % ver) raise GDALException('Could not parse GDAL version string "%s"' % ver)
return {key: m.group(key) for key in ('major', 'minor', 'subminor')} return {key: m.group(key) for key in ('major', 'minor', 'subminor')}
_verinfo = gdal_version_info() _verinfo = gdal_version_info()

View File

@ -4,7 +4,7 @@
""" """
from ctypes import c_void_p, string_at from ctypes import c_void_p, string_at
from django.contrib.gis.gdal.error import check_err, OGRException, SRSException from django.contrib.gis.gdal.error import check_err, GDALException, SRSException
from django.contrib.gis.gdal.libgdal import lgdal from django.contrib.gis.gdal.libgdal import lgdal
from django.utils import six from django.utils import six
@ -80,7 +80,7 @@ def check_geom(result, func, cargs):
if isinstance(result, six.integer_types): if isinstance(result, six.integer_types):
result = c_void_p(result) result = c_void_p(result)
if not result: if not result:
raise OGRException('Invalid geometry pointer returned from "%s".' % func.__name__) raise GDALException('Invalid geometry pointer returned from "%s".' % func.__name__)
return result return result
@ -124,7 +124,7 @@ def check_pointer(result, func, cargs):
if result: if result:
return result return result
else: else:
raise OGRException('Invalid pointer returned from "%s"' % func.__name__) raise GDALException('Invalid pointer returned from "%s"' % func.__name__)
def check_str_arg(result, func, cargs): def check_str_arg(result, func, cargs):

View File

@ -3,7 +3,7 @@ import unittest
from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.gdal import HAS_GDAL
if HAS_GDAL: if HAS_GDAL:
from django.contrib.gis.gdal import Driver, OGRException from django.contrib.gis.gdal import Driver, GDALException
valid_drivers = ( valid_drivers = (
@ -40,7 +40,7 @@ class DriverTest(unittest.TestCase):
def test02_invalid_driver(self): def test02_invalid_driver(self):
"Testing invalid GDAL/OGR Data Source Drivers." "Testing invalid GDAL/OGR Data Source Drivers."
for i in invalid_drivers: for i in invalid_drivers:
self.assertRaises(OGRException, Driver, i) self.assertRaises(GDALException, Driver, i)
def test03_aliases(self): def test03_aliases(self):
"Testing driver aliases." "Testing driver aliases."

View File

@ -6,7 +6,7 @@ from django.contrib.gis.gdal import HAS_GDAL
from django.contrib.gis.geometry.test_data import get_ds_file, TestDS, TEST_DATA from django.contrib.gis.geometry.test_data import get_ds_file, TestDS, TEST_DATA
if HAS_GDAL: if HAS_GDAL:
from django.contrib.gis.gdal import DataSource, Envelope, OGRGeometry, OGRException, OGRIndexError, GDAL_VERSION from django.contrib.gis.gdal import DataSource, Envelope, OGRGeometry, GDALException, OGRIndexError, GDAL_VERSION
from django.contrib.gis.gdal.field import OFTReal, OFTInteger, OFTString from django.contrib.gis.gdal.field import OFTReal, OFTInteger, OFTString
# List of acceptable data sources. # List of acceptable data sources.
@ -85,7 +85,7 @@ class DataSourceTest(unittest.TestCase):
def test02_invalid_shp(self): def test02_invalid_shp(self):
"Testing invalid SHP files for the Data Source." "Testing invalid SHP files for the Data Source."
for source in bad_ds: for source in bad_ds:
self.assertRaises(OGRException, DataSource, source.ds) self.assertRaises(GDALException, DataSource, source.ds)
def test03a_layers(self): def test03a_layers(self):
"Testing Data Source Layers." "Testing Data Source Layers."

View File

@ -4,7 +4,7 @@ from unittest import skipUnless
from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.gdal import HAS_GDAL
if HAS_GDAL: if HAS_GDAL:
from django.contrib.gis.gdal import Envelope, OGRException from django.contrib.gis.gdal import Envelope, GDALException
class TestPoint(object): class TestPoint(object):
@ -25,16 +25,16 @@ class EnvelopeTest(unittest.TestCase):
Envelope(0, 0, 5, 5) Envelope(0, 0, 5, 5)
Envelope(0, '0', '5', 5) # Thanks to ww for this Envelope(0, '0', '5', 5) # Thanks to ww for this
Envelope(e1._envelope) Envelope(e1._envelope)
self.assertRaises(OGRException, Envelope, (5, 5, 0, 0)) self.assertRaises(GDALException, Envelope, (5, 5, 0, 0))
self.assertRaises(OGRException, Envelope, 5, 5, 0, 0) self.assertRaises(GDALException, Envelope, 5, 5, 0, 0)
self.assertRaises(OGRException, Envelope, (0, 0, 5, 5, 3)) self.assertRaises(GDALException, Envelope, (0, 0, 5, 5, 3))
self.assertRaises(OGRException, Envelope, ()) self.assertRaises(GDALException, Envelope, ())
self.assertRaises(ValueError, Envelope, 0, 'a', 5, 5) self.assertRaises(ValueError, Envelope, 0, 'a', 5, 5)
self.assertRaises(TypeError, Envelope, 'foo') self.assertRaises(TypeError, Envelope, 'foo')
self.assertRaises(OGRException, Envelope, (1, 1, 0, 0)) self.assertRaises(GDALException, Envelope, (1, 1, 0, 0))
try: try:
Envelope(0, 0, 0, 0) Envelope(0, 0, 0, 0)
except OGRException: except GDALException:
self.fail("shouldn't raise an exception for min_x == max_x or min_y == max_y") self.fail("shouldn't raise an exception for min_x == max_x or min_y == max_y")
def test02_properties(self): def test02_properties(self):

View File

@ -13,7 +13,7 @@ from django.utils.six.moves import range
if HAS_GDAL: if HAS_GDAL:
from django.contrib.gis.gdal import (OGRGeometry, OGRGeomType, from django.contrib.gis.gdal import (OGRGeometry, OGRGeomType,
OGRException, OGRIndexError, SpatialReference, CoordTransform, GDALException, OGRIndexError, SpatialReference, CoordTransform,
GDAL_VERSION) GDAL_VERSION)
@ -33,9 +33,9 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
OGRGeomType('Unknown') OGRGeomType('Unknown')
# Should throw TypeError on this input # Should throw TypeError on this input
self.assertRaises(OGRException, OGRGeomType, 23) self.assertRaises(GDALException, OGRGeomType, 23)
self.assertRaises(OGRException, OGRGeomType, 'fooD') self.assertRaises(GDALException, OGRGeomType, 'fooD')
self.assertRaises(OGRException, OGRGeomType, 9) self.assertRaises(GDALException, OGRGeomType, 9)
# Equivalence can take strings, ints, and other OGRGeomTypes # Equivalence can take strings, ints, and other OGRGeomTypes
self.assertEqual(OGRGeomType(1), OGRGeomType(1)) self.assertEqual(OGRGeomType(1), OGRGeomType(1))
@ -243,7 +243,7 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
# Both rings in this geometry are not closed. # Both rings in this geometry are not closed.
poly = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5), (1 1, 2 1, 2 2, 2 1))') poly = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5), (1 1, 2 1, 2 2, 2 1))')
self.assertEqual(8, poly.point_count) self.assertEqual(8, poly.point_count)
with self.assertRaises(OGRException): with self.assertRaises(GDALException):
poly.centroid poly.centroid
poly.close_rings() poly.close_rings()
@ -407,7 +407,7 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
# Can't insert a Point into a MultiPolygon. # Can't insert a Point into a MultiPolygon.
mp = OGRGeometry('MultiPolygon') mp = OGRGeometry('MultiPolygon')
pnt = OGRGeometry('POINT(5 23)') pnt = OGRGeometry('POINT(5 23)')
self.assertRaises(OGRException, mp.add, pnt) self.assertRaises(GDALException, mp.add, pnt)
# GeometryCollection.add may take an OGRGeometry (if another collection # GeometryCollection.add may take an OGRGeometry (if another collection
# of the same type all child geoms will be added individually) or WKT. # of the same type all child geoms will be added individually) or WKT.

View File

@ -4,7 +4,7 @@ from unittest import skipUnless
from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.gdal import HAS_GDAL
if HAS_GDAL: if HAS_GDAL:
from django.contrib.gis.gdal import SpatialReference, CoordTransform, OGRException, SRSException from django.contrib.gis.gdal import SpatialReference, CoordTransform, GDALException, SRSException
class TestSRS: class TestSRS:
@ -160,7 +160,7 @@ class SpatialRefTest(unittest.TestCase):
try: try:
srs = SpatialReference(bad) srs = SpatialReference(bad)
srs.validate() srs.validate()
except (SRSException, OGRException): except (SRSException, GDALException):
pass pass
else: else:
self.fail('Should not have initialized on bad WKT "%s"!') self.fail('Should not have initialized on bad WKT "%s"!')

View File

@ -83,7 +83,7 @@ class Command(BaseCommand):
# Getting the OGR DataSource from the string parameter. # Getting the OGR DataSource from the string parameter.
try: try:
ds = gdal.DataSource(data_source) ds = gdal.DataSource(data_source)
except gdal.OGRException as msg: except gdal.GDALException as msg:
raise CommandError(msg) raise CommandError(msg)
# Returning the output of ogrinspect with the given arguments # Returning the output of ogrinspect with the given arguments

View File

@ -12,7 +12,7 @@ from django.contrib.gis.geometry.test_data import TEST_DATA
from django.utils.six import StringIO from django.utils.six import StringIO
if HAS_GDAL: if HAS_GDAL:
from django.contrib.gis.gdal import Driver, OGRException from django.contrib.gis.gdal import Driver, GDALException
from django.contrib.gis.utils.ogrinspect import ogrinspect from django.contrib.gis.utils.ogrinspect import ogrinspect
from .models import AllOGRFields from .models import AllOGRFields
@ -94,7 +94,7 @@ class OGRInspectTest(TestCase):
model_def = ogrinspect(ogr_db, 'Measurement', model_def = ogrinspect(ogr_db, 'Measurement',
layer_key=AllOGRFields._meta.db_table, layer_key=AllOGRFields._meta.db_table,
decimal=['f_decimal']) decimal=['f_decimal'])
except OGRException: except GDALException:
self.skipTest("Unable to setup an OGR connection to your database") self.skipTest("Unable to setup an OGR connection to your database")
self.assertTrue(model_def.startswith( self.assertTrue(model_def.startswith(

View File

@ -12,7 +12,7 @@ from django.core.exceptions import ObjectDoesNotExist
from django.db import connections, router from django.db import connections, router
from django.contrib.gis.db.models import GeometryField from django.contrib.gis.db.models import GeometryField
from django.contrib.gis.gdal import (CoordTransform, DataSource, from django.contrib.gis.gdal import (CoordTransform, DataSource,
OGRException, OGRGeometry, OGRGeomType, SpatialReference) GDALException, OGRGeometry, OGRGeomType, SpatialReference)
from django.contrib.gis.gdal.field import ( from django.contrib.gis.gdal.field import (
OFTDate, OFTDateTime, OFTInteger, OFTReal, OFTString, OFTTime) OFTDate, OFTDateTime, OFTInteger, OFTReal, OFTString, OFTTime)
from django.db import models, transaction from django.db import models, transaction
@ -207,7 +207,7 @@ class LayerMapping(object):
gtype = OGRGeomType(ogr_name + '25D') gtype = OGRGeomType(ogr_name + '25D')
else: else:
gtype = OGRGeomType(ogr_name) gtype = OGRGeomType(ogr_name)
except OGRException: except GDALException:
raise LayerMapError('Invalid mapping for GeometryField "%s".' % field_name) raise LayerMapError('Invalid mapping for GeometryField "%s".' % field_name)
# Making sure that the OGR Layer's Geometry is compatible. # Making sure that the OGR Layer's Geometry is compatible.
@ -304,7 +304,7 @@ class LayerMapping(object):
# Verify OGR geometry. # Verify OGR geometry.
try: try:
val = self.verify_geom(feat.geom, model_field) val = self.verify_geom(feat.geom, model_field)
except OGRException: except GDALException:
raise LayerMapError('Could not retrieve geometry from feature.') raise LayerMapError('Could not retrieve geometry from feature.')
elif isinstance(model_field, models.base.ModelBase): elif isinstance(model_field, models.base.ModelBase):
# The related _model_, not a field was passed in -- indicating # The related _model_, not a field was passed in -- indicating

View File

@ -161,6 +161,10 @@ Minor features
* Compatibility shims for ``SpatialRefSys`` and ``GeometryColumns`` changed in * Compatibility shims for ``SpatialRefSys`` and ``GeometryColumns`` changed in
Django 1.2 have been removed. Django 1.2 have been removed.
* All GDAL-related exceptions are now raised with ``GDALException``. The former
``OGRException`` has been kept for backwards compatibility but should not be
used any longer.
:mod:`django.contrib.messages` :mod:`django.contrib.messages`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^