layermapping.py 27 KB

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