adapter.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """
  2. This object provides quoting for GEOS geometries into PostgreSQL/PostGIS.
  3. """
  4. from __future__ import unicode_literals
  5. from psycopg2 import Binary
  6. from psycopg2.extensions import ISQLQuote
  7. class PostGISAdapter(object):
  8. def __init__(self, geom):
  9. "Initializes on the geometry."
  10. # Getting the WKB (in string form, to allow easy pickling of
  11. # the adaptor) and the SRID from the geometry.
  12. self.ewkb = bytes(geom.ewkb)
  13. self.srid = geom.srid
  14. self._adapter = Binary(self.ewkb)
  15. def __conform__(self, proto):
  16. # Does the given protocol conform to what Psycopg2 expects?
  17. if proto == ISQLQuote:
  18. return self
  19. else:
  20. raise Exception('Error implementing psycopg2 protocol. Is psycopg2 installed?')
  21. def __eq__(self, other):
  22. if not isinstance(other, PostGISAdapter):
  23. return False
  24. return (self.ewkb == other.ewkb) and (self.srid == other.srid)
  25. def __str__(self):
  26. return self.getquoted()
  27. def prepare(self, conn):
  28. """
  29. This method allows escaping the binary in the style required by the
  30. server's `standard_conforming_string` setting.
  31. """
  32. self._adapter.prepare(conn)
  33. def getquoted(self):
  34. "Returns a properly quoted string for use in PostgreSQL/PostGIS."
  35. # psycopg will figure out whether to use E'\\000' or '\000'
  36. return str('ST_GeomFromEWKB(%s)' % self._adapter.getquoted().decode())
  37. def prepare_database_save(self, unused):
  38. return self