测试gitnore

This commit is contained in:
ladeng07
2022-05-06 15:45:57 +08:00
parent 12f390949b
commit 51552904f9
2347 changed files with 120102 additions and 53549 deletions
@@ -10,8 +10,7 @@ try:
# LayerMapping requires DJANGO_SETTINGS_MODULE to be set,
# and ImproperlyConfigured is raised if that's not the case.
from django.contrib.gis.utils.layermapping import ( # NOQA
LayerMapError,
LayerMapping,
LayerMapError, LayerMapping,
)
except ImproperlyConfigured:
pass
@@ -7,26 +7,16 @@
https://docs.djangoproject.com/en/dev/ref/contrib/gis/layermapping/
"""
import sys
from decimal import Decimal
from decimal import InvalidOperation as DecimalInvalidOperation
from decimal import Decimal, InvalidOperation as DecimalInvalidOperation
from pathlib import Path
from django.contrib.gis.db.models import GeometryField
from django.contrib.gis.gdal import (
CoordTransform,
DataSource,
GDALException,
OGRGeometry,
OGRGeomType,
CoordTransform, DataSource, GDALException, OGRGeometry, OGRGeomType,
SpatialReference,
)
from django.contrib.gis.gdal.field import (
OFTDate,
OFTDateTime,
OFTInteger,
OFTInteger64,
OFTReal,
OFTString,
OFTDate, OFTDateTime, OFTInteger, OFTInteger64, OFTReal, OFTString,
OFTTime,
)
from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist
@@ -60,12 +50,12 @@ class LayerMapping:
# Acceptable 'base' types for a multi-geometry type.
MULTI_TYPES = {
1: OGRGeomType("MultiPoint"),
2: OGRGeomType("MultiLineString"),
3: OGRGeomType("MultiPolygon"),
OGRGeomType("Point25D").num: OGRGeomType("MultiPoint25D"),
OGRGeomType("LineString25D").num: OGRGeomType("MultiLineString25D"),
OGRGeomType("Polygon25D").num: OGRGeomType("MultiPolygon25D"),
1: OGRGeomType('MultiPoint'),
2: OGRGeomType('MultiLineString'),
3: OGRGeomType('MultiPolygon'),
OGRGeomType('Point25D').num: OGRGeomType('MultiPoint25D'),
OGRGeomType('LineString25D').num: OGRGeomType('MultiLineString25D'),
OGRGeomType('Polygon25D').num: OGRGeomType('MultiPolygon25D'),
}
# Acceptable Django field types and corresponding acceptable OGR
# counterparts.
@@ -93,19 +83,10 @@ class LayerMapping:
models.PositiveSmallIntegerField: (OFTInteger, OFTReal, OFTString),
}
def __init__(
self,
model,
data,
mapping,
layer=0,
source_srs=None,
encoding="utf-8",
transaction_mode="commit_on_success",
transform=True,
unique=None,
using=None,
):
def __init__(self, model, data, mapping, layer=0,
source_srs=None, encoding='utf-8',
transaction_mode='commit_on_success',
transform=True, unique=None, using=None):
"""
A LayerMapping object is initialized using the given Model (not an instance),
a DataSource (or string path to an OGR-supported data file), and a mapping
@@ -151,7 +132,6 @@ class LayerMapping:
# Making sure the encoding exists, if not a LookupError
# exception will be thrown.
from codecs import lookup
lookup(encoding)
self.encoding = encoding
else:
@@ -159,7 +139,7 @@ class LayerMapping:
if unique:
self.check_unique(unique)
transaction_mode = "autocommit" # Has to be set to autocommit.
transaction_mode = 'autocommit' # Has to be set to autocommit.
self.unique = unique
else:
self.unique = None
@@ -167,12 +147,12 @@ class LayerMapping:
# Setting the transaction decorator with the function in the
# transaction modes dictionary.
self.transaction_mode = transaction_mode
if transaction_mode == "autocommit":
if transaction_mode == 'autocommit':
self.transaction_decorator = None
elif transaction_mode == "commit_on_success":
elif transaction_mode == 'commit_on_success':
self.transaction_decorator = transaction.atomic
else:
raise LayerMapError("Unrecognized transaction mode: %s" % transaction_mode)
raise LayerMapError('Unrecognized transaction mode: %s' % transaction_mode)
# #### Checking routines used during initialization ####
def check_fid_range(self, fid_range):
@@ -209,9 +189,7 @@ class LayerMapping:
try:
idx = ogr_fields.index(ogr_map_fld)
except ValueError:
raise LayerMapError(
'Given mapping OGR field "%s" not found in OGR Layer.' % ogr_map_fld
)
raise LayerMapError('Given mapping OGR field "%s" not found in OGR Layer.' % ogr_map_fld)
return idx
# No need to increment through each feature in the model, simply check
@@ -222,44 +200,32 @@ class LayerMapping:
try:
model_field = self.model._meta.get_field(field_name)
except FieldDoesNotExist:
raise LayerMapError(
'Given mapping field "%s" not in given Model fields.' % field_name
)
raise LayerMapError('Given mapping field "%s" not in given Model fields.' % field_name)
# Getting the string name for the Django field class (e.g., 'PointField').
fld_name = model_field.__class__.__name__
if isinstance(model_field, GeometryField):
if self.geom_field:
raise LayerMapError(
"LayerMapping does not support more than one GeometryField per "
"model."
)
raise LayerMapError('LayerMapping does not support more than one GeometryField per model.')
# Getting the coordinate dimension of the geometry field.
coord_dim = model_field.dim
try:
if coord_dim == 3:
gtype = OGRGeomType(ogr_name + "25D")
gtype = OGRGeomType(ogr_name + '25D')
else:
gtype = OGRGeomType(ogr_name)
except GDALException:
raise LayerMapError(
'Invalid mapping for GeometryField "%s".' % field_name
)
raise LayerMapError('Invalid mapping for GeometryField "%s".' % field_name)
# Making sure that the OGR Layer's Geometry is compatible.
ltype = self.layer.geom_type
if not (
ltype.name.startswith(gtype.name)
or self.make_multi(ltype, model_field)
):
raise LayerMapError(
"Invalid mapping geometry; model has %s%s, "
"layer geometry type is %s."
% (fld_name, "(dim=3)" if coord_dim == 3 else "", ltype)
)
if not (ltype.name.startswith(gtype.name) or self.make_multi(ltype, model_field)):
raise LayerMapError('Invalid mapping geometry; model has %s%s, '
'layer geometry type is %s.' %
(fld_name, '(dim=3)' if coord_dim == 3 else '', ltype))
# Setting the `geom_field` attribute w/the name of the model field
# that is a Geometry. Also setting the coordinate dimension
@@ -276,19 +242,15 @@ class LayerMapping:
try:
rel_model._meta.get_field(rel_name)
except FieldDoesNotExist:
raise LayerMapError(
'ForeignKey mapping field "%s" not in %s fields.'
% (rel_name, rel_model.__class__.__name__)
)
raise LayerMapError('ForeignKey mapping field "%s" not in %s fields.' %
(rel_name, rel_model.__class__.__name__))
fields_val = rel_model
else:
raise TypeError("ForeignKey mapping must be of dictionary type.")
raise TypeError('ForeignKey mapping must be of dictionary type.')
else:
# Is the model field type supported by LayerMapping?
if model_field.__class__ not in self.FIELD_TYPES:
raise LayerMapError(
'Django field type "%s" has no OGR mapping (yet).' % fld_name
)
raise LayerMapError('Django field type "%s" has no OGR mapping (yet).' % fld_name)
# Is the OGR field in the Layer?
idx = check_ogr_fld(ogr_name)
@@ -296,10 +258,8 @@ class LayerMapping:
# Can the OGR field type be mapped to the Django field type?
if not issubclass(ogr_field, self.FIELD_TYPES[model_field.__class__]):
raise LayerMapError(
'OGR field "%s" (of type %s) cannot be mapped to Django %s.'
% (ogr_field, ogr_field.__name__, fld_name)
)
raise LayerMapError('OGR field "%s" (of type %s) cannot be mapped to Django %s.' %
(ogr_field, ogr_field.__name__, fld_name))
fields_val = model_field
self.fields[field_name] = fields_val
@@ -318,7 +278,7 @@ class LayerMapping:
sr = self.layer.srs
if not sr:
raise LayerMapError("No source reference system defined.")
raise LayerMapError('No source reference system defined.')
else:
return sr
@@ -334,9 +294,7 @@ class LayerMapping:
if unique not in self.mapping:
raise ValueError
else:
raise TypeError(
"Unique keyword argument must be set with a tuple, list, or string."
)
raise TypeError('Unique keyword argument must be set with a tuple, list, or string.')
# Keyword argument retrieval routines ####
def feature_kwargs(self, feat):
@@ -357,7 +315,7 @@ class LayerMapping:
try:
val = self.verify_geom(feat.geom, model_field)
except GDALException:
raise LayerMapError("Could not retrieve geometry from feature.")
raise LayerMapError('Could not retrieve geometry from feature.')
elif isinstance(model_field, models.base.ModelBase):
# The related _model_, not a field was passed in -- indicating
# another mapping for the related Model.
@@ -389,34 +347,23 @@ class LayerMapping:
Verify if the OGR Field contents are acceptable to the model field. If
they are, return the verified value, otherwise raise an exception.
"""
if isinstance(ogr_field, OFTString) and isinstance(
model_field, (models.CharField, models.TextField)
):
if (isinstance(ogr_field, OFTString) and
isinstance(model_field, (models.CharField, models.TextField))):
if self.encoding and ogr_field.value is not None:
# The encoding for OGR data sources may be specified here
# (e.g., 'cp437' for Census Bureau boundary files).
val = force_str(ogr_field.value, self.encoding)
else:
val = ogr_field.value
if (
model_field.max_length
and val is not None
and len(val) > model_field.max_length
):
raise InvalidString(
"%s model field maximum string length is %s, given %s characters."
% (model_field.name, model_field.max_length, len(val))
)
elif isinstance(ogr_field, OFTReal) and isinstance(
model_field, models.DecimalField
):
if model_field.max_length and val is not None and len(val) > model_field.max_length:
raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
(model_field.name, model_field.max_length, len(val)))
elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
try:
# Creating an instance of the Decimal value to use.
d = Decimal(str(ogr_field.value))
except DecimalInvalidOperation:
raise InvalidDecimal(
"Could not construct decimal from: %s" % ogr_field.value
)
raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)
# Getting the decimal value as a tuple.
dtup = d.as_tuple()
@@ -437,21 +384,17 @@ class LayerMapping:
# InvalidDecimal exception.
if n_prec > max_prec:
raise InvalidDecimal(
"A DecimalField with max_digits %d, decimal_places %d must "
"round to an absolute value less than 10^%d."
% (model_field.max_digits, model_field.decimal_places, max_prec)
'A DecimalField with max_digits %d, decimal_places %d must '
'round to an absolute value less than 10^%d.' %
(model_field.max_digits, model_field.decimal_places, max_prec)
)
val = d
elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(
model_field, models.IntegerField
):
elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
# Attempt to convert any OFTReal and OFTString value to an OFTInteger.
try:
val = int(ogr_field.value)
except ValueError:
raise InvalidInteger(
"Could not construct integer from: %s" % ogr_field.value
)
raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
else:
val = ogr_field.value
return val
@@ -468,17 +411,15 @@ class LayerMapping:
# Constructing and verifying the related model keyword arguments.
fk_kwargs = {}
for field_name, ogr_name in rel_mapping.items():
fk_kwargs[field_name] = self.verify_ogr_field(
feat[ogr_name], rel_model._meta.get_field(field_name)
)
fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name))
# Attempting to retrieve and return the related model.
try:
return rel_model.objects.using(self.using).get(**fk_kwargs)
except ObjectDoesNotExist:
raise MissingForeignKey(
"No ForeignKey %s model found with keyword arguments: %s"
% (rel_model.__name__, fk_kwargs)
'No ForeignKey %s model found with keyword arguments: %s' %
(rel_model.__name__, fk_kwargs)
)
def verify_geom(self, geom, model_field):
@@ -514,17 +455,13 @@ class LayerMapping:
SpatialRefSys = self.spatial_backend.spatial_ref_sys()
try:
# Getting the target spatial reference system
target_srs = (
SpatialRefSys.objects.using(self.using)
.get(srid=self.geo_field.srid)
.srs
)
target_srs = SpatialRefSys.objects.using(self.using).get(srid=self.geo_field.srid).srs
# Creating the CoordTransform object
return CoordTransform(self.source_srs, target_srs)
except Exception as exc:
raise LayerMapError(
"Could not translate between the data source and model geometry."
'Could not translate between the data source and model geometry.'
) from exc
def geometry_field(self):
@@ -539,21 +476,11 @@ class LayerMapping:
Given the OGRGeomType for a geometry and its associated GeometryField,
determine whether the geometry should be turned into a GeometryCollection.
"""
return (
geom_type.num in self.MULTI_TYPES
and model_field.__class__.__name__ == "Multi%s" % geom_type.django
)
return (geom_type.num in self.MULTI_TYPES and
model_field.__class__.__name__ == 'Multi%s' % geom_type.django)
def save(
self,
verbose=False,
fid_range=False,
step=False,
progress=False,
silent=False,
stream=sys.stdout,
strict=False,
):
def save(self, verbose=False, fid_range=False, step=False,
progress=False, silent=False, stream=sys.stdout, strict=False):
"""
Save the contents from the OGR DataSource Layer into the database
according to the mapping dictionary given at initialization.
@@ -619,9 +546,7 @@ class LayerMapping:
if strict:
raise
elif not silent:
stream.write(
"Ignoring Feature ID %s because: %s\n" % (feat.fid, msg)
)
stream.write('Ignoring Feature ID %s because: %s\n' % (feat.fid, msg))
else:
# Constructing the model using the keyword args
is_update = False
@@ -659,29 +584,23 @@ class LayerMapping:
m.save(using=self.using)
num_saved += 1
if verbose:
stream.write(
"%s: %s\n" % ("Updated" if is_update else "Saved", m)
)
stream.write('%s: %s\n' % ('Updated' if is_update else 'Saved', m))
except Exception as msg:
if strict:
# Bailing out if the `strict` keyword is set.
if not silent:
stream.write(
"Failed to save the feature (id: %s) into the "
"model with the keyword arguments:\n" % feat.fid
'Failed to save the feature (id: %s) into the '
'model with the keyword arguments:\n' % feat.fid
)
stream.write("%s\n" % kwargs)
stream.write('%s\n' % kwargs)
raise
elif not silent:
stream.write(
"Failed to save %s:\n %s\nContinuing\n" % (kwargs, msg)
)
stream.write('Failed to save %s:\n %s\nContinuing\n' % (kwargs, msg))
# Printing progress information, if requested.
if progress and num_feat % progress_interval == 0:
stream.write(
"Processed %d features, saved %d ...\n" % (num_feat, num_saved)
)
stream.write('Processed %d features, saved %d ...\n' % (num_feat, num_saved))
# Only used for status output purposes -- incremental saving uses the
# values returned here.
@@ -694,10 +613,7 @@ class LayerMapping:
if step and isinstance(step, int) and step < nfeat:
# Incremental saving is requested at the given interval (step)
if default_range:
raise LayerMapError(
"The `step` keyword may not be used in conjunction with the "
"`fid_range` keyword."
)
raise LayerMapError('The `step` keyword may not be used in conjunction with the `fid_range` keyword.')
beg, num_feat, num_saved = (0, 0, 0)
indices = range(step, nfeat, step)
n_i = len(indices)
@@ -714,9 +630,7 @@ class LayerMapping:
num_feat, num_saved = _save(step_slice, num_feat, num_saved)
beg = end
except Exception: # Deliberately catch everything
stream.write(
"%s\nFailed to save slice: %s\n" % ("=-" * 20, step_slice)
)
stream.write('%s\nFailed to save slice: %s\n' % ('=-' * 20, step_slice))
raise
else:
# Otherwise, just calling the previously defined _save() function.
@@ -20,9 +20,7 @@ def ogrinfo(data_source, num_features=10):
elif isinstance(data_source, DataSource):
pass
else:
raise Exception(
"Data source parameter must be a string or a DataSource object."
)
raise Exception('Data source parameter must be a string or a DataSource object.')
for i, layer in enumerate(data_source):
print("data source : %s" % data_source.name)
@@ -46,8 +44,8 @@ def ogrinfo(data_source, num_features=10):
if isinstance(val, str):
val_fmt = ' ("%s")'
else:
val_fmt = " (%s)"
val_fmt = ' (%s)'
output += val_fmt % val
else:
output += " (None)"
output += ' (None)'
print(output)
@@ -5,17 +5,12 @@ models for GeoDjango and/or mapping dictionaries for use with the
"""
from django.contrib.gis.gdal import DataSource
from django.contrib.gis.gdal.field import (
OFTDate,
OFTDateTime,
OFTInteger,
OFTInteger64,
OFTReal,
OFTString,
OFTDate, OFTDateTime, OFTInteger, OFTInteger64, OFTReal, OFTString,
OFTTime,
)
def mapping(data_source, geom_name="geom", layer_key=0, multi_geom=False):
def mapping(data_source, geom_name='geom', layer_key=0, multi_geom=False):
"""
Given a DataSource, generate a dictionary that may be used
for invoking the LayerMapping utility.
@@ -35,9 +30,7 @@ def mapping(data_source, geom_name="geom", layer_key=0, multi_geom=False):
elif isinstance(data_source, DataSource):
pass
else:
raise TypeError(
"Data source parameter must be a string or a DataSource object."
)
raise TypeError('Data source parameter must be a string or a DataSource object.')
# Creating the dictionary.
_mapping = {}
@@ -45,8 +38,8 @@ def mapping(data_source, geom_name="geom", layer_key=0, multi_geom=False):
# Generating the field name for each field in the layer.
for field in data_source[layer_key].fields:
mfield = field.lower()
if mfield[-1:] == "_":
mfield += "field"
if mfield[-1:] == '_':
mfield += 'field'
_mapping[mfield] = field
gtype = data_source[layer_key].geom_type
if multi_geom:
@@ -123,22 +116,12 @@ def ogrinspect(*args, **kwargs):
Note: Call the _ogrinspect() helper to do the heavy lifting.
"""
return "\n".join(_ogrinspect(*args, **kwargs))
return '\n'.join(_ogrinspect(*args, **kwargs))
def _ogrinspect(
data_source,
model_name,
geom_name="geom",
layer_key=0,
srid=None,
multi_geom=False,
name_field=None,
imports=True,
decimal=False,
blank=False,
null=False,
):
def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=None,
multi_geom=False, name_field=None, imports=True,
decimal=False, blank=False, null=False):
"""
Helper routine for `ogrinspect` that generates GeoDjango models corresponding
to the given data source. See the `ogrinspect` docstring for more details.
@@ -149,9 +132,7 @@ def _ogrinspect(
elif isinstance(data_source, DataSource):
pass
else:
raise TypeError(
"Data source parameter must be a string or a DataSource object."
)
raise TypeError('Data source parameter must be a string or a DataSource object.')
# Getting the layer corresponding to the layer key and getting
# a string listing of all OGR fields in the Layer.
@@ -167,7 +148,6 @@ def _ogrinspect(
return [s.lower() for s in ogr_fields]
else:
return []
null_fields = process_kwarg(null)
blank_fields = process_kwarg(blank)
decimal_fields = process_kwarg(decimal)
@@ -176,30 +156,29 @@ def _ogrinspect(
def get_kwargs_str(field_name):
kwlist = []
if field_name.lower() in null_fields:
kwlist.append("null=True")
kwlist.append('null=True')
if field_name.lower() in blank_fields:
kwlist.append("blank=True")
kwlist.append('blank=True')
if kwlist:
return ", " + ", ".join(kwlist)
return ', ' + ', '.join(kwlist)
else:
return ""
return ''
# For those wishing to disable the imports.
if imports:
yield "# This is an auto-generated Django model module created by ogrinspect."
yield "from django.contrib.gis.db import models"
yield ""
yield ""
yield '# This is an auto-generated Django model module created by ogrinspect.'
yield 'from django.contrib.gis.db import models'
yield ''
yield ''
yield "class %s(models.Model):" % model_name
yield 'class %s(models.Model):' % model_name
for field_name, width, precision, field_type in zip(
ogr_fields, layer.field_widths, layer.field_precisions, layer.field_types
):
ogr_fields, layer.field_widths, layer.field_precisions, layer.field_types):
# The model field name.
mfield = field_name.lower()
if mfield[-1:] == "_":
mfield += "field"
if mfield[-1:] == '_':
mfield += 'field'
# Getting the keyword args string.
kwargs_str = get_kwargs_str(field_name)
@@ -209,34 +188,25 @@ def _ogrinspect(
# may also be mapped to `DecimalField` if specified in the
# `decimal` keyword.
if field_name.lower() in decimal_fields:
yield (
" %s = models.DecimalField(max_digits=%d, decimal_places=%d%s)"
) % (
mfield,
width,
precision,
kwargs_str,
yield ' %s = models.DecimalField(max_digits=%d, decimal_places=%d%s)' % (
mfield, width, precision, kwargs_str
)
else:
yield " %s = models.FloatField(%s)" % (mfield, kwargs_str[2:])
yield ' %s = models.FloatField(%s)' % (mfield, kwargs_str[2:])
elif field_type is OFTInteger:
yield " %s = models.IntegerField(%s)" % (mfield, kwargs_str[2:])
yield ' %s = models.IntegerField(%s)' % (mfield, kwargs_str[2:])
elif field_type is OFTInteger64:
yield " %s = models.BigIntegerField(%s)" % (mfield, kwargs_str[2:])
yield ' %s = models.BigIntegerField(%s)' % (mfield, kwargs_str[2:])
elif field_type is OFTString:
yield " %s = models.CharField(max_length=%s%s)" % (
mfield,
width,
kwargs_str,
)
yield ' %s = models.CharField(max_length=%s%s)' % (mfield, width, kwargs_str)
elif field_type is OFTDate:
yield " %s = models.DateField(%s)" % (mfield, kwargs_str[2:])
yield ' %s = models.DateField(%s)' % (mfield, kwargs_str[2:])
elif field_type is OFTDateTime:
yield " %s = models.DateTimeField(%s)" % (mfield, kwargs_str[2:])
yield ' %s = models.DateTimeField(%s)' % (mfield, kwargs_str[2:])
elif field_type is OFTTime:
yield " %s = models.TimeField(%s)" % (mfield, kwargs_str[2:])
yield ' %s = models.TimeField(%s)' % (mfield, kwargs_str[2:])
else:
raise TypeError("Unknown field type %s in %s" % (field_type, mfield))
raise TypeError('Unknown field type %s in %s' % (field_type, mfield))
# TODO: Autodetection of multigeometry types (see #7218).
gtype = layer.geom_type
@@ -247,21 +217,21 @@ def _ogrinspect(
# Setting up the SRID keyword string.
if srid is None:
if layer.srs is None:
srid_str = "srid=-1"
srid_str = 'srid=-1'
else:
srid = layer.srs.srid
if srid is None:
srid_str = "srid=-1"
srid_str = 'srid=-1'
elif srid == 4326:
# WGS84 is already the default.
srid_str = ""
srid_str = ''
else:
srid_str = "srid=%s" % srid
srid_str = 'srid=%s' % srid
else:
srid_str = "srid=%s" % srid
srid_str = 'srid=%s' % srid
yield " %s = models.%s(%s)" % (geom_name, geom_field, srid_str)
yield ' %s = models.%s(%s)' % (geom_name, geom_field, srid_str)
if name_field:
yield ""
yield " def __str__(self): return self.%s" % name_field
yield ''
yield ' def __str__(self): return self.%s' % name_field
@@ -2,9 +2,8 @@ from django.contrib.gis.gdal import SpatialReference
from django.db import DEFAULT_DB_ALIAS, connections
def add_srs_entry(
srs, auth_name="EPSG", auth_srid=None, ref_sys_name=None, database=None
):
def add_srs_entry(srs, auth_name='EPSG', auth_srid=None, ref_sys_name=None,
database=None):
"""
Take a GDAL SpatialReference system and add its information to the
`spatial_ref_sys` table of the spatial backend. Doing this enables
@@ -36,10 +35,11 @@ def add_srs_entry(
database = database or DEFAULT_DB_ALIAS
connection = connections[database]
if not hasattr(connection.ops, "spatial_version"):
raise Exception("The `add_srs_entry` utility only works with spatial backends.")
if not hasattr(connection.ops, 'spatial_version'):
raise Exception('The `add_srs_entry` utility only works '
'with spatial backends.')
if not connection.features.supports_add_srs_entry:
raise Exception("This utility does not support your database backend.")
raise Exception('This utility does not support your database backend.')
SpatialRefSys = connection.ops.spatial_ref_sys()
# If argument is not a `SpatialReference` instance, use it as parameter
@@ -48,26 +48,24 @@ def add_srs_entry(
srs = SpatialReference(srs)
if srs.srid is None:
raise Exception(
"Spatial reference requires an SRID to be "
"compatible with the spatial backend."
)
raise Exception('Spatial reference requires an SRID to be '
'compatible with the spatial backend.')
# Initializing the keyword arguments dictionary for both PostGIS
# and SpatiaLite.
kwargs = {
"srid": srs.srid,
"auth_name": auth_name,
"auth_srid": auth_srid or srs.srid,
"proj4text": srs.proj4,
'srid': srs.srid,
'auth_name': auth_name,
'auth_srid': auth_srid or srs.srid,
'proj4text': srs.proj4,
}
# Backend-specific fields for the SpatialRefSys model.
srs_field_names = {f.name for f in SpatialRefSys._meta.get_fields()}
if "srtext" in srs_field_names:
kwargs["srtext"] = srs.wkt
if "ref_sys_name" in srs_field_names:
if 'srtext' in srs_field_names:
kwargs['srtext'] = srs.wkt
if 'ref_sys_name' in srs_field_names:
# SpatiaLite specific
kwargs["ref_sys_name"] = ref_sys_name or srs.name
kwargs['ref_sys_name'] = ref_sys_name or srs.name
# Creating the spatial_ref_sys model.
try: