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 27 KiB

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