1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
|
import json
from collections import OrderedDict
from django.contrib.gis.gdal import GDALException
from django.contrib.gis.geos import GEOSException, GEOSGeometry
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from rest_framework.fields import Field, SerializerMethodField
__all__ = ['GeometryField', 'GeometrySerializerMethodField']
class GeometryField(Field):
"""
A field to handle GeoDjango Geometry fields
"""
type_name = 'GeometryField'
def __init__(
self, precision=None, remove_duplicates=False, auto_bbox=False, **kwargs
):
"""
:param auto_bbox: Whether the GeoJSON object should include a bounding box
"""
self.precision = precision
self.auto_bbox = auto_bbox
self.remove_dupes = remove_duplicates
super().__init__(**kwargs)
self.style.setdefault('base_template', 'textarea.html')
def to_representation(self, value):
if isinstance(value, dict) or value is None:
return value
# we expect value to be a GEOSGeometry instance
if value.geojson:
geojson = GeoJsonDict(value.geojson)
# in this case we're dealing with an empty point
else:
geojson = GeoJsonDict({'type': value.geom_type, 'coordinates': []})
if geojson['type'] == 'GeometryCollection':
geometries = geojson.get('geometries')
else:
geometries = [geojson]
for geometry in geometries:
if self.precision is not None:
geometry['coordinates'] = self._recursive_round(
geometry['coordinates'], self.precision
)
if self.remove_dupes:
geometry['coordinates'] = self._rm_redundant_points(
geometry['coordinates'], geometry['type']
)
if self.auto_bbox:
geojson["bbox"] = value.extent
return geojson
def to_internal_value(self, value):
if value == '' or value is None:
return value
if isinstance(value, GEOSGeometry):
# value already has the correct representation
return value
if isinstance(value, dict):
value = json.dumps(value)
try:
return GEOSGeometry(value)
except GEOSException:
raise ValidationError(
_(
'Invalid format: string or unicode input unrecognized as GeoJSON, WKT EWKT or HEXEWKB.'
)
)
except (ValueError, TypeError, GDALException) as e:
raise ValidationError(
_('Unable to convert to python object: {}'.format(str(e)))
)
def validate_empty_values(self, data):
if data == '':
self.fail('required')
return super().validate_empty_values(data)
def _recursive_round(self, value, precision):
"""
Round all numbers within an array or nested arrays
value: number or nested array of numbers
precision: integer valueue of number of decimals to keep
"""
if hasattr(value, '__iter__'):
return tuple(self._recursive_round(v, precision) for v in value)
return round(value, precision)
def _rm_redundant_points(self, geometry, geo_type):
"""
Remove redundant coordinate pairs from geometry
geometry: array of coordinates or nested-array of coordinates
geo_type: GeoJSON type attribute for provided geometry, used to
determine structure of provided `geometry` argument
"""
if geo_type in ('MultiPoint', 'LineString'):
close = geo_type == 'LineString'
output = []
for coord in geometry:
coord = tuple(coord)
if not output or coord != output[-1]:
output.append(coord)
if close and len(output) == 1:
output.append(output[0])
return tuple(output)
if geo_type in ('MultiLineString', 'Polygon'):
return [self._rm_redundant_points(c, 'LineString') for c in geometry]
if geo_type == 'MultiPolygon':
return [self._rm_redundant_points(c, 'Polygon') for c in geometry]
return geometry
class GeometrySerializerMethodField(SerializerMethodField):
def to_representation(self, value):
value = super().to_representation(value)
if value is not None:
# we expect value to be a GEOSGeometry instance
return GeoJsonDict(value.geojson)
else:
return None
class GeoJsonDict(OrderedDict):
"""
Used for serializing GIS values to GeoJSON values
TODO: remove this when support for python 2.6/2.7 will be dropped
"""
def __init__(self, *args, **kwargs):
"""
If a string is passed attempt to pass it through json.loads,
because it should be a geojson formatted string.
"""
if args and isinstance(args[0], str):
try:
geojson = json.loads(args[0])
args = (geojson,)
except ValueError:
pass
super().__init__(*args, **kwargs)
def __str__(self):
"""
Avoid displaying strings like
``{ 'type': u'Point', 'coordinates': [12, 32] }``
in DRF browsable UI inputs (python 2.6/2.7)
see: https://github.com/openwisp/django-rest-framework-gis/pull/60
"""
return json.dumps(self)
|