factory.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. from django.contrib.gis import memoryview
  2. from django.contrib.gis.geos.geometry import GEOSGeometry, wkt_regex, hex_regex
  3. from django.utils import six
  4. def fromfile(file_h):
  5. """
  6. Given a string file name, returns a GEOSGeometry. The file may contain WKB,
  7. WKT, or HEX.
  8. """
  9. # If given a file name, get a real handle.
  10. if isinstance(file_h, six.string_types):
  11. with open(file_h, 'rb') as file_h:
  12. buf = file_h.read()
  13. else:
  14. buf = file_h.read()
  15. # If we get WKB need to wrap in memoryview(), so run through regexes.
  16. if isinstance(buf, bytes):
  17. try:
  18. decoded = buf.decode()
  19. if wkt_regex.match(decoded) or hex_regex.match(decoded):
  20. return GEOSGeometry(decoded)
  21. except UnicodeDecodeError:
  22. pass
  23. else:
  24. return GEOSGeometry(buf)
  25. return GEOSGeometry(memoryview(buf))
  26. def fromstr(string, **kwargs):
  27. "Given a string value, returns a GEOSGeometry object."
  28. return GEOSGeometry(string, **kwargs)