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.

datasource.py 4.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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 django.contrib.gis.gdal.base import GDALBase
  31. from django.contrib.gis.gdal.driver import Driver
  32. from django.contrib.gis.gdal.error import GDALException
  33. from django.contrib.gis.gdal.layer import Layer
  34. from django.contrib.gis.gdal.prototypes import ds as capi
  35. from django.utils.encoding import force_bytes, force_text
  36. # For more information, see the OGR C API source code:
  37. # https://www.gdal.org/ogr__api_8h.html
  38. #
  39. # The OGR_DS_* routines are relevant here.
  40. class DataSource(GDALBase):
  41. "Wraps an OGR Data Source object."
  42. destructor = capi.destroy_ds
  43. def __init__(self, ds_input, ds_driver=False, write=False, encoding='utf-8'):
  44. # The write flag.
  45. if write:
  46. self._write = 1
  47. else:
  48. self._write = 0
  49. # See also https://trac.osgeo.org/gdal/wiki/rfc23_ogr_unicode
  50. self.encoding = encoding
  51. Driver.ensure_registered()
  52. if isinstance(ds_input, str):
  53. # The data source driver is a void pointer.
  54. ds_driver = Driver.ptr_type()
  55. try:
  56. # OGROpen will auto-detect the data source type.
  57. ds = capi.open_ds(force_bytes(ds_input), self._write, byref(ds_driver))
  58. except GDALException:
  59. # Making the error message more clear rather than something
  60. # like "Invalid pointer returned from OGROpen".
  61. raise GDALException('Could not open the datasource at "%s"' % ds_input)
  62. elif isinstance(ds_input, self.ptr_type) and isinstance(ds_driver, Driver.ptr_type):
  63. ds = ds_input
  64. else:
  65. raise GDALException('Invalid data source input type: %s' % type(ds_input))
  66. if ds:
  67. self.ptr = ds
  68. self.driver = Driver(ds_driver)
  69. else:
  70. # Raise an exception if the returned pointer is NULL
  71. raise GDALException('Invalid data source file "%s"' % ds_input)
  72. def __getitem__(self, index):
  73. "Allows use of the index [] operator to get a layer at the index."
  74. if isinstance(index, str):
  75. try:
  76. layer = capi.get_layer_by_name(self.ptr, force_bytes(index))
  77. except GDALException:
  78. raise IndexError('Invalid OGR layer name given: %s.' % index)
  79. elif isinstance(index, int):
  80. if 0 <= index < self.layer_count:
  81. layer = capi.get_layer(self._ptr, index)
  82. else:
  83. raise IndexError('Index out of range when accessing layers in a datasource: %s.' % index)
  84. else:
  85. raise TypeError('Invalid index type: %s' % type(index))
  86. return Layer(layer, self)
  87. def __len__(self):
  88. "Return the number of layers within the data source."
  89. return self.layer_count
  90. def __str__(self):
  91. "Return OGR GetName and Driver for the Data Source."
  92. return '%s (%s)' % (self.name, self.driver)
  93. @property
  94. def layer_count(self):
  95. "Return the number of layers in the data source."
  96. return capi.get_layer_count(self._ptr)
  97. @property
  98. def name(self):
  99. "Return the name of the data source."
  100. name = capi.get_ds_name(self._ptr)
  101. return force_text(name, self.encoding, strings_only=True)