PageRenderTime 114ms CodeModel.GetById 108ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/django/contrib/gis/db/models/proxy.py

https://code.google.com/p/mango-py/
Python | 64 lines | 27 code | 7 blank | 30 comment | 8 complexity | cde30ceb2ec8dbee7c55af299bb2fb43 MD5 | raw file
 1"""
 2The GeometryProxy object, allows for lazy-geometries.  The proxy uses
 3Python descriptors for instantiating and setting Geometry objects
 4corresponding to geographic model fields.
 5
 6Thanks to Robert Coup for providing this functionality (see #4322).
 7"""
 8
 9class GeometryProxy(object):
10    def __init__(self, klass, field):
11        """
12        Proxy initializes on the given Geometry class (not an instance) and
13        the GeometryField.
14        """
15        self._field = field
16        self._klass = klass
17
18    def __get__(self, obj, type=None):
19        """
20        This accessor retrieves the geometry, initializing it using the geometry
21        class specified during initialization and the HEXEWKB value of the field.
22        Currently, only GEOS or OGR geometries are supported.
23        """
24        if obj is None:
25            # Accessed on a class, not an instance
26            return self
27
28        # Getting the value of the field.
29        geom_value = obj.__dict__[self._field.attname]
30
31        if isinstance(geom_value, self._klass):
32            geom = geom_value
33        elif (geom_value is None) or (geom_value==''):
34            geom = None
35        else:
36            # Otherwise, a Geometry object is built using the field's contents,
37            # and the model's corresponding attribute is set.
38            geom = self._klass(geom_value)
39            setattr(obj, self._field.attname, geom)
40        return geom
41
42    def __set__(self, obj, value):
43        """
44        This accessor sets the proxied geometry with the geometry class
45        specified during initialization.  Values of None, HEXEWKB, or WKT may
46        be used to set the geometry as well.
47        """
48        # The OGC Geometry type of the field.
49        gtype = self._field.geom_type
50
51        # The geometry type must match that of the field -- unless the
52        # general GeometryField is used.
53        if isinstance(value, self._klass) and (str(value.geom_type).upper() == gtype or gtype == 'GEOMETRY'):
54            # Assigning the SRID to the geometry.
55            if value.srid is None: value.srid = self._field.srid
56        elif value is None or isinstance(value, (basestring, buffer)):
57            # Set with None, WKT, HEX, or WKB
58            pass
59        else:
60            raise TypeError('cannot set %s GeometryProxy with value of type: %s' % (obj.__class__.__name__, type(value)))
61
62        # Setting the objects dictionary with the value, and returning.
63        obj.__dict__[self._field.attname] = value
64        return value