ogrinfo.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. """
  2. This module includes some utility functions for inspecting the layout
  3. of a GDAL data source -- the functionality is analogous to the output
  4. produced by the `ogrinfo` utility.
  5. """
  6. from django.contrib.gis.gdal import DataSource
  7. from django.contrib.gis.gdal.geometries import GEO_CLASSES
  8. def ogrinfo(data_source, num_features=10):
  9. """
  10. Walk the available layers in the supplied `data_source`, displaying
  11. the fields for the first `num_features` features.
  12. """
  13. # Checking the parameters.
  14. if isinstance(data_source, str):
  15. data_source = DataSource(data_source)
  16. elif isinstance(data_source, DataSource):
  17. pass
  18. else:
  19. raise Exception(
  20. "Data source parameter must be a string or a DataSource object."
  21. )
  22. for i, layer in enumerate(data_source):
  23. print("data source : %s" % data_source.name)
  24. print("==== layer %s" % i)
  25. print(" shape type: %s" % GEO_CLASSES[layer.geom_type.num].__name__)
  26. print(" # features: %s" % len(layer))
  27. print(" srs: %s" % layer.srs)
  28. extent_tup = layer.extent.tuple
  29. print(" extent: %s - %s" % (extent_tup[0:2], extent_tup[2:4]))
  30. print("Displaying the first %s features ====" % num_features)
  31. width = max(*map(len, layer.fields))
  32. fmt = " %%%ss: %%s" % width
  33. for j, feature in enumerate(layer[:num_features]):
  34. print("=== Feature %s" % j)
  35. for fld_name in layer.fields:
  36. type_name = feature[fld_name].type_name
  37. output = fmt % (fld_name, type_name)
  38. val = feature.get(fld_name)
  39. if val:
  40. if isinstance(val, str):
  41. val_fmt = ' ("%s")'
  42. else:
  43. val_fmt = " (%s)"
  44. output += val_fmt % val
  45. else:
  46. output += " (None)"
  47. print(output)