datasource.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. """
  2. DataSource is a wrapper for the OGR Data Source object, which provides
  3. an interface for reading vector geometry data from many different file
  4. formats (including ESRI shapefiles).
  5. When instantiating a DataSource object, use the filename of a
  6. GDAL-supported data source. For example, a SHP file or a
  7. TIGER/Line file from the government.
  8. The ds_driver keyword is used internally when a ctypes pointer
  9. is passed in directly.
  10. Example:
  11. ds = DataSource('/home/foo/bar.shp')
  12. for layer in ds:
  13. for feature in layer:
  14. # Getting the geometry for the feature.
  15. g = feature.geom
  16. # Getting the 'description' field for the feature.
  17. desc = feature['description']
  18. # We can also increment through all of the fields
  19. # attached to this feature.
  20. for field in feature:
  21. # Get the name of the field (e.g. 'description')
  22. nm = field.name
  23. # Get the type (integer) of the field, e.g. 0 => OFTInteger
  24. t = field.type
  25. # Returns the value the field; OFTIntegers return ints,
  26. # OFTReal returns floats, all else returns string.
  27. val = field.value
  28. """
  29. from ctypes import byref
  30. from pathlib import Path
  31. from django.contrib.gis.gdal.base import GDALBase
  32. from django.contrib.gis.gdal.driver import Driver
  33. from django.contrib.gis.gdal.error import GDALException
  34. from django.contrib.gis.gdal.layer import Layer
  35. from django.contrib.gis.gdal.prototypes import ds as capi
  36. from django.utils.encoding import force_bytes, force_str
  37. # For more information, see the OGR C API documentation:
  38. # https://gdal.org/api/vector_c_api.html
  39. #
  40. # The OGR_DS_* routines are relevant here.
  41. class DataSource(GDALBase):
  42. "Wraps an OGR Data Source object."
  43. destructor = capi.destroy_ds
  44. def __init__(self, ds_input, ds_driver=False, write=False, encoding="utf-8"):
  45. # The write flag.
  46. if write:
  47. self._write = 1
  48. else:
  49. self._write = 0
  50. # See also https://gdal.org/development/rfc/rfc23_ogr_unicode.html
  51. self.encoding = encoding
  52. Driver.ensure_registered()
  53. if isinstance(ds_input, (str, Path)):
  54. # The data source driver is a void pointer.
  55. ds_driver = Driver.ptr_type()
  56. try:
  57. # OGROpen will auto-detect the data source type.
  58. ds = capi.open_ds(force_bytes(ds_input), self._write, byref(ds_driver))
  59. except GDALException:
  60. # Making the error message more clear rather than something
  61. # like "Invalid pointer returned from OGROpen".
  62. raise GDALException('Could not open the datasource at "%s"' % ds_input)
  63. elif isinstance(ds_input, self.ptr_type) and isinstance(
  64. ds_driver, Driver.ptr_type
  65. ):
  66. ds = ds_input
  67. else:
  68. raise GDALException("Invalid data source input type: %s" % type(ds_input))
  69. if ds:
  70. self.ptr = ds
  71. self.driver = Driver(ds_driver)
  72. else:
  73. # Raise an exception if the returned pointer is NULL
  74. raise GDALException('Invalid data source file "%s"' % ds_input)
  75. def __getitem__(self, index):
  76. "Allows use of the index [] operator to get a layer at the index."
  77. if isinstance(index, str):
  78. try:
  79. layer = capi.get_layer_by_name(self.ptr, force_bytes(index))
  80. except GDALException:
  81. raise IndexError("Invalid OGR layer name given: %s." % index)
  82. elif isinstance(index, int):
  83. if 0 <= index < self.layer_count:
  84. layer = capi.get_layer(self._ptr, index)
  85. else:
  86. raise IndexError(
  87. "Index out of range when accessing layers in a datasource: %s."
  88. % index
  89. )
  90. else:
  91. raise TypeError("Invalid index type: %s" % type(index))
  92. return Layer(layer, self)
  93. def __len__(self):
  94. "Return the number of layers within the data source."
  95. return self.layer_count
  96. def __str__(self):
  97. "Return OGR GetName and Driver for the Data Source."
  98. return "%s (%s)" % (self.name, self.driver)
  99. @property
  100. def layer_count(self):
  101. "Return the number of layers in the data source."
  102. return capi.get_layer_count(self._ptr)
  103. @property
  104. def name(self):
  105. "Return the name of the data source."
  106. name = capi.get_ds_name(self._ptr)
  107. return force_str(name, self.encoding, strings_only=True)