Django

Code

Changeset 6436

Show
Ignore:
Timestamp:
09/29/07 09:02:41 (1 year ago)
Author:
jbronn
Message:

gis: gdal: OSGeo sprint -- cleaned up spatial references associated with geometries (fixed a segfault); cleaned up Envelope module (thanks to ww for help), and added tests; added a test module for invoking all gdal tests; changed exception style.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/gis/django/contrib/gis/gdal/datasource.py

    r5749 r6436  
    55# The GDAL C library, OGR exceptions, and the Layer object. 
    66from django.contrib.gis.gdal.libgdal import lgdal 
    7 from django.contrib.gis.gdal.error import OGRException, check_err 
     7from django.contrib.gis.gdal.error import OGRException, OGRIndexError, check_err 
    88from django.contrib.gis.gdal.layer import Layer 
    99from django.contrib.gis.gdal.driver import Driver 
     
    6161        #  _before_ we try to open up a data source. 
    6262        if not lgdal.OGRGetDriverCount() and not lgdal.OGRRegisterAll(): 
    63             raise OGRException, 'Could not register all the OGR data source drivers!' 
     63            raise OGRException('Could not register all the OGR data source drivers!') 
    6464 
    6565        if isinstance(ds_input, StringType): 
     
    7373            ds = ds_input 
    7474        else: 
    75             raise OGRException, 'Invalid data source input type: %s' % str(type(ds_input)) 
     75            raise OGRException('Invalid data source input type: %s' % str(type(ds_input))) 
    7676 
    7777        # Raise an exception if the returned pointer is NULL 
    7878        if not ds: 
    7979            self._ds = False 
    80             raise OGRException, 'Invalid data source file "%s"' % ds_input 
     80            raise OGRException('Invalid data source file "%s"' % ds_input) 
    8181        else: 
    8282            self._ds = ds 
     
    9696        if isinstance(index, StringType): 
    9797            l = lgdal.OGR_DS_GetLayerByName(self._ds, c_char_p(index)) 
    98             if not l: raise IndexError, 'invalid OGR Layer name given: "%s"' % index 
     98            if not l: raise OGRIndexError('invalid OGR Layer name given: "%s"' % index) 
    9999        else: 
    100100            if index < 0 or index >= self.layer_count: 
    101                 raise IndexError, 'index out of range' 
     101                raise OGRIndexError('index out of range') 
    102102            l = lgdal.OGR_DS_GetLayer(self._ds, c_int(index)) 
    103103        return Layer(l) 
  • django/branches/gis/django/contrib/gis/gdal/driver.py

    r5749 r6436  
    4646            dr = input 
    4747        else: 
    48             raise OGRException, 'Unrecognized input type for OGR Driver: %s' % str(type(input)) 
     48            raise OGRException('Unrecognized input type for OGR Driver: %s' % str(type(input))) 
    4949 
    5050        # Making sure we get a valid pointer to the OGR Driver 
    5151        if not dr: 
    52             raise OGRException, 'Could not initialize OGR Driver on input: %s' % str(input
     52            raise OGRException('Could not initialize OGR Driver on input: %s' % str(input)
    5353        self._dr = dr 
    5454 
     
    6262        #  will be registered over and over again) 
    6363        if not self.driver_count and not lgdal.OGRRegisterAll(): 
    64             raise OGRException, 'Could not register all the OGR data source drivers!' 
     64            raise OGRException('Could not register all the OGR data source drivers!') 
    6565                     
    6666    # Driver properties 
  • django/branches/gis/django/contrib/gis/gdal/envelope.py

    r5749 r6436  
    1 from ctypes import Structure, c_double 
    2 from types import TupleType 
    3  
    41""" 
    52 The GDAL/OGR library uses an Envelope structure to hold the bounding 
     
    1512   
    1613""" 
     14from ctypes import Structure, c_double 
     15from types import TupleType, ListType 
     16from django.contrib.gis.gdal.error import OGRException 
    1717 
    1818# The OGR definition of an Envelope is a C structure containing four doubles. 
     
    2828 
    2929class Envelope(object): 
    30     "A class that will wrap an OGR Envelope structure." 
     30    """ 
     31    The Envelope object is a C structure that contains the minimum and 
     32     maximum X, Y coordinates for a rectangle bounding box.  The naming 
     33     of the variables is compatible with the OGR Envelope structure. 
     34    """ 
    3135 
    3236    def __init__(self, *args): 
     37        """ 
     38        The initialization function may take an OGREnvelope structure, 4-element 
     39         tuple or list, or 4 individual arguments. 
     40        """ 
     41         
    3342        if len(args) == 1: 
    3443            if isinstance(args[0], OGREnvelope): 
    3544                # OGREnvelope (a ctypes Structure) was passed in. 
    3645                self._envelope = args[0] 
    37             elif isinstance(args[0], TupleType) and len(args[0]) == 4: 
    38                 # A Tuple was passed in 
    39                 self._from_tuple(args[0]) 
     46            elif isinstance(args[0], (TupleType, ListType)): 
     47                # A tuple was passed in. 
     48                if len(args[0]) != 4: 
     49                    raise OGRException('Incorrect number of tuple elements (%d).' % len(args[0])) 
     50                else: 
     51                    self._from_sequence(args[0]) 
    4052            else: 
    41                 raise OGRException, 'Incorrect type of argument: %s' % str(type(args[0])) 
     53                raise TypeError('Incorrect type of argument: %s' % str(type(args[0]))) 
    4254        elif len(args) == 4: 
    43             self._from_tuple(args) 
     55            # Individiual parameters passed in. 
     56            #  Thanks to ww for the help 
     57            self._from_sequence(map(float, args)) 
    4458        else: 
    45             raise OGRException, 'Incorrect number of arguments!' 
     59            raise OGRException('Incorrect number (%d) of arguments.' % len(args)) 
     60 
     61        # Checking the x,y coordinates 
     62        if self.min_x >= self.max_x: 
     63            raise OGRException('Envelope minimum X >= maximum X.') 
     64        if self.min_y >= self.max_y: 
     65            raise OGRException('Envelope minimum Y >= maximum Y.') 
    4666 
    4767    def __eq__(self, other): 
    48         "Returns true if the envelopes are equivalent; can compare against other Envelopes and 4-tuples." 
     68        """ 
     69        Returns True if the envelopes are equivalent; can compare against 
     70        other Envelopes and 4-tuples. 
     71        """ 
    4972        if isinstance(other, Envelope): 
    5073            return (self.min_x == other.min_x) and (self.min_y == other.min_y) and \ 
     
    5477                   (self.max_x == other[2]) and (self.max_y == other[3]) 
    5578        else: 
    56             raise OGRException, 'Equivalence testing only works with other Envelopes.' 
     79            raise OGRException('Equivalence testing only works with other Envelopes.') 
    5780 
    5881    def __str__(self): 
     
    6083        return str(self.tuple) 
    6184 
    62     def _from_tuple(self, tup): 
    63         "Initializes the C OGR Envelope structure from the given tuple." 
     85    def _from_sequence(self, seq): 
     86        "Initializes the C OGR Envelope structure from the given sequence." 
    6487        self._envelope = OGREnvelope() 
    65         self._envelope.MinX = tup[0] 
    66         self._envelope.MinY = tup[1] 
    67         self._envelope.MaxX = tup[2] 
    68         self._envelope.MaxY = tup[3] 
     88        self._envelope.MinX = seq[0] 
     89        self._envelope.MinY = seq[1] 
     90        self._envelope.MaxX = seq[2] 
     91        self._envelope.MaxY = seq[3] 
    6992     
    7093    @property 
     
    107130        "Returns WKT representing a Polygon for this envelope." 
    108131        # TODO: Fix significant figures. 
    109         return 'POLYGON((%s %s,%s %s,%s %s,%s %s,%s %s))' % (self.min_x, self.min_y, self.min_x, self.max_y, 
    110                                                              self.max_x, self.max_y, self.max_x, self.min_y, 
    111                                                              self.min_x, self.min_y) 
    112  
     132        return 'POLYGON((%s %s,%s %s,%s %s,%s %s,%s %s))' % \ 
     133               (self.min_x, self.min_y, self.min_x, self.max_y, 
     134                self.max_x, self.max_y, self.max_x, self.min_y, 
     135                self.min_x, self.min_y) 
  • django/branches/gis/django/contrib/gis/gdal/feature.py

    r6421 r6436  
    88from django.contrib.gis.gdal.field import Field 
    99from django.contrib.gis.gdal.geometries import OGRGeometry, OGRGeomType 
     10from django.contrib.gis.gdal.srs import SpatialReference 
    1011 
    1112# For more information, see the OGR C API source code: 
     
    2223        self._fdefn = 0  
    2324        if not f: 
    24             raise OGRException, 'Cannot create OGR Feature, invalid pointer given.' 
     25            raise OGRException('Cannot create OGR Feature, invalid pointer given.') 
    2526        self._feat = f 
    2627        self._fdefn = lgdal.OGR_F_GetDefnRef(f) 
     
    3637        else: 
    3738            if index < 0 or index > self.num_fields: 
    38                 raise OGRIndexError, 'index out of range' 
     39                raise OGRIndexError('index out of range') 
    3940            i = index 
    4041        return Field(lgdal.OGR_F_GetFieldDefnRef(self._feat, c_int(i)), 
     
    8586    def geom(self): 
    8687        "Returns the OGR Geometry for this Feature." 
    87         # A clone is used, so destruction of the Geometry won't bork the Feature. 
    88         return OGRGeometry(lgdal.OGR_G_Clone(lgdal.OGR_F_GetGeometryRef(self._feat))) 
     88        # Retrieving the geometry pointer for the feature. 
     89        geom_ptr = lgdal.OGR_F_GetGeometryRef(self._feat) 
     90        if not geom_ptr: 
     91            raise OGRException('Cannot retrieve Geometry from the feature.') 
     92 
     93        # Attempting to retrieve the Spatial Reference for the geometry. 
     94        srs_ptr  = lgdal.OGR_G_GetSpatialReference(geom_ptr) 
     95        if srs_ptr: 
     96            srs = SpatialReference(srs_ptr, 'ogr') 
     97        else: 
     98            srs = None 
     99 
     100        # Geometry is cloned so the feature isn't invalidated. 
     101        return OGRGeometry(lgdal.OGR_G_Clone(geom_ptr), srs) 
    89102 
    90103    @property 
     
    106119        "Returns the index of the given field name." 
    107120        i = lgdal.OGR_F_GetFieldIndex(self._feat, c_char_p(field_name)) 
    108         if i < 0: raise OGRIndexError, 'invalid OFT field name given: "%s"' % field_name 
     121        if i < 0: raise OGRIndexError('invalid OFT field name given: "%s"' % field_name) 
    109122        return i 
    110123 
  • django/branches/gis/django/contrib/gis/gdal/field.py

    r5754 r6436  
    11from ctypes import string_at 
    2  
    32from django.contrib.gis.gdal.libgdal import lgdal 
    43from django.contrib.gis.gdal.error import OGRException 
     
    1716 
    1817        if not fld: 
    19             raise OGRException, 'Cannot create OGR Field, invalid pointer given.' 
     18            raise OGRException('Cannot create OGR Field, invalid pointer given.') 
    2019        self._fld = fld 
    2120        self._val = val 
     
    6564class OFTRealList(Field): pass 
    6665 
    67 class OFTString(Field): pass 
     66class OFTString(Field): 
     67    def __str__(self): 
     68        return '%s ("%s")' % (self.name, self.value) 
     69     
    6870class OFTStringList(Field): pass 
    6971class OFTWideString(Field): pass 
  • django/branches/gis/django/contrib/gis/gdal/geometries.py

    r6412 r6436  
    1 # types & ctypes 
    2 from types import IntType, StringType 
    3 from ctypes import byref, string_at, c_char_p, c_double, c_int, c_void_p 
    4  
    5 # Getting geodjango gdal prerequisites 
    6 from django.contrib.gis.gdal.libgdal import lgdal 
    7 from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope 
    8 from django.contrib.gis.gdal.error import check_err, OGRException, OGRIndexError 
    9 from django.contrib.gis.gdal.geomtype import OGRGeomType 
    10 from django.contrib.gis.gdal.srs import SpatialReference, CoordTransform 
    11  
    121""" 
    132  The OGRGeometry is a wrapper for using the OGR Geometry class 
    14     (see http://www.gdal.org/ogr/classOGRGeometry.html).  OGRGeometry 
    15     may be instantiated when reading geometries from OGR Data Sources 
    16     (e.g. SHP files), or when given OGC WKT (a string). 
     3   (see http://www.gdal.org/ogr/classOGRGeometry.html).  OGRGeometry 
     4   may be instantiated when reading geometries from OGR Data Sources 
     5   (e.g. SHP files), or when given OGC WKT (a string). 
    176 
    187  While the 'full' API is not present yet, the API is "pythonic" unlike 
    19     the traditional and "next-generation" OGR Python bindings.  One major 
    20     advantage OGR Geometries have over their GEOS counterparts is support 
    21     for spatial reference systems and their transformation. 
     8   the traditional and "next-generation" OGR Python bindings.  One major 
     9   advantage OGR Geometries have over their GEOS counterparts is support 
     10   for spatial reference systems and their transformation. 
    2211 
    2312  Example: 
     
    5039    True 
    5140""" 
     41# types & ctypes 
     42from types import IntType, StringType 
     43from ctypes import byref, string_at, c_char_p, c_double, c_int, c_void_p 
     44 
     45# Getting GDAL prerequisites 
     46from django.contrib.gis.gdal.libgdal import lgdal 
     47from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope 
     48from django.contrib.gis.gdal.error import check_err, OGRException, OGRIndexError 
     49from django.contrib.gis.gdal.geomtype import OGRGeomType 
     50from django.contrib.gis.gdal.srs import SpatialReference, CoordTransform 
    5251 
    5352# For more information, see the OGR C API source code: 
     
    7675    "Generally encapsulates an OGR geometry." 
    7776 
    78     def __init__(self, input, srs=False): 
     77    def __init__(self, geom_input, srs=None): 
    7978        "Initializes Geometry on either WKT or an OGR pointer as input." 
    8079 
    8180        self._g = 0 # Initially NULL 
    82         self._init_srs(srs) 
    83  
    84         if isinstance(input, StringType): 
     81 
     82        if isinstance(geom_input, StringType): 
    8583            # First, trying the input as WKT 
    86             buf = c_char_p(input) 
     84            buf = c_char_p(geom_input) 
    8785            g = c_void_p() 
    8886 
    8987            try: 
    90                 check_err(lgdal.OGR_G_CreateFromWkt(byref(buf), self._s._srs, byref(g))) 
    91             except OGRException, msg
     88                check_err(lgdal.OGR_G_CreateFromWkt(byref(buf), c_void_p(), byref(g))) 
     89            except OGRException
    9290                try: 
    93                     ogr_t = OGRGeomType(input) # Seeing if the input is a valid short-hand string 
     91                    # Seeing if the input is a valid short-hand string 
     92                    ogr_t = OGRGeomType(geom_input) 
    9493                    g = lgdal.OGR_G_CreateGeometry(ogr_t.num) 
    9594                except: 
    96                     raise OGRException, 'Could not initialize on WKT "%s"' % input 
    97         elif isinstance(input, OGRGeomType): 
    98             g = lgdal.OGR_G_CreateGeometry(input.num) 
    99             lgdal.OGR_G_AssignSpatialReference(g, self._s._srs) 
    100         elif isinstance(input, IntType): 
     95                    raise OGRException('Could not initialize OGR Geometry from: %s' % geom_input) 
     96        elif isinstance(geom_input, OGRGeomType): 
     97            g = lgdal.OGR_G_CreateGeometry(geom_input.num) 
     98        elif isinstance(geom_input, IntType): 
    10199            # OGR Pointer (integer) was the input 
    102             g = input 
    103         else: 
    104             raise OGRException, 'Type of input cannot be determined!' 
     100            g = geom_input 
     101        else: 
     102            raise OGRException('Type of input cannot be determined!') 
     103 
     104        # Assigning the SpatialReference object to the geometry, if valid. 
     105        if bool(srs): 
     106            if isinstance(srs, SpatialReference): 
     107                srs_ptr = srs._srs 
     108            else: 
     109                sr = SpatialReference(srs) 
     110                srs_ptr = sr._srs 
     111            lgdal.OGR_G_AssignSpatialReference(g, srs_ptr) 
    105112 
    106113        # Now checking the Geometry pointer before finishing initialization 
    107114        if not g: 
    108             raise OGRException, 'Cannot create OGR Geometry from input: %s' % str(input
     115            raise OGRException('Cannot create OGR Geometry from input: %s' % str(geom_input)
    109116        self._g = g 
    110117 
     
    115122        "Deletes this Geometry." 
    116123        if self._g: lgdal.OGR_G_DestroyGeometry(self._g) 
    117  
    118     def _init_srs(self, srs): 
    119         # Getting the spatial 
    120         if not isinstance(srs, SpatialReference): 
    121             self._s = SpatialReference() # creating an empty spatial reference 
    122         else: 
    123             self._s = srs.clone() # cloning the given spatial reference 
    124124 
    125125    ### Geometry set-like operations ### 
     
    185185    def srs(self): 
    186186        "Returns the Spatial Reference for this Geometry." 
    187         return SpatialReference(lgdal.OSRClone(lgdal.OGR_G_GetSpatialReference(self._g)), 'ogr') 
     187        srs_ptr = lgdal.OGR_G_GetSpatialReference(self._g) 
     188        if srs_ptr: 
     189            return SpatialReference(lgdal.OSRClone(srs_ptr), 'ogr') 
     190        else: 
     191            return None 
    188192 
    189193    @property 
     
    196200        "Returns the Name of this Geometry." 
    197201        return string_at(lgdal.OGR_G_GetGeometryName(self._g)) 
    198  
    199     @property 
    200     def wkt(self): 
    201         "Returns the WKT form of the Geometry." 
    202         buf = c_char_p() 
    203         check_err(lgdal.OGR_G_ExportToWkt(self._g, byref(buf))) 
    204         return string_at(buf) 
    205202 
    206203    @property 
     
    215212        lgdal.OGR_G_GetEnvelope(self._g, byref(env)) 
    216213        return Envelope(env) 
     214 
     215    #### Output Methods #### 
     216    @property 
     217    def gml(self): 
     218        "Returns the GML representation of the Geometry." 
     219        buf = c_char_p() 
     220        check_err(lgdal.OGR_G_ExportToGML(self._g, byref(buf))) 
     221        return string_at(buf) 
     222 
     223    @property 
     224    def wkt(self): 
     225        "Returns the WKT representation of the Geometry." 
     226        buf = c_char_p() 
     227        check_err(lgdal.OGR_G_ExportToWkt(self._g, byref(buf))) 
     228        return string_at(buf) 
    217229     
    218230    #### Geometry Methods #### 
     
    231243        "Transforms this Geometry with the given CoordTransform object." 
    232244        if not isinstance(coord_trans, CoordTransform): 
    233             raise OGRException, 'CoordTransform object required for transform.' 
     245            raise OGRException('CoordTransform object required for transform.') 
    234246        check_err(lgdal.OGR_G_Transform(self._g, coord_trans._ct)) 
    235247 
     
    237249        "Transforms this Geometry with the given SpatialReference." 
    238250        if not isinstance(srs, SpatialReference): 
    239             raise OGRException, 'SpatialReference object required for transform_to.' 
     251            raise OGRException('SpatialReference object required for transform_to.') 
    240252        check_err(lgdal.OGR_G_TransformTo(self._g, srs._srs)) 
    241253 
     
    245257        the other geometry to perform the operation on.""" 
    246258        if not isinstance(other, OGRGeometry): 
    247             raise OGRException, 'Must use another OGRGeometry object for topology operations!' 
     259            raise OGRException('Must use another OGRGeometry object for topology operations!') 
    248260 
    249261        # Calling the passed-in topology function with the other geometry 
     
    369381                return (x.value, y.value, z.value) 
    370382        else: 
    371             raise OGRIndexError, 'index out of range: %s' % str(index
     383            raise OGRIndexError('index out of range: %s' % str(index)
    372384 
    373385    def __iter__(self): 
     
    402414        "Gets the ring at the specified index." 
    403415        if index < 0 or index >= self.geom_count: 
    404             raise OGRIndexError, 'index out of range: %s' % str(index
    405         else: 
    406             return OGRGeometry(lgdal.OGR_G_Clone(lgdal.OGR_G_GetGeometryRef(self._g, c_int(index)))
     416            raise OGRIndexError('index out of range: %s' % str(index)
     417        else: 
     418            return OGRGeometry(lgdal.OGR_G_Clone(lgdal.OGR_G_GetGeometryRef(self._g, c_int(index))), self.srs
    407419 
    408420    # Polygon Properties 
     
    438450        "Gets the Geometry at the specified index." 
    439451        if index < 0 or index >= self.geom_count: 
    440             raise OGRIndexError, 'index out of range: %s' % str(index
    441         else: 
    442             return OGRGeometry(lgdal.OGR_G_Clone(lgdal.OGR_G_GetGeometryRef(self._g, c_int(index)))
     452            raise OGRIndexError('index out of range: %s' % str(index)
     453        else: 
     454            return OGRGeometry(lgdal.OGR_G_Clone(lgdal.OGR_G_GetGeometryRef(self._g, c_int(index))), self.srs
    443455         
    444456    def __iter__(self): 
     
    459471            ptr = tmp._g 
    460472        else: 
    461             raise OGRException, 'Must add an OGRGeometry.' 
     473            raise OGRException('Must add an OGRGeometry.') 
    462474        lgdal.OGR_G_AddGeometry(self._g, ptr) 
    463475 
  • django/branches/gis/django/contrib/gis/gdal/geomtype.py

    r5761 r6436  
    1212    __ogr_int = [1, 2, 3, 4, 5, 6, 7, 101] 
    1313 
    14     def __init__(self, input): 
     14    def __init__(self, type_input): 
    1515        "Figures out the correct OGR Type based upon the input." 
    16         if isinstance(input, OGRGeomType): 
    17             self._index = input._index 
    18         elif isinstance(input, StringType): 
    19             idx = self._has_str(self.__ogr_str, input) 
     16        if isinstance(type_input, OGRGeomType): 
     17            self._index = type_input._index 
     18        elif isinstance(type_input, StringType): 
     19            idx = self._has_str(self.__ogr_str, type_input) 
    2020            if idx == None: 
    21                 raise OGRException, 'Invalid OGR String Type "%s"' % input 
     21                raise OGRException('Invalid OGR String Type "%s"' % type_input) 
    2222            self._index = idx 
    23         elif isinstance(input, int): 
    24             if not input in self.__ogr_int: 
    25                 raise OGRException, 'Invalid OGR Integer Type: %d' % input 
    26             self._index =  self.__ogr_int.index(input) 
     23        elif isinstance(type_input, int): 
     24            if not type_input in self.__ogr_int: 
     25                raise OGRException('Invalid OGR Integer Type: %d' % type_input) 
     26            self._index =  self.__ogr_int.index(type_input) 
    2727        else: 
    28             raise TypeError, 'Invalid OGR Input type given!' 
     28            raise TypeError('Invalid OGR Input type given!') 
    2929 
    3030    def __str__(self): 
     
    4545            return self.__ogr_int.index(other) == self._index 
    4646        else: 
    47             raise TypeError, 'Cannot compare with type: %s' % str(type(other)) 
     47            raise TypeError('Cannot compare with type: %s' % str(type(other))) 
    4848 
    4949    def _has_str(self, arr, s): 
  • django/branches/gis/django/contrib/gis/gdal/__init__.py

    r6412 r6436  
     1""" 
     2 This module houses ctypes interfaces for GDAL objects.  The following GDAL 
     3  objects are supported: 
     4 
     5 CoordTransform: Used for coordinate transformations from one spatial 
     6  reference system to another. 
     7 
     8 Driver: Wraps an OGR data source driver. 
     9   
     10 DataSource: Wrapper for the OGR data source object, supports 
     11  OGR-supported data sources. 
     12 
     13 Envelope: A ctypes structure for bounding boxes (GDAL library 
     14  not required). 
     15 
     16 OGRGeometry: Layer for accessing OGR Geometry objects. 
     17 
     18 OGRGeomType: A class for representing the different OGR Geometry 
     19  types (GDAL library not required). 
     20 
     21 SpatialReference: Represents OSR Spatial Reference objects. 
     22""" 
     23# Attempting to import objects that depend on the GDAL library.  The 
     24#  HAS_GDAL flag will be set to True if the library is present on 
     25#  the system. 
    126try: 
    227    from django.contrib.gis.gdal.driver import Driver 
    3     from django.contrib.gis.gdal.envelope import Envelope 
    428    from django.contrib.gis.gdal.datasource import DataSource 
    529    from django.contrib.gis.gdal.srs import SpatialReference, CoordTransform 
    630    from django.contrib.gis.gdal.geometries import OGRGeometry 
    7     from django.contrib.gis.gdal.geomtype import OGRGeomType 
    8     from django.contrib.gis.gdal.error import check_err, OGRException, SRSException 
    931    HAS_GDAL = True 
    1032except: 
    1133    HAS_GDAL = False 
    1234 
     35# The envelope, error, and geomtype modules do not actually require the 
     36#  GDAL library. 
     37from django.contrib.gis.gdal.envelope import Envelope 
     38from django.contrib.gis.gdal.error import check_err, OGRException, OGRIndexError, SRSException 
     39from django.contrib.gis.gdal.geomtype import OGRGeomType 
  • django/branches/gis/django/contrib/gis/gdal/srs.py

    r6412 r6436  
    8080 
    8181    #### Python 'magic' routines #### 
    82     def __init__(self, input='', srs_type='wkt'): 
     82    def __init__(self, srs_input='', srs_type='wkt'): 
    8383        "Creates a spatial reference object from the given OGC Well Known Text (WKT)." 
    8484 
     
    8888        buf = c_char_p('') 
    8989 
    90         if isinstance(input, UnicodeType): 
    91             input = input.encode('ascii') 
    92  
    93         if isinstance(input, StringType): 
     90        # Encoding to ASCII if unicode passed in. 
     91        if isinstance(srs_input, UnicodeType): 
     92            srs_input = srs_input.encode('ascii') 
     93 
     94        if isinstance(srs_input, StringType): 
    9495            # Is this an EPSG well known name? 
    95             m = self._epsg_regex.match(input) 
     96            m = self._epsg_regex.match(srs_input) 
    9697            if m: 
    9798                srs_type = 'epsg' 
    98                 input = int(m.group('epsg')) 
     99                srs_input = int(m.group('epsg')) 
    99100            # Is this a short-hand well known name? 
    100             elif input in self._well_known: 
     101            elif srs_input in self._well_known: 
    101102                srs_type = 'epsg' 
    102                 input = self._well_known[input] 
     103                srs_input = self._well_known[srs_input] 
    103104            elif srs_type == 'proj': 
    104105                pass 
    105106            else: 
    106                 buf = c_char_p(input) 
    107         elif isinstance(input, int): 
     107                buf = c_char_p(srs_input) 
     108        elif isinstance(srs_input, int): 
    108109            if srs_type == 'wkt': srs_type = 'epsg' # want to try epsg if only integer provided 
    109110            if srs_type not in ('epsg', 'ogr'):  
    110                 raise SRSException, 'Integer input requires SRS type of "ogr" or "epsg".' 
     111                raise SRSException('Integer input requires SRS type of "ogr" or "epsg".') 
    111112        else: 
    112             raise TypeError, 'Invalid SRS type "%s"' % srs_type 
     113            raise TypeError('Invalid SRS type "%s"' % srs_type) 
    113114 
    114115        # Calling OSRNewSpatialReference with the string buffer. 
    115116        if srs_type == 'ogr': 
    116             srs = input # Input is OGR pointer 
     117            srs = srs_input # SRS input is OGR pointer 
    117118        else: 
    118119            srs = lgdal.OSRNewSpatialReference(buf) 
     
    120121        # If the pointer is NULL, throw an exception. 
    121122        if not srs: 
    122             raise SRSException, 'Could not create spatial reference from WKT! (%s)' % input 
     123            raise SRSException('Could not create spatial reference from: %s' % srs_input) 
    123124        else: 
    124125            self._srs = srs 
    125126 
    126127        # Post-processing if in PROJ.4 or EPSG formats. 
    127         if srs_type == 'proj': self.import_proj(input) 
    128         elif srs_type == 'epsg': self.import_epsg(input) 
     128        if srs_type == 'proj': self.import_proj(srs_input) 
     129        elif srs_type == 'epsg': self.import_epsg(srs_input) 
    129130 
    130131    def __del__(self): 
     
    142143        else: 
    143144            return self.attr_value(target) 
     145 
     146    def __nonzero__(self): 
     147        "Returns True if this SpatialReference object is valid." 
     148        try: 
     149            self.validate() 
     150            return True 
     151        except OGRException: 
     152            return False 
    144153 
    145154    def __str__(self): 
     
    189198        elif self.local: return self.attr_value('LOCAL_CS') 
    190199        else: return None 
    191      
     200 
     201    @property 
     202    def srid(self): 
     203        """ 
     204        Returns the EPSG SRID of this Spatial Reference, will be None if 
     205        if undefined. 
     206        """ 
     207        return self.srs['AUTHORITY', 1] 
     208         
    192209    #### Unit Properties #### 
    193210    def _cache_linear(self): 
     
    346363        self._ct = 0 # Initially NULL  
    347364        if not isinstance(source, SpatialReference) or not isinstance(target, SpatialReference): 
    348             raise SRSException, 'source and target must be of type SpatialReference' 
     365            raise SRSException('source and target must be of type SpatialReference') 
    349366        ct = lgdal.OCTNewCoordinateTransformation(source._srs, target._srs) 
    350367        if not ct: 
    351             raise SRSException, 'could not intialize CoordTransform object' 
     368            raise SRSException('could not intialize CoordTransform object') 
    352369        self._ct = ct 
    353370        self._srs1_name = source.name 
  • django/branches/gis/django/contrib/gis/tests/__init__.py

    r6413 r6436  
    1414        'test_gdal_driver', 
    1515        'test_gdal_ds', 
     16        'test_gdal_envelope', 
    1617        'test_gdal_geom', 
    1718        'test_gdal_srs', 
  • django/branches/gis/django/contrib/gis/tests/test_gdal_ds.py

    r5749 r6436  
    11import os, os.path, unittest 
    2 from django.contrib.gis.gdal import DataSource, OGRException 
    3 from django.contrib.gis.gdal.envelope import Envelope 
     2from django.contrib.gis.gdal import DataSource, Envelope, OGRException, OGRIndexError 
    43from django.contrib.gis.gdal.field import OFTReal, OFTInteger, OFTString 
    54 
     
    4948            try: 
    5049                ds[len(ds)] 
    51             except IndexError: 
     50            except OGRIndexError: 
    5251                pass 
    5352            else: 
     
    107106                        # Asserting the string representation, and making sure we get 
    108107                        #  the proper OGR Field instance. 
    109                         self.assertEqual('%s (%s)' % (k, fld.value), str(fld)) 
     108                        if isinstance(fld, OFTString): fmt = '%s ("%s")' 
     109                        else: fmt = '%s (%s)' 
     110                        self.assertEqual(fmt % (k, fld.value), str(fld)) 
    110111                        self.assertEqual(True, isinstance(fld, v)) 
    111112 
     
    137138def run(verbosity=2): 
    138139    unittest.TextTestRunner(verbosity=verbosity).run(suite()) 
    139  
    140          
  • django/branches/gis/django/contrib/gis/tests/test_gdal_geom.py

    r6237 r6436  
    11import unittest 
    2 from django.contrib.gis.gdal import OGRGeometry, OGRGeomType, OGRException 
     2from django.contrib.gis.gdal import OGRGeometry, OGRGeomType, OGRException, SpatialReference 
    33from geometries import * 
    44 
     
    131131                self.assertEqual(mp.num_geom, len(mpoly)) 
    132132 
     133    def test09_srs(self): 
     134        "Testing OGR Geometries with Spatial Reference objects." 
     135        for mp in multipolygons: 
     136            sr = SpatialReference('WGS84') 
     137            mpoly = OGRGeometry(mp.wkt, sr) 
     138            self.assertEqual(sr.wkt, mpoly.srs.wkt) 
     139            for poly in mpoly: 
     140                self.assertEqual(sr.wkt, poly.srs.wkt) 
     141                for ring in poly: 
     142                    self.assertEqual(sr.wkt, ring.srs.wkt) 
     143             
     144 
    133145def suite(): 
    134146    s = unittest.TestSuite()