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