driver.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # prerequisites imports
  2. from ctypes import c_void_p
  3. from django.contrib.gis.gdal.base import GDALBase
  4. from django.contrib.gis.gdal.error import OGRException
  5. from django.contrib.gis.gdal.prototypes import ds as capi
  6. from django.utils import six
  7. from django.utils.encoding import force_bytes
  8. # For more information, see the OGR C API source code:
  9. # http://www.gdal.org/ogr/ogr__api_8h.html
  10. #
  11. # The OGR_Dr_* routines are relevant here.
  12. class Driver(GDALBase):
  13. "Wraps an OGR Data Source Driver."
  14. # Case-insensitive aliases for OGR Drivers.
  15. _alias = {'esri': 'ESRI Shapefile',
  16. 'shp': 'ESRI Shapefile',
  17. 'shape': 'ESRI Shapefile',
  18. 'tiger': 'TIGER',
  19. 'tiger/line': 'TIGER',
  20. }
  21. def __init__(self, dr_input):
  22. "Initializes an OGR driver on either a string or integer input."
  23. if isinstance(dr_input, six.string_types):
  24. # If a string name of the driver was passed in
  25. self._register()
  26. # Checking the alias dictionary (case-insensitive) to see if an alias
  27. # exists for the given driver.
  28. if dr_input.lower() in self._alias:
  29. name = self._alias[dr_input.lower()]
  30. else:
  31. name = dr_input
  32. # Attempting to get the OGR driver by the string name.
  33. dr = capi.get_driver_by_name(force_bytes(name))
  34. elif isinstance(dr_input, int):
  35. self._register()
  36. dr = capi.get_driver(dr_input)
  37. elif isinstance(dr_input, c_void_p):
  38. dr = dr_input
  39. else:
  40. raise OGRException('Unrecognized input type for OGR Driver: %s' % str(type(dr_input)))
  41. # Making sure we get a valid pointer to the OGR Driver
  42. if not dr:
  43. raise OGRException('Could not initialize OGR Driver on input: %s' % str(dr_input))
  44. self.ptr = dr
  45. def __str__(self):
  46. "Returns the string name of the OGR Driver."
  47. return capi.get_driver_name(self.ptr)
  48. def _register(self):
  49. "Attempts to register all the data source drivers."
  50. # Only register all if the driver count is 0 (or else all drivers
  51. # will be registered over and over again)
  52. if not self.driver_count:
  53. capi.register_all()
  54. # Driver properties
  55. @property
  56. def driver_count(self):
  57. "Returns the number of OGR data source drivers registered."
  58. return capi.get_driver_count()