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.

layermapping.py 27KB

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