layermapping.py 28 KB

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