layermapping.py 26 KB

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