layermapping.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. # LayerMapping -- A Django Model/OGR Layer Mapping Utility
  2. """
  3. The LayerMapping class provides a way to map the contents of OGR
  4. vector files (e.g. SHP files) to Geographic-enabled Django models.
  5. For more information, please consult the GeoDjango documentation:
  6. https://docs.djangoproject.com/en/dev/ref/contrib/gis/layermapping/
  7. """
  8. import sys
  9. from decimal import Decimal, InvalidOperation as DecimalInvalidOperation
  10. from django.contrib.gis.db.models import GeometryField
  11. from django.contrib.gis.gdal import (
  12. CoordTransform, DataSource, GDALException, OGRGeometry, OGRGeomType,
  13. SpatialReference,
  14. )
  15. from django.contrib.gis.gdal.field import (
  16. OFTDate, OFTDateTime, OFTInteger, OFTInteger64, OFTReal, OFTString,
  17. OFTTime,
  18. )
  19. from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist
  20. from django.db import connections, models, router, transaction
  21. from django.utils.encoding import force_str
  22. # LayerMapping exceptions.
  23. class LayerMapError(Exception):
  24. pass
  25. class InvalidString(LayerMapError):
  26. pass
  27. class InvalidDecimal(LayerMapError):
  28. pass
  29. class InvalidInteger(LayerMapError):
  30. pass
  31. class MissingForeignKey(LayerMapError):
  32. pass
  33. class LayerMapping:
  34. "A class that maps OGR Layers to GeoDjango Models."
  35. # Acceptable 'base' types for a multi-geometry type.
  36. MULTI_TYPES = {
  37. 1: OGRGeomType('MultiPoint'),
  38. 2: OGRGeomType('MultiLineString'),
  39. 3: OGRGeomType('MultiPolygon'),
  40. OGRGeomType('Point25D').num: OGRGeomType('MultiPoint25D'),
  41. OGRGeomType('LineString25D').num: OGRGeomType('MultiLineString25D'),
  42. OGRGeomType('Polygon25D').num: OGRGeomType('MultiPolygon25D'),
  43. }
  44. # Acceptable Django field types and corresponding acceptable OGR
  45. # counterparts.
  46. FIELD_TYPES = {
  47. models.AutoField: OFTInteger,
  48. models.BigAutoField: OFTInteger64,
  49. models.SmallAutoField: OFTInteger,
  50. models.BooleanField: (OFTInteger, OFTReal, OFTString),
  51. models.IntegerField: (OFTInteger, OFTReal, OFTString),
  52. models.FloatField: (OFTInteger, OFTReal),
  53. models.DateField: OFTDate,
  54. models.DateTimeField: OFTDateTime,
  55. models.EmailField: OFTString,
  56. models.TimeField: OFTTime,
  57. models.DecimalField: (OFTInteger, OFTReal),
  58. models.CharField: OFTString,
  59. models.SlugField: OFTString,
  60. models.TextField: OFTString,
  61. models.URLField: OFTString,
  62. models.UUIDField: OFTString,
  63. models.BigIntegerField: (OFTInteger, OFTReal, OFTString),
  64. models.SmallIntegerField: (OFTInteger, OFTReal, OFTString),
  65. models.PositiveIntegerField: (OFTInteger, OFTReal, OFTString),
  66. models.PositiveSmallIntegerField: (OFTInteger, OFTReal, OFTString),
  67. }
  68. def __init__(self, model, data, mapping, layer=0,
  69. source_srs=None, encoding='utf-8',
  70. transaction_mode='commit_on_success',
  71. transform=True, unique=None, using=None):
  72. """
  73. A LayerMapping object is initialized using the given Model (not an instance),
  74. a DataSource (or string path to an OGR-supported data file), and a mapping
  75. dictionary. See the module level docstring for more details and keyword
  76. argument usage.
  77. """
  78. # Getting the DataSource and the associated Layer.
  79. if isinstance(data, str):
  80. self.ds = DataSource(data, encoding=encoding)
  81. else:
  82. self.ds = data
  83. self.layer = self.ds[layer]
  84. self.using = using if using is not None else router.db_for_write(model)
  85. self.spatial_backend = connections[self.using].ops
  86. # Setting the mapping & model attributes.
  87. self.mapping = mapping
  88. self.model = model
  89. # Checking the layer -- initialization of the object will fail if
  90. # things don't check out before hand.
  91. self.check_layer()
  92. # Getting the geometry column associated with the model (an
  93. # exception will be raised if there is no geometry column).
  94. if connections[self.using].features.supports_transform:
  95. self.geo_field = self.geometry_field()
  96. else:
  97. transform = False
  98. # Checking the source spatial reference system, and getting
  99. # the coordinate transformation object (unless the `transform`
  100. # keyword is set to False)
  101. if transform:
  102. self.source_srs = self.check_srs(source_srs)
  103. self.transform = self.coord_transform()
  104. else:
  105. self.transform = transform
  106. # Setting the encoding for OFTString fields, if specified.
  107. if encoding:
  108. # Making sure the encoding exists, if not a LookupError
  109. # exception will be thrown.
  110. from codecs import lookup
  111. lookup(encoding)
  112. self.encoding = encoding
  113. else:
  114. self.encoding = None
  115. if unique:
  116. self.check_unique(unique)
  117. transaction_mode = 'autocommit' # Has to be set to autocommit.
  118. self.unique = unique
  119. else:
  120. self.unique = None
  121. # Setting the transaction decorator with the function in the
  122. # transaction modes dictionary.
  123. self.transaction_mode = transaction_mode
  124. if transaction_mode == 'autocommit':
  125. self.transaction_decorator = None
  126. elif transaction_mode == 'commit_on_success':
  127. self.transaction_decorator = transaction.atomic
  128. else:
  129. raise LayerMapError('Unrecognized transaction mode: %s' % transaction_mode)
  130. # #### Checking routines used during initialization ####
  131. def check_fid_range(self, fid_range):
  132. "Check the `fid_range` keyword."
  133. if fid_range:
  134. if isinstance(fid_range, (tuple, list)):
  135. return slice(*fid_range)
  136. elif isinstance(fid_range, slice):
  137. return fid_range
  138. else:
  139. raise TypeError
  140. else:
  141. return None
  142. def check_layer(self):
  143. """
  144. Check the Layer metadata and ensure that it's compatible with the
  145. mapping information and model. Unlike previous revisions, there is no
  146. need to increment through each feature in the Layer.
  147. """
  148. # The geometry field of the model is set here.
  149. # TODO: Support more than one geometry field / model. However, this
  150. # depends on the GDAL Driver in use.
  151. self.geom_field = False
  152. self.fields = {}
  153. # Getting lists of the field names and the field types available in
  154. # the OGR Layer.
  155. ogr_fields = self.layer.fields
  156. ogr_field_types = self.layer.field_types
  157. # Function for determining if the OGR mapping field is in the Layer.
  158. def check_ogr_fld(ogr_map_fld):
  159. try:
  160. idx = ogr_fields.index(ogr_map_fld)
  161. except ValueError:
  162. raise LayerMapError('Given mapping OGR field "%s" not found in OGR Layer.' % ogr_map_fld)
  163. return idx
  164. # No need to increment through each feature in the model, simply check
  165. # the Layer metadata against what was given in the mapping dictionary.
  166. for field_name, ogr_name in self.mapping.items():
  167. # Ensuring that a corresponding field exists in the model
  168. # for the given field name in the mapping.
  169. try:
  170. model_field = self.model._meta.get_field(field_name)
  171. except FieldDoesNotExist:
  172. raise LayerMapError('Given mapping field "%s" not in given Model fields.' % field_name)
  173. # Getting the string name for the Django field class (e.g., 'PointField').
  174. fld_name = model_field.__class__.__name__
  175. if isinstance(model_field, GeometryField):
  176. if self.geom_field:
  177. raise LayerMapError('LayerMapping does not support more than one GeometryField per model.')
  178. # Getting the coordinate dimension of the geometry field.
  179. coord_dim = model_field.dim
  180. try:
  181. if coord_dim == 3:
  182. gtype = OGRGeomType(ogr_name + '25D')
  183. else:
  184. gtype = OGRGeomType(ogr_name)
  185. except GDALException:
  186. raise LayerMapError('Invalid mapping for GeometryField "%s".' % field_name)
  187. # Making sure that the OGR Layer's Geometry is compatible.
  188. ltype = self.layer.geom_type
  189. if not (ltype.name.startswith(gtype.name) or self.make_multi(ltype, model_field)):
  190. raise LayerMapError('Invalid mapping geometry; model has %s%s, '
  191. 'layer geometry type is %s.' %
  192. (fld_name, '(dim=3)' if coord_dim == 3 else '', ltype))
  193. # Setting the `geom_field` attribute w/the name of the model field
  194. # that is a Geometry. Also setting the coordinate dimension
  195. # attribute.
  196. self.geom_field = field_name
  197. self.coord_dim = coord_dim
  198. fields_val = model_field
  199. elif isinstance(model_field, models.ForeignKey):
  200. if isinstance(ogr_name, dict):
  201. # Is every given related model mapping field in the Layer?
  202. rel_model = model_field.remote_field.model
  203. for rel_name, ogr_field in ogr_name.items():
  204. idx = check_ogr_fld(ogr_field)
  205. try:
  206. rel_model._meta.get_field(rel_name)
  207. except FieldDoesNotExist:
  208. raise LayerMapError('ForeignKey mapping field "%s" not in %s fields.' %
  209. (rel_name, rel_model.__class__.__name__))
  210. fields_val = rel_model
  211. else:
  212. raise TypeError('ForeignKey mapping must be of dictionary type.')
  213. else:
  214. # Is the model field type supported by LayerMapping?
  215. if model_field.__class__ not in self.FIELD_TYPES:
  216. raise LayerMapError('Django field type "%s" has no OGR mapping (yet).' % fld_name)
  217. # Is the OGR field in the Layer?
  218. idx = check_ogr_fld(ogr_name)
  219. ogr_field = ogr_field_types[idx]
  220. # Can the OGR field type be mapped to the Django field type?
  221. if not issubclass(ogr_field, self.FIELD_TYPES[model_field.__class__]):
  222. raise LayerMapError('OGR field "%s" (of type %s) cannot be mapped to Django %s.' %
  223. (ogr_field, ogr_field.__name__, fld_name))
  224. fields_val = model_field
  225. self.fields[field_name] = fields_val
  226. def check_srs(self, source_srs):
  227. "Check the compatibility of the given spatial reference object."
  228. if isinstance(source_srs, SpatialReference):
  229. sr = source_srs
  230. elif isinstance(source_srs, self.spatial_backend.spatial_ref_sys()):
  231. sr = source_srs.srs
  232. elif isinstance(source_srs, (int, str)):
  233. sr = SpatialReference(source_srs)
  234. else:
  235. # Otherwise just pulling the SpatialReference from the layer
  236. sr = self.layer.srs
  237. if not sr:
  238. raise LayerMapError('No source reference system defined.')
  239. else:
  240. return sr
  241. def check_unique(self, unique):
  242. "Check the `unique` keyword parameter -- may be a sequence or string."
  243. if isinstance(unique, (list, tuple)):
  244. # List of fields to determine uniqueness with
  245. for attr in unique:
  246. if attr not in self.mapping:
  247. raise ValueError
  248. elif isinstance(unique, str):
  249. # Only a single field passed in.
  250. if unique not in self.mapping:
  251. raise ValueError
  252. else:
  253. raise TypeError('Unique keyword argument must be set with a tuple, list, or string.')
  254. # Keyword argument retrieval routines ####
  255. def feature_kwargs(self, feat):
  256. """
  257. Given an OGR Feature, return a dictionary of keyword arguments for
  258. constructing the mapped model.
  259. """
  260. # The keyword arguments for model construction.
  261. kwargs = {}
  262. # Incrementing through each model field and OGR field in the
  263. # dictionary mapping.
  264. for field_name, ogr_name in self.mapping.items():
  265. model_field = self.fields[field_name]
  266. if isinstance(model_field, GeometryField):
  267. # Verify OGR geometry.
  268. try:
  269. val = self.verify_geom(feat.geom, model_field)
  270. except GDALException:
  271. raise LayerMapError('Could not retrieve geometry from feature.')
  272. elif isinstance(model_field, models.base.ModelBase):
  273. # The related _model_, not a field was passed in -- indicating
  274. # another mapping for the related Model.
  275. val = self.verify_fk(feat, model_field, ogr_name)
  276. else:
  277. # Otherwise, verify OGR Field type.
  278. val = self.verify_ogr_field(feat[ogr_name], model_field)
  279. # Setting the keyword arguments for the field name with the
  280. # value obtained above.
  281. kwargs[field_name] = val
  282. return kwargs
  283. def unique_kwargs(self, kwargs):
  284. """
  285. Given the feature keyword arguments (from `feature_kwargs`), construct
  286. and return the uniqueness keyword arguments -- a subset of the feature
  287. kwargs.
  288. """
  289. if isinstance(self.unique, str):
  290. return {self.unique: kwargs[self.unique]}
  291. else:
  292. return {fld: kwargs[fld] for fld in self.unique}
  293. # #### Verification routines used in constructing model keyword arguments. ####
  294. def verify_ogr_field(self, ogr_field, model_field):
  295. """
  296. Verify if the OGR Field contents are acceptable to the model field. If
  297. they are, return the verified value, otherwise raise an exception.
  298. """
  299. if (isinstance(ogr_field, OFTString) and
  300. isinstance(model_field, (models.CharField, models.TextField))):
  301. if self.encoding and ogr_field.value is not None:
  302. # The encoding for OGR data sources may be specified here
  303. # (e.g., 'cp437' for Census Bureau boundary files).
  304. val = force_str(ogr_field.value, self.encoding)
  305. else:
  306. val = ogr_field.value
  307. if model_field.max_length and val is not None and len(val) > model_field.max_length:
  308. raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
  309. (model_field.name, model_field.max_length, len(val)))
  310. elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
  311. try:
  312. # Creating an instance of the Decimal value to use.
  313. d = Decimal(str(ogr_field.value))
  314. except DecimalInvalidOperation:
  315. raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)
  316. # Getting the decimal value as a tuple.
  317. dtup = d.as_tuple()
  318. digits = dtup[1]
  319. d_idx = dtup[2] # index where the decimal is
  320. # Maximum amount of precision, or digits to the left of the decimal.
  321. max_prec = model_field.max_digits - model_field.decimal_places
  322. # Getting the digits to the left of the decimal place for the
  323. # given decimal.
  324. if d_idx < 0:
  325. n_prec = len(digits[:d_idx])
  326. else:
  327. n_prec = len(digits) + d_idx
  328. # If we have more than the maximum digits allowed, then throw an
  329. # InvalidDecimal exception.
  330. if n_prec > max_prec:
  331. raise InvalidDecimal(
  332. 'A DecimalField with max_digits %d, decimal_places %d must '
  333. 'round to an absolute value less than 10^%d.' %
  334. (model_field.max_digits, model_field.decimal_places, max_prec)
  335. )
  336. val = d
  337. elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
  338. # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
  339. try:
  340. val = int(ogr_field.value)
  341. except ValueError:
  342. raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
  343. else:
  344. val = ogr_field.value
  345. return val
  346. def verify_fk(self, feat, rel_model, rel_mapping):
  347. """
  348. Given an OGR Feature, the related model and its dictionary mapping,
  349. retrieve the related model for the ForeignKey mapping.
  350. """
  351. # TODO: It is expensive to retrieve a model for every record --
  352. # explore if an efficient mechanism exists for caching related
  353. # ForeignKey models.
  354. # Constructing and verifying the related model keyword arguments.
  355. fk_kwargs = {}
  356. for field_name, ogr_name in rel_mapping.items():
  357. fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name))
  358. # Attempting to retrieve and return the related model.
  359. try:
  360. return rel_model.objects.using(self.using).get(**fk_kwargs)
  361. except ObjectDoesNotExist:
  362. raise MissingForeignKey(
  363. 'No ForeignKey %s model found with keyword arguments: %s' %
  364. (rel_model.__name__, fk_kwargs)
  365. )
  366. def verify_geom(self, geom, model_field):
  367. """
  368. Verify the geometry -- construct and return a GeometryCollection
  369. if necessary (for example if the model field is MultiPolygonField while
  370. the mapped shapefile only contains Polygons).
  371. """
  372. # Downgrade a 3D geom to a 2D one, if necessary.
  373. if self.coord_dim != geom.coord_dim:
  374. geom.coord_dim = self.coord_dim
  375. if self.make_multi(geom.geom_type, model_field):
  376. # Constructing a multi-geometry type to contain the single geometry
  377. multi_type = self.MULTI_TYPES[geom.geom_type.num]
  378. g = OGRGeometry(multi_type)
  379. g.add(geom)
  380. else:
  381. g = geom
  382. # Transforming the geometry with our Coordinate Transformation object,
  383. # but only if the class variable `transform` is set w/a CoordTransform
  384. # object.
  385. if self.transform:
  386. g.transform(self.transform)
  387. # Returning the WKT of the geometry.
  388. return g.wkt
  389. # #### Other model methods ####
  390. def coord_transform(self):
  391. "Return the coordinate transformation object."
  392. SpatialRefSys = self.spatial_backend.spatial_ref_sys()
  393. try:
  394. # Getting the target spatial reference system
  395. target_srs = SpatialRefSys.objects.using(self.using).get(srid=self.geo_field.srid).srs
  396. # Creating the CoordTransform object
  397. return CoordTransform(self.source_srs, target_srs)
  398. except Exception as exc:
  399. raise LayerMapError(
  400. 'Could not translate between the data source and model geometry.'
  401. ) from exc
  402. def geometry_field(self):
  403. "Return the GeometryField instance associated with the geographic column."
  404. # Use `get_field()` on the model's options so that we
  405. # get the correct field instance if there's model inheritance.
  406. opts = self.model._meta
  407. return opts.get_field(self.geom_field)
  408. def make_multi(self, geom_type, model_field):
  409. """
  410. Given the OGRGeomType for a geometry and its associated GeometryField,
  411. determine whether the geometry should be turned into a GeometryCollection.
  412. """
  413. return (geom_type.num in self.MULTI_TYPES and
  414. model_field.__class__.__name__ == 'Multi%s' % geom_type.django)
  415. def save(self, verbose=False, fid_range=False, step=False,
  416. progress=False, silent=False, stream=sys.stdout, strict=False):
  417. """
  418. Save the contents from the OGR DataSource Layer into the database
  419. according to the mapping dictionary given at initialization.
  420. Keyword Parameters:
  421. verbose:
  422. If set, information will be printed subsequent to each model save
  423. executed on the database.
  424. fid_range:
  425. May be set with a slice or tuple of (begin, end) feature ID's to map
  426. from the data source. In other words, this keyword enables the user
  427. to selectively import a subset range of features in the geographic
  428. data source.
  429. step:
  430. If set with an integer, transactions will occur at every step
  431. interval. For example, if step=1000, a commit would occur after
  432. the 1,000th feature, the 2,000th feature etc.
  433. progress:
  434. When this keyword is set, status information will be printed giving
  435. the number of features processed and successfully saved. By default,
  436. progress information will pe printed every 1000 features processed,
  437. however, this default may be overridden by setting this keyword with an
  438. integer for the desired interval.
  439. stream:
  440. Status information will be written to this file handle. Defaults to
  441. using `sys.stdout`, but any object with a `write` method is supported.
  442. silent:
  443. By default, non-fatal error notifications are printed to stdout, but
  444. this keyword may be set to disable these notifications.
  445. strict:
  446. Execution of the model mapping will cease upon the first error
  447. encountered. The default behavior is to attempt to continue.
  448. """
  449. # Getting the default Feature ID range.
  450. default_range = self.check_fid_range(fid_range)
  451. # Setting the progress interval, if requested.
  452. if progress:
  453. if progress is True or not isinstance(progress, int):
  454. progress_interval = 1000
  455. else:
  456. progress_interval = progress
  457. def _save(feat_range=default_range, num_feat=0, num_saved=0):
  458. if feat_range:
  459. layer_iter = self.layer[feat_range]
  460. else:
  461. layer_iter = self.layer
  462. for feat in layer_iter:
  463. num_feat += 1
  464. # Getting the keyword arguments
  465. try:
  466. kwargs = self.feature_kwargs(feat)
  467. except LayerMapError as msg:
  468. # Something borked the validation
  469. if strict:
  470. raise
  471. elif not silent:
  472. stream.write('Ignoring Feature ID %s because: %s\n' % (feat.fid, msg))
  473. else:
  474. # Constructing the model using the keyword args
  475. is_update = False
  476. if self.unique:
  477. # If we want unique models on a particular field, handle the
  478. # geometry appropriately.
  479. try:
  480. # Getting the keyword arguments and retrieving
  481. # the unique model.
  482. u_kwargs = self.unique_kwargs(kwargs)
  483. m = self.model.objects.using(self.using).get(**u_kwargs)
  484. is_update = True
  485. # Getting the geometry (in OGR form), creating
  486. # one from the kwargs WKT, adding in additional
  487. # geometries, and update the attribute with the
  488. # just-updated geometry WKT.
  489. geom_value = getattr(m, self.geom_field)
  490. if geom_value is None:
  491. geom = OGRGeometry(kwargs[self.geom_field])
  492. else:
  493. geom = geom_value.ogr
  494. new = OGRGeometry(kwargs[self.geom_field])
  495. for g in new:
  496. geom.add(g)
  497. setattr(m, self.geom_field, geom.wkt)
  498. except ObjectDoesNotExist:
  499. # No unique model exists yet, create.
  500. m = self.model(**kwargs)
  501. else:
  502. m = self.model(**kwargs)
  503. try:
  504. # Attempting to save.
  505. m.save(using=self.using)
  506. num_saved += 1
  507. if verbose:
  508. stream.write('%s: %s\n' % ('Updated' if is_update else 'Saved', m))
  509. except Exception as msg:
  510. if strict:
  511. # Bailing out if the `strict` keyword is set.
  512. if not silent:
  513. stream.write(
  514. 'Failed to save the feature (id: %s) into the '
  515. 'model with the keyword arguments:\n' % feat.fid
  516. )
  517. stream.write('%s\n' % kwargs)
  518. raise
  519. elif not silent:
  520. stream.write('Failed to save %s:\n %s\nContinuing\n' % (kwargs, msg))
  521. # Printing progress information, if requested.
  522. if progress and num_feat % progress_interval == 0:
  523. stream.write('Processed %d features, saved %d ...\n' % (num_feat, num_saved))
  524. # Only used for status output purposes -- incremental saving uses the
  525. # values returned here.
  526. return num_saved, num_feat
  527. if self.transaction_decorator is not None:
  528. _save = self.transaction_decorator(_save)
  529. nfeat = self.layer.num_feat
  530. if step and isinstance(step, int) and step < nfeat:
  531. # Incremental saving is requested at the given interval (step)
  532. if default_range:
  533. raise LayerMapError('The `step` keyword may not be used in conjunction with the `fid_range` keyword.')
  534. beg, num_feat, num_saved = (0, 0, 0)
  535. indices = range(step, nfeat, step)
  536. n_i = len(indices)
  537. for i, end in enumerate(indices):
  538. # Constructing the slice to use for this step; the last slice is
  539. # special (e.g, [100:] instead of [90:100]).
  540. if i + 1 == n_i:
  541. step_slice = slice(beg, None)
  542. else:
  543. step_slice = slice(beg, end)
  544. try:
  545. num_feat, num_saved = _save(step_slice, num_feat, num_saved)
  546. beg = end
  547. except Exception: # Deliberately catch everything
  548. stream.write('%s\nFailed to save slice: %s\n' % ('=-' * 20, step_slice))
  549. raise
  550. else:
  551. # Otherwise, just calling the previously defined _save() function.
  552. _save()