Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

adapter.py 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """
  2. This object provides quoting for GEOS geometries into PostgreSQL/PostGIS.
  3. """
  4. from psycopg2 import Binary
  5. from psycopg2.extensions import ISQLQuote
  6. from django.contrib.gis.db.backends.postgis.pgraster import to_pgraster
  7. from django.contrib.gis.geos import GEOSGeometry
  8. class PostGISAdapter:
  9. def __init__(self, obj, geography=False):
  10. """
  11. Initialize on the spatial object.
  12. """
  13. self.is_geometry = isinstance(obj, (GEOSGeometry, PostGISAdapter))
  14. # Getting the WKB (in string form, to allow easy pickling of
  15. # the adaptor) and the SRID from the geometry or raster.
  16. if self.is_geometry:
  17. self.ewkb = bytes(obj.ewkb)
  18. self._adapter = Binary(self.ewkb)
  19. else:
  20. self.ewkb = to_pgraster(obj)
  21. self.srid = obj.srid
  22. self.geography = geography
  23. def __conform__(self, proto):
  24. """Does the given protocol conform to what Psycopg2 expects?"""
  25. if proto == ISQLQuote:
  26. return self
  27. else:
  28. raise Exception('Error implementing psycopg2 protocol. Is psycopg2 installed?')
  29. def __eq__(self, other):
  30. return isinstance(other, PostGISAdapter) and self.ewkb == other.ewkb
  31. def __hash__(self):
  32. return hash(self.ewkb)
  33. def __str__(self):
  34. return self.getquoted()
  35. def prepare(self, conn):
  36. """
  37. This method allows escaping the binary in the style required by the
  38. server's `standard_conforming_string` setting.
  39. """
  40. if self.is_geometry:
  41. self._adapter.prepare(conn)
  42. def getquoted(self):
  43. """
  44. Return a properly quoted string for use in PostgreSQL/PostGIS.
  45. """
  46. if self.is_geometry:
  47. # Psycopg will figure out whether to use E'\\000' or '\000'.
  48. return '%s(%s)' % (
  49. 'ST_GeogFromWKB' if self.geography else 'ST_GeomFromEWKB',
  50. self._adapter.getquoted().decode()
  51. )
  52. else:
  53. # For rasters, add explicit type cast to WKB string.
  54. return "'%s'::raster" % self.ewkb