././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1641564397.388531 djangorestframework-gis-0.18/0000775000175000017500000000000000000000000017433 5ustar00nemesisnemesis00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1611531918.0 djangorestframework-gis-0.18/AUTHORS0000664000175000017500000000062000000000000020501 0ustar00nemesisnemesis00000000000000Original Author --------------- Douglas Meehan https://github.com/dmeehan Contributors ------------ Christoph Heer https://github.com/jarus Federico Capoano https://github.com/nemesisdesign/ Shanto https://github.com/Shanto Eric Theise https://github.com/erictheise Asif Saifuddin https://github.com/auvipy Dhaval Mehta https://github.com/dhaval-mehta ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1641563944.0 djangorestframework-gis-0.18/CHANGES.rst0000664000175000017500000002441400000000000021242 0ustar00nemesisnemesis00000000000000Changelog ========= Version 0.18.0 [2022-01-07] --------------------------- - [fix] Add schema generation support for plain GeometryFields `#257 `_ - [fix] Fixed psycopg2 compatibility for Django 3.0 - [feature] Added support and CI testing for Django 3.2 and Django 4.0 Version 0.17.0 [2021-01-25] --------------------------- - [feature] Added `OpenAPI Schema Generation `_ (`#219 `_) - special thanks to `Dhaval Mehta `_ Version 0.16.0 [2020-09-07] --------------------------- - [fix] Added support for representation of empty geometries (`#168 `_) - [fix] Don't override the additional arguments passed as ``style`` to ``GeometryField`` - [feature] Added `DistanceToPointOrderingFilter `_ (`#210 `_) - [deps] Added support for django 3.1 in the CI build - [deps] Dropped django 1.11 and Python 3.5 from the CI build, compatibility may still work but it's not guaranteed anymore, please upgrade! - [qa] Added QA checks to CI build (`#230 `_) Version 0.15.0 [2019-12-09] --------------------------- - Dropped Python 3.4 support - `#190 `_: Added django 2.2 on test matrix - `#199 `_: Dropped Django 2.0 support - `#195 `_: Updated the way that ``to_representation`` removes already processed - `#197 `_: Removed six dependency - `#202 `_: Updated DRF to 3.10, removed support for previous DRF versions - `#200 `_: Added Django 3.0 and Python 3.8 support Version 0.14.0 [2018-12-02] --------------------------- - `#173 `_: added support for django 2.1, DRF 3.9 and switched to django-filters >= 2.0 (**which requires python >= 3.4**) - `#178 `_: simplified ``setup.py`` and tox build Version 0.13.0 [2018-04-27] --------------------------- - `#161 `_: added flag to reduce precision of ``GeometryField`` - `#164 `_: added compatibility with django-rest-framework 3.8 Version 0.12.0 [2017-11-12] --------------------------- - `#138 `_: added support for ``GeometryCollection`` fields - `#146 `_: added compatibility with django-rest-framework 3.7 - `#147 `_: added support to django 2.0 beta - dropped support for django 1.7, 1.8, 1.9 and 1.10 Version 0.11.2 [2017-05-22] --------------------------- - `eb54fc0 `_: ``GeometryFilter`` now use ``BaseGeometryWidget`` - `33a6418 `_: fixed tests for Django 1.11: ``Point`` comparison uses ``srid`` Version 0.11.1 [2017-05-05] --------------------------- - `#119 `_: Added support to "__all__" fields in serializer - `#130 `_: Added compatibility with DRF 3.6 Version 0.11.0 [2016-11-22] --------------------------- - `#106 `_: dropped support for django 1.7 - `#117 `_: added support for django-filter 0.15 - `6479949 `_: fixed tests for latest DRF 3.5 version - `35e3b87 `_: added official support to django 1.10 Version 0.10.1 [2016-01-06] --------------------------- - `#93 `_ skipped a few tests if spatialite DB backend is being used - `#95 `_ fixed misunderstanding regarding 0.9.6 DRF compatibility in README - `#96 `_ added missing assets in python package source tarball Version 0.10.0 [2015-12-07] --------------------------- - `#87 `_ dropped support for old django versions and python 2.6 Version 0.9.6 [2015-11-02] -------------------------- - `#82 `_: avoid ``KeyError`` id field not in ``fields`` (bug introduced in 0.9.5) - `fbaf9b1 `_: improved documentation for new default ``id_field`` behaviour - `#84 `_: switched to ``assertAlmostEqual`` in ``test_post_location_list_EWKT`` to ease testing for debian package - `#85 `_: fixed serialization of properties holding ``None`` values (bug introduced in 0.9.5) - `#86 `_: updated advertised compatibility to include **python 3.5** Version 0.9.5 [2015-10-12] -------------------------- - `#71 `_: added possibility to override GeoJSON properties in ``GeoFeatureModelSerializer`` - `52e15a5 `_: Added default ``page_size_query_param`` in ``GeoJsonPagination`` Version 0.9.4 [2015-09-08] -------------------------- - `#68 `_: ensure not having drf-gis in ``INSTALLED_APPS`` works anyway - `#76 `_: avoid pickle errors in ``GeoJsonDict`` - `#75 `_: return ``GEOSGeometry`` instead of geojson property Version 0.9.3 [2015-07-22] -------------------------- - `04fd1bf `_: Added ``GeoJsonPagination`` - `fe47d86 `_: Improved ``ValidationError`` message of ``GeometryField`` - `a3ddd3d `_: **Improved serialization performance between 25% and 29%** - `fb6ed36 `_: ``GeoModelSerializer`` deprecated because obsolete - `#66 `_: geometry now allows ``None`` values according to the **GeoJSON spec** - `#67 `_: discern ``False`` or empty string values from ``None`` in ``GeoFeatureModelSerializer`` Version 0.9.2 [2015-07-15] -------------------------- - `#59 `_: Added GeometrySerializerMethodField - `3fa2354 `_: removed broken/obsolete/untested code Version 0.9.1 [2015-06-28] -------------------------- - `#63 `_: added compatibility with python 3.2 and updated compatibility table in README - `#60 `_: ensure GeoJSON is rendered correctly in browsable API when using python 2 - `#62 `_: updated django-rest-framework requirement to 3.1.3 Version 0.9 [2015-05-31] ------------------------ - `#55 `_: Fixed exception in ``DistanceToPointFilter`` in case of invalid point - `#58 `_: Fixed handling of ``None`` values in ``GeoFeatureModelSerializer`` to avoid problems with ``FileField`` and ``ImageField`` - `#57 `_: Added support for GeoJSON Bounding Boxes in ``GeoFeatureModelSerializer`` Version 0.8.2 [2015-04-29] -------------------------- - `#53 `_: Added support for PATCH requests in ``GeoFeatureModelSerializer`` Version 0.8.1 [2015-03-25] -------------------------- - Added compatibility with django-rest-framework 3.1.x - Added compatibility with django 1.8 (RC1) Version 0.8 [2015-03-03] ------------------------ - Added compatibility with django-rest-framework 3.x Version 0.7 [2014-10-03] ------------------------ - upgraded development status classifer to Beta - avoid empty string in textarea widget if value is None - allow field definition in GeoFeatureModelSerializer to be list Version 0.6 [2014-09-24] ------------------------ - Added compatibility to django-rest-framework 2.4.3 Version 0.5 [2014-09-07] ------------------------ - added TMSTileFilter - added DistanceToPointFilter - renamed InBBOXFilter to InBBoxFilter - added compatibility with DRF 2.4.0 Version 0.4 [2014-08-25] ------------------------ - python3 compatibility - improved DRF browsable API HTML widget (textarea instead of text input) Version 0.3 [2014-07-07] ------------------------ - added compatibility with DRF 2.3.14 Version 0.2 [2014-03-18] ------------------------ - geofilter support - README in restructured text for pypi - updated python package info Version 0.1 [2013-12-30] ------------------------ - first release ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1598581253.0 djangorestframework-gis-0.18/LICENSE0000664000175000017500000000204700000000000020443 0ustar00nemesisnemesis00000000000000Copyright (C) 2013-2014 Douglas Meehan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1575898946.0 djangorestframework-gis-0.18/MANIFEST.in0000644000175000017500000000014400000000000021166 0ustar00nemesisnemesis00000000000000include AUTHORS include LICENSE include README.rst include CHANGES.rst recursive-include tests *.py ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1641564397.388531 djangorestframework-gis-0.18/PKG-INFO0000664000175000017500000007061700000000000020543 0ustar00nemesisnemesis00000000000000Metadata-Version: 2.1 Name: djangorestframework-gis Version: 0.18 Summary: Geographic add-ons for Django Rest Framework Home-page: https://github.com/openwisp/django-rest-framework-gis Author: Douglas Meehan Author-email: django-rest-framework-gis@googlegroups.com License: BSD Download-URL: https://github.com/openwisp/django-rest-framework-gis/releases Project-URL: Bug Reports, https://github.com/openwisp/django-rest-framework-gis/issues Project-URL: Continuous Integration, https://travis-ci.org/openwisp/django-rest-framework-gis Project-URL: Mailing List, https://groups.google.com/forum/#!forum/django-rest-framework-gis Project-URL: Code Coverage, https://coveralls.io/github/openwisp/django-rest-framework-gis Project-URL: Source Code, https://github.com/openwisp/django-rest-framework-gis Keywords: django,rest-framework,gis,geojson Platform: Platform Indipendent Classifier: Development Status :: 4 - Beta Classifier: Environment :: Web Environment Classifier: Topic :: Internet :: WWW/HTTP Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Framework :: Django Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3 :: Only License-File: LICENSE License-File: AUTHORS django-rest-framework-gis ========================= |Build Status| |Coverage Status| |Requirements Status| |PyPI version| |PyPI downloads| |Black| Geographic add-ons for Django Rest Framework - `Mailing List `__. Install last stable version from pypi ------------------------------------- .. code-block:: bash pip install djangorestframework-gis Install development version --------------------------- .. code-block:: bash pip install https://github.com/openwisp/django-rest-framework-gis/tarball/master Setup ----- Add ``rest_framework_gis`` in ``settings.INSTALLED_APPS``, after ``rest_framework``: .. code-block:: python INSTALLED_APPS = [ # ... 'rest_framework', 'rest_framework_gis', # ... ] Compatibility with DRF, Django and Python ----------------------------------------- ======================== ============================ ==================== ================================== DRF-gis version DRF version Django version Python version **0.18.x** **3.10** up to **3.13** **2.2 to 4.0** **3.6** to **3.9** **0.17.x** **3.10** up to **3.12** **2.2 to 3.1** **3.6** to **3.8** **0.16.x** **3.10** **2.2 to 3.1** **3.6** to **3.8** **0.15.x** **3.10** **1.11, 2.2 to 3.0** **3.5** to **3.8** **0.14.x** **3.3** to **3.9** **1.11** to **2.1** **3.4** to **3.7** **0.13.x** **3.3** to **3.8** **1.11** to **2.0** **2.7** to **3.6** **0.12.x** **3.1** to **3.7** **1.11** to **2.0** **2.7** to **3.6** **0.11.x** **3.1** to **3.6** **1.7** to **1.11** **2.7** to **3.6** **0.10.x** **3.1** to **3.3** **1.7** to **1.9** **2.7** to **3.5** **0.9.6** **3.1** to **3.2** **1.5** to **1.8** **2.6** to **3.5** **0.9.5** **3.1** to **3.2** **1.5** to **1.8** **2.6** to **3.4** **0.9.4** **3.1** to **3.2** **1.5** to **1.8** **2.6** to **3.4** **0.9.3** **3.1** **1.5** to **1.8** **2.6** to **3.4** **0.9.2** **3.1** **1.5** to **1.8** **2.6** to **3.4** **0.9.1** **3.1** **1.5** to **1.8** **2.6** to **3.4** **0.9** **3.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** **0.9** **3.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** **0.9** **3.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** **0.8.2** **3.0.4** to **3.1.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** **0.8.1** **3.0.4** to **3.1.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** **0.8** **3.0.4** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** **0.7** **2.4.3** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** **0.6** **2.4.3** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** **0.5** from **2.3.14** to **2.4.2** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** **0.4** from **2.3.14** to **2.4.2** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** **0.3** from **2.3.14** to **2.4.2** **1.5**, **1.6** **2.6**, **2.7** **0.2** from **2.2.2** to **2.3.13** **1.5**, **1.6** **2.6**, **2.7** ======================== ============================ ==================== ================================== Fields ------ GeometryField ~~~~~~~~~~~~~ Provides a ``GeometryField``, which is a subclass of Django Rest Framework (from now on **DRF**) ``WritableField``. This field handles GeoDjango geometry fields, providing custom ``to_native`` and ``from_native`` methods for GeoJSON input/output. This field takes two optional arguments: ``precision``: Passes coordinates through Python's builtin ``round()`` function (`docs `_), rounding values to the provided level of precision. E.g. A Point with lat/lng of ``[51.0486, -114.0708]`` passed through a ``GeometryField(precision=2)`` would return a Point with a lat/lng of ``[51.05, -114.07]``. ``remove_duplicates``: Remove sequential duplicate coordinates from line and polygon geometries. This is particularly useful when used with the ``precision`` argument, as the likelihood of duplicate coordinates increase as precision of coordinates are reduced. **Note:** While both above arguments are designed to reduce the byte size of the API response, they will also increase the processing time required to render the response. This will likely be negligible for small GeoJSON responses but may become an issue for large responses. **New in 0.9.3:** there is no need to define this field explicitly in your serializer, it's mapped automatically during initialization in ``rest_framework_gis.apps.AppConfig.ready()``. GeometrySerializerMethodField ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provides a ``GeometrySerializerMethodField``, which is a subclass of DRF ``SerializerMethodField`` and handles values which are computed with a serializer method and are used as a ``geo_field``. `See example below `__. Serializers ----------- GeoModelSerializer (DEPRECATED) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ **Deprecated, will be removed in 1.0**: Using this serializer is not needed anymore since 0.9.3, if you add ``rest_framework_gis`` in ``settings.INSTALLED_APPS`` the serialization will work out of the box with DRF. Refer `Issue #156 `__. Provides a ``GeoModelSerializer``, which is a subclass of DRF ``ModelSerializer``. This serializer updates the field\_mapping dictionary to include field mapping of GeoDjango geometry fields to the above ``GeometryField``. For example, the following model: .. code-block:: python class Location(models.Model): """ A model which holds information about a particular location """ address = models.CharField(max_length=255) city = models.CharField(max_length=100) state = models.CharField(max_length=100) point = models.PointField() By default, the DRF ModelSerializer **ver < 0.9.3** will output: .. code-block:: javascript { "id": 1, "address": "742 Evergreen Terrace", "city": "Springfield", "state": "Oregon", "point": "POINT(-123.0208 44.0464)" } In contrast, the ``GeoModelSerializer`` will output: .. code-block:: javascript { "id": 1, "address": "742 Evergreen Terrace", "city": "Springfield", "state": "Oregon", "point": { "type": "Point", "coordinates": [-123.0208, 44.0464], } } **Note:** For ``ver>=0.9.3``: The DRF model serializer will give the same output as above, if; - ``rest_framework_gis`` is set in ``settings.INSTALLED_APPS`` or - the field in the serializer is set explicitly as ``GeometryField``. GeoFeatureModelSerializer ~~~~~~~~~~~~~~~~~~~~~~~~~ ``GeoFeatureModelSerializer`` is a subclass of ``rest_framework.ModelSerializer`` which will output data in a format that is **GeoJSON** compatible. Using the above example, the ``GeoFeatureModelSerializer`` will output: .. code-block:: javascript { "id": 1, "type": "Feature", "geometry": { "type": "Point", "coordinates": [-123.0208, 44.0464], }, "properties": { "address": "742 Evergreen Terrace", "city": "Springfield", "state": "Oregon" } } If you are serializing an object list, ``GeoFeatureModelSerializer`` will create a ``FeatureCollection``: .. code-block:: javascript { "type": "FeatureCollection", "features": [ { "id": 1 "type": "Feature", "geometry": { "type": "Point", "coordinates": [-123.0208, 44.0464], }, "properties": { "address": "742 Evergreen Terrace", "city": "Springfield", "state": "Oregon", } } { "id": 2, "type": "Feature", "geometry": { "type": "Point", "coordinates": [-123.0208, 44.0489], }, "properties": { "address": "744 Evergreen Terrace", "city": "Springfield", "state": "Oregon" } } } Specifying the geometry field: "geo_field" ########################################## ``GeoFeatureModelSerializer`` requires you to define a ``geo_field`` to be serialized as the "geometry". For example: .. code-block:: python from rest_framework_gis.serializers import GeoFeatureModelSerializer class LocationSerializer(GeoFeatureModelSerializer): """ A class to serialize locations as GeoJSON compatible data """ class Meta: model = Location geo_field = "point" # you can also explicitly declare which fields you want to include # as with a ModelSerializer. fields = ('id', 'address', 'city', 'state') Using GeometrySerializerMethodField as "geo_field" ################################################## ``geo_field`` may also be an instance of ``GeometrySerializerMethodField``. In this case you can compute its value during serialization. For example: .. code-block:: python from django.contrib.gis.geos import Point from rest_framework_gis.serializers import GeoFeatureModelSerializer, GeometrySerializerMethodField class LocationSerializer(GeoFeatureModelSerializer): """ A class to serialize locations as GeoJSON compatible data """ # a field which contains a geometry value and can be used as geo_field other_point = GeometrySerializerMethodField() def get_other_point(self, obj): return Point(obj.point.lat / 2, obj.point.lon / 2) class Meta: model = Location geo_field = 'other_point' Serializer for ``geo_field`` may also return ``None`` value, which will translate to ``null`` value for geojson ``geometry`` field. Specifying the ID: "id_field" ############################# The primary key of the model (usually the "id" attribute) is automatically used as the ``id`` field of each `GeoJSON Feature Object `_. The default behaviour follows the `GeoJSON RFC `_, but it can be disabled by setting ``id_field`` to ``False``: .. code-block:: python from rest_framework_gis.serializers import GeoFeatureModelSerializer class LocationSerializer(GeoFeatureModelSerializer): class Meta: model = Location geo_field = "point" id_field = False fields = ('id', 'address', 'city', 'state') The ``id_field`` can also be set to use some other unique field in your model, eg: ``slug``: .. code-block:: python from rest_framework_gis.serializers import GeoFeatureModelSerializer class LocationSerializer(GeoFeatureModelSerializer): class Meta: model = Location geo_field = 'point' id_field = 'slug' fields = ('slug', 'address', 'city', 'state') Bounding Box: "auto_bbox" and "bbox_geo_field" ############################################## The GeoJSON specification allows a feature to contain a `boundingbox of a feature `__. ``GeoFeatureModelSerializer`` allows two different ways to fill this property. The first is using the ``geo_field`` to calculate the bounding box of a feature. This only allows read access for a REST client and can be achieved using ``auto_bbox``. Example: .. code-block:: python from rest_framework_gis.serializers import GeoFeatureModelSerializer class LocationSerializer(GeoFeatureModelSerializer): class Meta: model = Location geo_field = 'geometry' auto_bbox = True The second approach uses the ``bbox_geo_field`` to specify an additional ``GeometryField`` of the model which will be used to calculate the bounding box. This allows boundingboxes differ from the exact extent of a features geometry. Additionally this enables read and write access for the REST client. Bounding boxes send from the client will be saved as Polygons. Example: .. code-block:: python from rest_framework_gis.serializers import GeoFeatureModelSerializer class LocationSerializer(GeoFeatureModelSerializer): class Meta: model = BoxedLocation geo_field = 'geometry' bbox_geo_field = 'bbox_geometry' Custom GeoJSON properties source ################################ In GeoJSON each feature can have a ``properties`` member containing the attributes of the feature. By default this field is filled with the attributes from your Django model, excluding the id, geometry and bounding box fields. It's possible to override this behaviour and implement a custom source for the ``properties`` member. The following example shows how to use a PostgreSQL HStore field as a source for the ``properties`` member: .. code-block:: python # models.py class Link(models.Model): """ Metadata is stored in a PostgreSQL HStore field, which allows us to store arbitrary key-value pairs with a link record. """ metadata = HStoreField(blank=True, null=True, default=dict) geo = models.LineStringField() objects = models.GeoManager() # serializers.py class NetworkGeoSerializer(GeoFeatureModelSerializer): class Meta: model = models.Link geo_field = 'geo' auto_bbox = True def get_properties(self, instance, fields): # This is a PostgreSQL HStore field, which django maps to a dict return instance.metadata def unformat_geojson(self, feature): attrs = { self.Meta.geo_field: feature["geometry"], "metadata": feature["properties"] } if self.Meta.bbox_geo_field and "bbox" in feature: attrs[self.Meta.bbox_geo_field] = Polygon.from_bbox(feature["bbox"]) return attrs When the serializer renders GeoJSON, it calls the method ``get_properties`` for each object in the database. This function should return a dictionary containing the attributes for the feature. In the case of a HStore field, this function is easily implemented. The reverse is also required: mapping a GeoJSON formatted structure to attributes of your model. This task is done by ``unformat_geojson``. It should return a dictionary with your model attributes as keys, and the corresponding values retrieved from the GeoJSON feature data. Pagination ---------- We provide a ``GeoJsonPagination`` class. GeoJsonPagination ~~~~~~~~~~~~~~~~~ Based on ``rest_framework.pagination.PageNumberPagination``. Code example: .. code-block:: python from rest_framework_gis.pagination import GeoJsonPagination # --- other omitted imports --- # class GeojsonLocationList(generics.ListCreateAPIView): # -- other omitted view attributes --- # pagination_class = GeoJsonPagination Example result response (cut to one element only instead of 10): .. code-block:: javascript { "type": "FeatureCollection", "count": 25, "next": "http://localhost:8000/geojson/?page=2", "previous": null, "features": [ { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 42.0, 50.0 ] }, "properties": { "name": "test" } } ] } Filters ------- **note**: this feature has been tested up to django-filter 1.0. We provide a ``GeometryFilter`` field as well as a ``GeoFilterSet`` for usage with ``django_filter``. You simply provide, in the query string, one of the textual types supported by ``GEOSGeometry``. By default, this includes WKT, HEXEWKB, WKB (in a buffer), and GeoJSON. GeometryFilter ~~~~~~~~~~~~~~ .. code-block:: python from rest_framework_gis.filterset import GeoFilterSet from rest_framework_gis.filters import GeometryFilter from django_filters import filters class RegionFilter(GeoFilterSet): slug = filters.CharFilter(name='slug', lookup_expr='istartswith') contains_geom = GeometryFilter(name='geom', lookup_expr='contains') class Meta: model = Region We can then filter in the URL, using GeoJSON, and we will perform a ``__contains`` geometry lookup, e.g. ``/region/?contains_geom={ "type": "Point", "coordinates": [ -123.26436996459961, 44.564178042345375 ] }``. GeoFilterSet ~~~~~~~~~~~~ The ``GeoFilterSet`` provides a ``django_filter`` compatible ``FilterSet`` that will automatically create ``GeometryFilters`` for ``GeometryFields``. InBBoxFilter ~~~~~~~~~~~~ Provides a ``InBBoxFilter``, which is a subclass of DRF ``BaseFilterBackend``. Filters a queryset to only those instances within a certain bounding box. ``views.py:`` .. code-block:: python from rest_framework_gis.filters import InBBoxFilter class LocationList(ListAPIView): queryset = models.Location.objects.all() serializer_class = serializers.LocationSerializer bbox_filter_field = 'point' filter_backends = (InBBoxFilter,) bbox_filter_include_overlapping = True # Optional We can then filter in the URL, using Bounding Box format (min Lon, min Lat, max Lon, max Lat), and we can search for instances within the bounding box, e.g.: ``/location/?in_bbox=-90,29,-89,35``. By default, InBBoxFilter will only return those instances entirely within the stated bounding box. To include those instances which overlap the bounding box, include ``bbox_filter_include_overlapping = True`` in your view. Note that if you are using other filters, you'll want to include your other filter backend in your view. For example: ``filter_backends = (InBBoxFilter, DjangoFilterBackend,)`` TMSTileFilter ~~~~~~~~~~~~~ Provides a ``TMSTileFilter``, which is a subclass of ``InBBoxFilter``. Filters a queryset to only those instances within a bounding box defined by a `TMS tile `__ address. ``views.py:`` .. code-block:: python from rest_framework_gis.filters import TMSTileFilter class LocationList(ListAPIView): queryset = models.Location.objects.all() serializer_class = serializers.LocationSerializer bbox_filter_field = 'point' filter_backends = (TMSTileFilter,) bbox_filter_include_overlapping = True # Optional We can then filter in the URL, using TMS tile addresses in the zoom/x/y format, eg:. ``/location/?tile=8/100/200`` which is equivalent to filtering on the bbox (-39.37500,-71.07406,-37.96875,-70.61261). For more information on configuration options see InBBoxFilter. Note that the tile address start in the upper left, not the lower left origin used by some implementations. DistanceToPointFilter ~~~~~~~~~~~~~~~~~~~~~ Provides a ``DistanceToPointFilter``, which is a subclass of DRF ``BaseFilterBackend``. Filters a queryset to only those instances within a certain distance of a given point. ``views.py:`` .. code-block:: python from rest_framework_gis.filters import DistanceToPointFilter class LocationList(ListAPIView): queryset = models.Location.objects.all() serializer_class = serializers.LocationSerializer distance_filter_field = 'geometry' filter_backends = (DistanceToPointFilter,) We can then filter in the URL, using a distance and a point in (lon, lat) format. The distance can be given in meters or in degrees. eg:. ``/location/?dist=4000&point=-122.4862,37.7694&format=json`` which is equivalent to filtering within 4000 meters of the point (-122.4862, 37.7694). By default, DistanceToPointFilter will pass the 'distance' in the URL directly to the database for the search. The effect depends on the srid of the database in use. If geo data is indexed in meters (srid 3875, aka 900913), a distance in meters can be passed in directly without conversion. For lat-lon databases such as srid 4326, which is indexed in degrees, the 'distance' will be interpreted as degrees. Set the flag, 'distance_filter_convert_meters' to 'True' in order to convert an input distance in meters to degrees. This conversion is approximate, and the errors at latitudes > 60 degrees are > 25%. DistanceToPointOrderingFilter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provides a ``DistanceToPointOrderingFilter``, **available on Django >= 3.0**, which is a subclass of ``DistanceToPointFilter``. Orders a queryset by distance to a given point, from the nearest to the most distant point. ``views.py:`` .. code-block:: python from rest_framework_gis.filters import DistanceToPointOrderingFilter class LocationList(ListAPIView): queryset = models.Location.objects.all() serializer_class = serializers.LocationSerializer distance_ordering_filter_field = 'geometry' filter_backends = (DistanceToPointOrderingFilter,) We can then order the results by passing a point in (lon, lat) format in the URL. eg:. ``/location/?point=-122.4862,37.7694&format=json`` will order the results by the distance to the point (-122.4862, 37.7694). We can also reverse the order of the results by passing ``order=desc``: ``/location/?point=-122.4862,37.7694&order=desc&format=json`` Schema Generation ----------------- Note: Schema generation support is available only for DRF >= 3.12. Simplest Approach would be, change ``DEFAULT_SCHEMA_CLASS`` to ``rest_framework_gis.schema.GeoFeatureAutoSchema``: .. code-block:: python REST_FRAMEWORK = { ... 'DEFAULT_SCHEMA_CLASS': 'rest_framework_gis.schema.GeoFeatureAutoSchema', ... } If you do not want to change default schema generator class: - You can pass this class as an argument to ``get_schema_view`` function `[Ref] `__. - You can pass this class as an argument to the ``generateschema`` command `[Ref] `__. Running the tests ----------------- Required setup ============== You need one of the `Spatial Database servers supported by GeoDjango `__, and create a database for the tests. The following can be used with PostgreSQL: .. code-block:: bash createdb django_restframework_gis psql -U postgres -d django_restframework_gis -c "CREATE EXTENSION postgis" You might need to tweak the DB settings according to your DB configuration. You can copy the file ``local_settings.example.py`` to ``local_settings.py`` and change the ``DATABASES`` and/or ``INSTALLED_APPS`` directives there. This should allow you to run the tests already. For reference, the following steps will setup a development environment for contributing to the project: - create a spatial database named "django\_restframework\_gis" - create ``local_settings.py``, eg: ``cp local_settings.example.py local_settings.py`` - tweak the ``DATABASES`` configuration directive according to your DB settings - uncomment ``INSTALLED_APPS`` - run ``python manage.py syncdb`` - run ``python manage.py collectstatic`` - run ``python manage.py runserver`` Using tox ========= The recommended way to run the tests is by using `tox `__, which can be installed using `pip install tox`. You can use ``tox -l`` to list the available environments, and then e.g. use the following to run all tests with Python 3.6 and Django 1.11: .. code-block:: bash tox -e py36-django111 By default Django's test runner is used, but there is a variation of tox's envlist to use pytest (using the ``-pytest`` suffix). You can pass optional arguments to the test runner like this: .. code-block:: bash tox -e py36-django111-pytest -- -k test_foo Running tests manually ====================== Please refer to the ``tox.ini`` file for reference/help in case you want to run tests manually / without tox. To run tests in docker use .. code-block:: bash docker-compose build docker-compose run --rm test Running QA-checks ================= Install the test requirements: .. code-block:: shell pip install -r requirements-test.txt Reformat the code according to `our coding style conventions with `_: .. code-block:: shell openwisp-qa-format Run the QA checks by using .. code-block:: shell ./run-qa-checks In docker testing, QA checks are executed automatically. Contributing ------------ 1. Join the `Django REST Framework GIS Mailing List `__ and announce your intentions 2. Follow the `PEP8 Style Guide for Python Code `__ 3. Fork this repo 4. Write code 5. Write tests for your code 6. Ensure all tests pass 7. Ensure test coverage is not under 90% 8. Document your changes 9. Send pull request .. |Build Status| image:: https://github.com/openwisp/django-rest-framework-gis/workflows/Django%20Rest%20Framework%20Gis%20CI%20Build/badge.svg?branch=master :target: https://github.com/openwisp/django-rest-framework-gis/actions?query=workflow%3A%22Django+Rest+Framework+Gis+CI+Build%22 .. |Coverage Status| image:: https://coveralls.io/repos/openwisp/django-rest-framework-gis/badge.svg :target: https://coveralls.io/r/openwisp/django-rest-framework-gis .. |Requirements Status| image:: https://img.shields.io/librariesio/release/github/openwisp/django-rest-framework-gis :target: https://libraries.io/github/openwisp/django-rest-framework-gis#repository_dependencies :alt: Dependency monitoring .. |PyPI version| image:: https://badge.fury.io/py/djangorestframework-gis.svg :target: http://badge.fury.io/py/djangorestframework-gis .. |PyPI downloads| image:: https://pepy.tech/badge/djangorestframework-gis/month :target: https://pepy.tech/project/djangorestframework-gis .. |Black| image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://pypi.org/project/black/ ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1641563955.0 djangorestframework-gis-0.18/README.rst0000664000175000017500000006555400000000000021141 0ustar00nemesisnemesis00000000000000django-rest-framework-gis ========================= |Build Status| |Coverage Status| |Requirements Status| |PyPI version| |PyPI downloads| |Black| Geographic add-ons for Django Rest Framework - `Mailing List `__. Install last stable version from pypi ------------------------------------- .. code-block:: bash pip install djangorestframework-gis Install development version --------------------------- .. code-block:: bash pip install https://github.com/openwisp/django-rest-framework-gis/tarball/master Setup ----- Add ``rest_framework_gis`` in ``settings.INSTALLED_APPS``, after ``rest_framework``: .. code-block:: python INSTALLED_APPS = [ # ... 'rest_framework', 'rest_framework_gis', # ... ] Compatibility with DRF, Django and Python ----------------------------------------- ======================== ============================ ==================== ================================== DRF-gis version DRF version Django version Python version **0.18.x** **3.10** up to **3.13** **2.2 to 4.0** **3.6** to **3.9** **0.17.x** **3.10** up to **3.12** **2.2 to 3.1** **3.6** to **3.8** **0.16.x** **3.10** **2.2 to 3.1** **3.6** to **3.8** **0.15.x** **3.10** **1.11, 2.2 to 3.0** **3.5** to **3.8** **0.14.x** **3.3** to **3.9** **1.11** to **2.1** **3.4** to **3.7** **0.13.x** **3.3** to **3.8** **1.11** to **2.0** **2.7** to **3.6** **0.12.x** **3.1** to **3.7** **1.11** to **2.0** **2.7** to **3.6** **0.11.x** **3.1** to **3.6** **1.7** to **1.11** **2.7** to **3.6** **0.10.x** **3.1** to **3.3** **1.7** to **1.9** **2.7** to **3.5** **0.9.6** **3.1** to **3.2** **1.5** to **1.8** **2.6** to **3.5** **0.9.5** **3.1** to **3.2** **1.5** to **1.8** **2.6** to **3.4** **0.9.4** **3.1** to **3.2** **1.5** to **1.8** **2.6** to **3.4** **0.9.3** **3.1** **1.5** to **1.8** **2.6** to **3.4** **0.9.2** **3.1** **1.5** to **1.8** **2.6** to **3.4** **0.9.1** **3.1** **1.5** to **1.8** **2.6** to **3.4** **0.9** **3.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** **0.9** **3.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** **0.9** **3.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** **0.8.2** **3.0.4** to **3.1.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** **0.8.1** **3.0.4** to **3.1.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** **0.8** **3.0.4** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** **0.7** **2.4.3** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** **0.6** **2.4.3** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** **0.5** from **2.3.14** to **2.4.2** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** **0.4** from **2.3.14** to **2.4.2** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** **0.3** from **2.3.14** to **2.4.2** **1.5**, **1.6** **2.6**, **2.7** **0.2** from **2.2.2** to **2.3.13** **1.5**, **1.6** **2.6**, **2.7** ======================== ============================ ==================== ================================== Fields ------ GeometryField ~~~~~~~~~~~~~ Provides a ``GeometryField``, which is a subclass of Django Rest Framework (from now on **DRF**) ``WritableField``. This field handles GeoDjango geometry fields, providing custom ``to_native`` and ``from_native`` methods for GeoJSON input/output. This field takes two optional arguments: ``precision``: Passes coordinates through Python's builtin ``round()`` function (`docs `_), rounding values to the provided level of precision. E.g. A Point with lat/lng of ``[51.0486, -114.0708]`` passed through a ``GeometryField(precision=2)`` would return a Point with a lat/lng of ``[51.05, -114.07]``. ``remove_duplicates``: Remove sequential duplicate coordinates from line and polygon geometries. This is particularly useful when used with the ``precision`` argument, as the likelihood of duplicate coordinates increase as precision of coordinates are reduced. **Note:** While both above arguments are designed to reduce the byte size of the API response, they will also increase the processing time required to render the response. This will likely be negligible for small GeoJSON responses but may become an issue for large responses. **New in 0.9.3:** there is no need to define this field explicitly in your serializer, it's mapped automatically during initialization in ``rest_framework_gis.apps.AppConfig.ready()``. GeometrySerializerMethodField ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provides a ``GeometrySerializerMethodField``, which is a subclass of DRF ``SerializerMethodField`` and handles values which are computed with a serializer method and are used as a ``geo_field``. `See example below `__. Serializers ----------- GeoModelSerializer (DEPRECATED) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ **Deprecated, will be removed in 1.0**: Using this serializer is not needed anymore since 0.9.3, if you add ``rest_framework_gis`` in ``settings.INSTALLED_APPS`` the serialization will work out of the box with DRF. Refer `Issue #156 `__. Provides a ``GeoModelSerializer``, which is a subclass of DRF ``ModelSerializer``. This serializer updates the field\_mapping dictionary to include field mapping of GeoDjango geometry fields to the above ``GeometryField``. For example, the following model: .. code-block:: python class Location(models.Model): """ A model which holds information about a particular location """ address = models.CharField(max_length=255) city = models.CharField(max_length=100) state = models.CharField(max_length=100) point = models.PointField() By default, the DRF ModelSerializer **ver < 0.9.3** will output: .. code-block:: javascript { "id": 1, "address": "742 Evergreen Terrace", "city": "Springfield", "state": "Oregon", "point": "POINT(-123.0208 44.0464)" } In contrast, the ``GeoModelSerializer`` will output: .. code-block:: javascript { "id": 1, "address": "742 Evergreen Terrace", "city": "Springfield", "state": "Oregon", "point": { "type": "Point", "coordinates": [-123.0208, 44.0464], } } **Note:** For ``ver>=0.9.3``: The DRF model serializer will give the same output as above, if; - ``rest_framework_gis`` is set in ``settings.INSTALLED_APPS`` or - the field in the serializer is set explicitly as ``GeometryField``. GeoFeatureModelSerializer ~~~~~~~~~~~~~~~~~~~~~~~~~ ``GeoFeatureModelSerializer`` is a subclass of ``rest_framework.ModelSerializer`` which will output data in a format that is **GeoJSON** compatible. Using the above example, the ``GeoFeatureModelSerializer`` will output: .. code-block:: javascript { "id": 1, "type": "Feature", "geometry": { "type": "Point", "coordinates": [-123.0208, 44.0464], }, "properties": { "address": "742 Evergreen Terrace", "city": "Springfield", "state": "Oregon" } } If you are serializing an object list, ``GeoFeatureModelSerializer`` will create a ``FeatureCollection``: .. code-block:: javascript { "type": "FeatureCollection", "features": [ { "id": 1 "type": "Feature", "geometry": { "type": "Point", "coordinates": [-123.0208, 44.0464], }, "properties": { "address": "742 Evergreen Terrace", "city": "Springfield", "state": "Oregon", } } { "id": 2, "type": "Feature", "geometry": { "type": "Point", "coordinates": [-123.0208, 44.0489], }, "properties": { "address": "744 Evergreen Terrace", "city": "Springfield", "state": "Oregon" } } } Specifying the geometry field: "geo_field" ########################################## ``GeoFeatureModelSerializer`` requires you to define a ``geo_field`` to be serialized as the "geometry". For example: .. code-block:: python from rest_framework_gis.serializers import GeoFeatureModelSerializer class LocationSerializer(GeoFeatureModelSerializer): """ A class to serialize locations as GeoJSON compatible data """ class Meta: model = Location geo_field = "point" # you can also explicitly declare which fields you want to include # as with a ModelSerializer. fields = ('id', 'address', 'city', 'state') Using GeometrySerializerMethodField as "geo_field" ################################################## ``geo_field`` may also be an instance of ``GeometrySerializerMethodField``. In this case you can compute its value during serialization. For example: .. code-block:: python from django.contrib.gis.geos import Point from rest_framework_gis.serializers import GeoFeatureModelSerializer, GeometrySerializerMethodField class LocationSerializer(GeoFeatureModelSerializer): """ A class to serialize locations as GeoJSON compatible data """ # a field which contains a geometry value and can be used as geo_field other_point = GeometrySerializerMethodField() def get_other_point(self, obj): return Point(obj.point.lat / 2, obj.point.lon / 2) class Meta: model = Location geo_field = 'other_point' Serializer for ``geo_field`` may also return ``None`` value, which will translate to ``null`` value for geojson ``geometry`` field. Specifying the ID: "id_field" ############################# The primary key of the model (usually the "id" attribute) is automatically used as the ``id`` field of each `GeoJSON Feature Object `_. The default behaviour follows the `GeoJSON RFC `_, but it can be disabled by setting ``id_field`` to ``False``: .. code-block:: python from rest_framework_gis.serializers import GeoFeatureModelSerializer class LocationSerializer(GeoFeatureModelSerializer): class Meta: model = Location geo_field = "point" id_field = False fields = ('id', 'address', 'city', 'state') The ``id_field`` can also be set to use some other unique field in your model, eg: ``slug``: .. code-block:: python from rest_framework_gis.serializers import GeoFeatureModelSerializer class LocationSerializer(GeoFeatureModelSerializer): class Meta: model = Location geo_field = 'point' id_field = 'slug' fields = ('slug', 'address', 'city', 'state') Bounding Box: "auto_bbox" and "bbox_geo_field" ############################################## The GeoJSON specification allows a feature to contain a `boundingbox of a feature `__. ``GeoFeatureModelSerializer`` allows two different ways to fill this property. The first is using the ``geo_field`` to calculate the bounding box of a feature. This only allows read access for a REST client and can be achieved using ``auto_bbox``. Example: .. code-block:: python from rest_framework_gis.serializers import GeoFeatureModelSerializer class LocationSerializer(GeoFeatureModelSerializer): class Meta: model = Location geo_field = 'geometry' auto_bbox = True The second approach uses the ``bbox_geo_field`` to specify an additional ``GeometryField`` of the model which will be used to calculate the bounding box. This allows boundingboxes differ from the exact extent of a features geometry. Additionally this enables read and write access for the REST client. Bounding boxes send from the client will be saved as Polygons. Example: .. code-block:: python from rest_framework_gis.serializers import GeoFeatureModelSerializer class LocationSerializer(GeoFeatureModelSerializer): class Meta: model = BoxedLocation geo_field = 'geometry' bbox_geo_field = 'bbox_geometry' Custom GeoJSON properties source ################################ In GeoJSON each feature can have a ``properties`` member containing the attributes of the feature. By default this field is filled with the attributes from your Django model, excluding the id, geometry and bounding box fields. It's possible to override this behaviour and implement a custom source for the ``properties`` member. The following example shows how to use a PostgreSQL HStore field as a source for the ``properties`` member: .. code-block:: python # models.py class Link(models.Model): """ Metadata is stored in a PostgreSQL HStore field, which allows us to store arbitrary key-value pairs with a link record. """ metadata = HStoreField(blank=True, null=True, default=dict) geo = models.LineStringField() objects = models.GeoManager() # serializers.py class NetworkGeoSerializer(GeoFeatureModelSerializer): class Meta: model = models.Link geo_field = 'geo' auto_bbox = True def get_properties(self, instance, fields): # This is a PostgreSQL HStore field, which django maps to a dict return instance.metadata def unformat_geojson(self, feature): attrs = { self.Meta.geo_field: feature["geometry"], "metadata": feature["properties"] } if self.Meta.bbox_geo_field and "bbox" in feature: attrs[self.Meta.bbox_geo_field] = Polygon.from_bbox(feature["bbox"]) return attrs When the serializer renders GeoJSON, it calls the method ``get_properties`` for each object in the database. This function should return a dictionary containing the attributes for the feature. In the case of a HStore field, this function is easily implemented. The reverse is also required: mapping a GeoJSON formatted structure to attributes of your model. This task is done by ``unformat_geojson``. It should return a dictionary with your model attributes as keys, and the corresponding values retrieved from the GeoJSON feature data. Pagination ---------- We provide a ``GeoJsonPagination`` class. GeoJsonPagination ~~~~~~~~~~~~~~~~~ Based on ``rest_framework.pagination.PageNumberPagination``. Code example: .. code-block:: python from rest_framework_gis.pagination import GeoJsonPagination # --- other omitted imports --- # class GeojsonLocationList(generics.ListCreateAPIView): # -- other omitted view attributes --- # pagination_class = GeoJsonPagination Example result response (cut to one element only instead of 10): .. code-block:: javascript { "type": "FeatureCollection", "count": 25, "next": "http://localhost:8000/geojson/?page=2", "previous": null, "features": [ { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 42.0, 50.0 ] }, "properties": { "name": "test" } } ] } Filters ------- **note**: this feature has been tested up to django-filter 1.0. We provide a ``GeometryFilter`` field as well as a ``GeoFilterSet`` for usage with ``django_filter``. You simply provide, in the query string, one of the textual types supported by ``GEOSGeometry``. By default, this includes WKT, HEXEWKB, WKB (in a buffer), and GeoJSON. GeometryFilter ~~~~~~~~~~~~~~ .. code-block:: python from rest_framework_gis.filterset import GeoFilterSet from rest_framework_gis.filters import GeometryFilter from django_filters import filters class RegionFilter(GeoFilterSet): slug = filters.CharFilter(name='slug', lookup_expr='istartswith') contains_geom = GeometryFilter(name='geom', lookup_expr='contains') class Meta: model = Region We can then filter in the URL, using GeoJSON, and we will perform a ``__contains`` geometry lookup, e.g. ``/region/?contains_geom={ "type": "Point", "coordinates": [ -123.26436996459961, 44.564178042345375 ] }``. GeoFilterSet ~~~~~~~~~~~~ The ``GeoFilterSet`` provides a ``django_filter`` compatible ``FilterSet`` that will automatically create ``GeometryFilters`` for ``GeometryFields``. InBBoxFilter ~~~~~~~~~~~~ Provides a ``InBBoxFilter``, which is a subclass of DRF ``BaseFilterBackend``. Filters a queryset to only those instances within a certain bounding box. ``views.py:`` .. code-block:: python from rest_framework_gis.filters import InBBoxFilter class LocationList(ListAPIView): queryset = models.Location.objects.all() serializer_class = serializers.LocationSerializer bbox_filter_field = 'point' filter_backends = (InBBoxFilter,) bbox_filter_include_overlapping = True # Optional We can then filter in the URL, using Bounding Box format (min Lon, min Lat, max Lon, max Lat), and we can search for instances within the bounding box, e.g.: ``/location/?in_bbox=-90,29,-89,35``. By default, InBBoxFilter will only return those instances entirely within the stated bounding box. To include those instances which overlap the bounding box, include ``bbox_filter_include_overlapping = True`` in your view. Note that if you are using other filters, you'll want to include your other filter backend in your view. For example: ``filter_backends = (InBBoxFilter, DjangoFilterBackend,)`` TMSTileFilter ~~~~~~~~~~~~~ Provides a ``TMSTileFilter``, which is a subclass of ``InBBoxFilter``. Filters a queryset to only those instances within a bounding box defined by a `TMS tile `__ address. ``views.py:`` .. code-block:: python from rest_framework_gis.filters import TMSTileFilter class LocationList(ListAPIView): queryset = models.Location.objects.all() serializer_class = serializers.LocationSerializer bbox_filter_field = 'point' filter_backends = (TMSTileFilter,) bbox_filter_include_overlapping = True # Optional We can then filter in the URL, using TMS tile addresses in the zoom/x/y format, eg:. ``/location/?tile=8/100/200`` which is equivalent to filtering on the bbox (-39.37500,-71.07406,-37.96875,-70.61261). For more information on configuration options see InBBoxFilter. Note that the tile address start in the upper left, not the lower left origin used by some implementations. DistanceToPointFilter ~~~~~~~~~~~~~~~~~~~~~ Provides a ``DistanceToPointFilter``, which is a subclass of DRF ``BaseFilterBackend``. Filters a queryset to only those instances within a certain distance of a given point. ``views.py:`` .. code-block:: python from rest_framework_gis.filters import DistanceToPointFilter class LocationList(ListAPIView): queryset = models.Location.objects.all() serializer_class = serializers.LocationSerializer distance_filter_field = 'geometry' filter_backends = (DistanceToPointFilter,) We can then filter in the URL, using a distance and a point in (lon, lat) format. The distance can be given in meters or in degrees. eg:. ``/location/?dist=4000&point=-122.4862,37.7694&format=json`` which is equivalent to filtering within 4000 meters of the point (-122.4862, 37.7694). By default, DistanceToPointFilter will pass the 'distance' in the URL directly to the database for the search. The effect depends on the srid of the database in use. If geo data is indexed in meters (srid 3875, aka 900913), a distance in meters can be passed in directly without conversion. For lat-lon databases such as srid 4326, which is indexed in degrees, the 'distance' will be interpreted as degrees. Set the flag, 'distance_filter_convert_meters' to 'True' in order to convert an input distance in meters to degrees. This conversion is approximate, and the errors at latitudes > 60 degrees are > 25%. DistanceToPointOrderingFilter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provides a ``DistanceToPointOrderingFilter``, **available on Django >= 3.0**, which is a subclass of ``DistanceToPointFilter``. Orders a queryset by distance to a given point, from the nearest to the most distant point. ``views.py:`` .. code-block:: python from rest_framework_gis.filters import DistanceToPointOrderingFilter class LocationList(ListAPIView): queryset = models.Location.objects.all() serializer_class = serializers.LocationSerializer distance_ordering_filter_field = 'geometry' filter_backends = (DistanceToPointOrderingFilter,) We can then order the results by passing a point in (lon, lat) format in the URL. eg:. ``/location/?point=-122.4862,37.7694&format=json`` will order the results by the distance to the point (-122.4862, 37.7694). We can also reverse the order of the results by passing ``order=desc``: ``/location/?point=-122.4862,37.7694&order=desc&format=json`` Schema Generation ----------------- Note: Schema generation support is available only for DRF >= 3.12. Simplest Approach would be, change ``DEFAULT_SCHEMA_CLASS`` to ``rest_framework_gis.schema.GeoFeatureAutoSchema``: .. code-block:: python REST_FRAMEWORK = { ... 'DEFAULT_SCHEMA_CLASS': 'rest_framework_gis.schema.GeoFeatureAutoSchema', ... } If you do not want to change default schema generator class: - You can pass this class as an argument to ``get_schema_view`` function `[Ref] `__. - You can pass this class as an argument to the ``generateschema`` command `[Ref] `__. Running the tests ----------------- Required setup ============== You need one of the `Spatial Database servers supported by GeoDjango `__, and create a database for the tests. The following can be used with PostgreSQL: .. code-block:: bash createdb django_restframework_gis psql -U postgres -d django_restframework_gis -c "CREATE EXTENSION postgis" You might need to tweak the DB settings according to your DB configuration. You can copy the file ``local_settings.example.py`` to ``local_settings.py`` and change the ``DATABASES`` and/or ``INSTALLED_APPS`` directives there. This should allow you to run the tests already. For reference, the following steps will setup a development environment for contributing to the project: - create a spatial database named "django\_restframework\_gis" - create ``local_settings.py``, eg: ``cp local_settings.example.py local_settings.py`` - tweak the ``DATABASES`` configuration directive according to your DB settings - uncomment ``INSTALLED_APPS`` - run ``python manage.py syncdb`` - run ``python manage.py collectstatic`` - run ``python manage.py runserver`` Using tox ========= The recommended way to run the tests is by using `tox `__, which can be installed using `pip install tox`. You can use ``tox -l`` to list the available environments, and then e.g. use the following to run all tests with Python 3.6 and Django 1.11: .. code-block:: bash tox -e py36-django111 By default Django's test runner is used, but there is a variation of tox's envlist to use pytest (using the ``-pytest`` suffix). You can pass optional arguments to the test runner like this: .. code-block:: bash tox -e py36-django111-pytest -- -k test_foo Running tests manually ====================== Please refer to the ``tox.ini`` file for reference/help in case you want to run tests manually / without tox. To run tests in docker use .. code-block:: bash docker-compose build docker-compose run --rm test Running QA-checks ================= Install the test requirements: .. code-block:: shell pip install -r requirements-test.txt Reformat the code according to `our coding style conventions with `_: .. code-block:: shell openwisp-qa-format Run the QA checks by using .. code-block:: shell ./run-qa-checks In docker testing, QA checks are executed automatically. Contributing ------------ 1. Join the `Django REST Framework GIS Mailing List `__ and announce your intentions 2. Follow the `PEP8 Style Guide for Python Code `__ 3. Fork this repo 4. Write code 5. Write tests for your code 6. Ensure all tests pass 7. Ensure test coverage is not under 90% 8. Document your changes 9. Send pull request .. |Build Status| image:: https://github.com/openwisp/django-rest-framework-gis/workflows/Django%20Rest%20Framework%20Gis%20CI%20Build/badge.svg?branch=master :target: https://github.com/openwisp/django-rest-framework-gis/actions?query=workflow%3A%22Django+Rest+Framework+Gis+CI+Build%22 .. |Coverage Status| image:: https://coveralls.io/repos/openwisp/django-rest-framework-gis/badge.svg :target: https://coveralls.io/r/openwisp/django-rest-framework-gis .. |Requirements Status| image:: https://img.shields.io/librariesio/release/github/openwisp/django-rest-framework-gis :target: https://libraries.io/github/openwisp/django-rest-framework-gis#repository_dependencies :alt: Dependency monitoring .. |PyPI version| image:: https://badge.fury.io/py/djangorestframework-gis.svg :target: http://badge.fury.io/py/djangorestframework-gis .. |PyPI downloads| image:: https://pepy.tech/badge/djangorestframework-gis/month :target: https://pepy.tech/project/djangorestframework-gis .. |Black| image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://pypi.org/project/black/ ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1641564397.384531 djangorestframework-gis-0.18/djangorestframework_gis.egg-info/0000775000175000017500000000000000000000000026045 5ustar00nemesisnemesis00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1641564397.0 djangorestframework-gis-0.18/djangorestframework_gis.egg-info/PKG-INFO0000644000175000017500000007061700000000000027153 0ustar00nemesisnemesis00000000000000Metadata-Version: 2.1 Name: djangorestframework-gis Version: 0.18 Summary: Geographic add-ons for Django Rest Framework Home-page: https://github.com/openwisp/django-rest-framework-gis Author: Douglas Meehan Author-email: django-rest-framework-gis@googlegroups.com License: BSD Download-URL: https://github.com/openwisp/django-rest-framework-gis/releases Project-URL: Bug Reports, https://github.com/openwisp/django-rest-framework-gis/issues Project-URL: Continuous Integration, https://travis-ci.org/openwisp/django-rest-framework-gis Project-URL: Mailing List, https://groups.google.com/forum/#!forum/django-rest-framework-gis Project-URL: Code Coverage, https://coveralls.io/github/openwisp/django-rest-framework-gis Project-URL: Source Code, https://github.com/openwisp/django-rest-framework-gis Keywords: django,rest-framework,gis,geojson Platform: Platform Indipendent Classifier: Development Status :: 4 - Beta Classifier: Environment :: Web Environment Classifier: Topic :: Internet :: WWW/HTTP Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Framework :: Django Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3 :: Only License-File: LICENSE License-File: AUTHORS django-rest-framework-gis ========================= |Build Status| |Coverage Status| |Requirements Status| |PyPI version| |PyPI downloads| |Black| Geographic add-ons for Django Rest Framework - `Mailing List `__. Install last stable version from pypi ------------------------------------- .. code-block:: bash pip install djangorestframework-gis Install development version --------------------------- .. code-block:: bash pip install https://github.com/openwisp/django-rest-framework-gis/tarball/master Setup ----- Add ``rest_framework_gis`` in ``settings.INSTALLED_APPS``, after ``rest_framework``: .. code-block:: python INSTALLED_APPS = [ # ... 'rest_framework', 'rest_framework_gis', # ... ] Compatibility with DRF, Django and Python ----------------------------------------- ======================== ============================ ==================== ================================== DRF-gis version DRF version Django version Python version **0.18.x** **3.10** up to **3.13** **2.2 to 4.0** **3.6** to **3.9** **0.17.x** **3.10** up to **3.12** **2.2 to 3.1** **3.6** to **3.8** **0.16.x** **3.10** **2.2 to 3.1** **3.6** to **3.8** **0.15.x** **3.10** **1.11, 2.2 to 3.0** **3.5** to **3.8** **0.14.x** **3.3** to **3.9** **1.11** to **2.1** **3.4** to **3.7** **0.13.x** **3.3** to **3.8** **1.11** to **2.0** **2.7** to **3.6** **0.12.x** **3.1** to **3.7** **1.11** to **2.0** **2.7** to **3.6** **0.11.x** **3.1** to **3.6** **1.7** to **1.11** **2.7** to **3.6** **0.10.x** **3.1** to **3.3** **1.7** to **1.9** **2.7** to **3.5** **0.9.6** **3.1** to **3.2** **1.5** to **1.8** **2.6** to **3.5** **0.9.5** **3.1** to **3.2** **1.5** to **1.8** **2.6** to **3.4** **0.9.4** **3.1** to **3.2** **1.5** to **1.8** **2.6** to **3.4** **0.9.3** **3.1** **1.5** to **1.8** **2.6** to **3.4** **0.9.2** **3.1** **1.5** to **1.8** **2.6** to **3.4** **0.9.1** **3.1** **1.5** to **1.8** **2.6** to **3.4** **0.9** **3.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** **0.9** **3.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** **0.9** **3.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** **0.8.2** **3.0.4** to **3.1.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** **0.8.1** **3.0.4** to **3.1.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** **0.8** **3.0.4** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** **0.7** **2.4.3** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** **0.6** **2.4.3** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** **0.5** from **2.3.14** to **2.4.2** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** **0.4** from **2.3.14** to **2.4.2** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** **0.3** from **2.3.14** to **2.4.2** **1.5**, **1.6** **2.6**, **2.7** **0.2** from **2.2.2** to **2.3.13** **1.5**, **1.6** **2.6**, **2.7** ======================== ============================ ==================== ================================== Fields ------ GeometryField ~~~~~~~~~~~~~ Provides a ``GeometryField``, which is a subclass of Django Rest Framework (from now on **DRF**) ``WritableField``. This field handles GeoDjango geometry fields, providing custom ``to_native`` and ``from_native`` methods for GeoJSON input/output. This field takes two optional arguments: ``precision``: Passes coordinates through Python's builtin ``round()`` function (`docs `_), rounding values to the provided level of precision. E.g. A Point with lat/lng of ``[51.0486, -114.0708]`` passed through a ``GeometryField(precision=2)`` would return a Point with a lat/lng of ``[51.05, -114.07]``. ``remove_duplicates``: Remove sequential duplicate coordinates from line and polygon geometries. This is particularly useful when used with the ``precision`` argument, as the likelihood of duplicate coordinates increase as precision of coordinates are reduced. **Note:** While both above arguments are designed to reduce the byte size of the API response, they will also increase the processing time required to render the response. This will likely be negligible for small GeoJSON responses but may become an issue for large responses. **New in 0.9.3:** there is no need to define this field explicitly in your serializer, it's mapped automatically during initialization in ``rest_framework_gis.apps.AppConfig.ready()``. GeometrySerializerMethodField ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provides a ``GeometrySerializerMethodField``, which is a subclass of DRF ``SerializerMethodField`` and handles values which are computed with a serializer method and are used as a ``geo_field``. `See example below `__. Serializers ----------- GeoModelSerializer (DEPRECATED) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ **Deprecated, will be removed in 1.0**: Using this serializer is not needed anymore since 0.9.3, if you add ``rest_framework_gis`` in ``settings.INSTALLED_APPS`` the serialization will work out of the box with DRF. Refer `Issue #156 `__. Provides a ``GeoModelSerializer``, which is a subclass of DRF ``ModelSerializer``. This serializer updates the field\_mapping dictionary to include field mapping of GeoDjango geometry fields to the above ``GeometryField``. For example, the following model: .. code-block:: python class Location(models.Model): """ A model which holds information about a particular location """ address = models.CharField(max_length=255) city = models.CharField(max_length=100) state = models.CharField(max_length=100) point = models.PointField() By default, the DRF ModelSerializer **ver < 0.9.3** will output: .. code-block:: javascript { "id": 1, "address": "742 Evergreen Terrace", "city": "Springfield", "state": "Oregon", "point": "POINT(-123.0208 44.0464)" } In contrast, the ``GeoModelSerializer`` will output: .. code-block:: javascript { "id": 1, "address": "742 Evergreen Terrace", "city": "Springfield", "state": "Oregon", "point": { "type": "Point", "coordinates": [-123.0208, 44.0464], } } **Note:** For ``ver>=0.9.3``: The DRF model serializer will give the same output as above, if; - ``rest_framework_gis`` is set in ``settings.INSTALLED_APPS`` or - the field in the serializer is set explicitly as ``GeometryField``. GeoFeatureModelSerializer ~~~~~~~~~~~~~~~~~~~~~~~~~ ``GeoFeatureModelSerializer`` is a subclass of ``rest_framework.ModelSerializer`` which will output data in a format that is **GeoJSON** compatible. Using the above example, the ``GeoFeatureModelSerializer`` will output: .. code-block:: javascript { "id": 1, "type": "Feature", "geometry": { "type": "Point", "coordinates": [-123.0208, 44.0464], }, "properties": { "address": "742 Evergreen Terrace", "city": "Springfield", "state": "Oregon" } } If you are serializing an object list, ``GeoFeatureModelSerializer`` will create a ``FeatureCollection``: .. code-block:: javascript { "type": "FeatureCollection", "features": [ { "id": 1 "type": "Feature", "geometry": { "type": "Point", "coordinates": [-123.0208, 44.0464], }, "properties": { "address": "742 Evergreen Terrace", "city": "Springfield", "state": "Oregon", } } { "id": 2, "type": "Feature", "geometry": { "type": "Point", "coordinates": [-123.0208, 44.0489], }, "properties": { "address": "744 Evergreen Terrace", "city": "Springfield", "state": "Oregon" } } } Specifying the geometry field: "geo_field" ########################################## ``GeoFeatureModelSerializer`` requires you to define a ``geo_field`` to be serialized as the "geometry". For example: .. code-block:: python from rest_framework_gis.serializers import GeoFeatureModelSerializer class LocationSerializer(GeoFeatureModelSerializer): """ A class to serialize locations as GeoJSON compatible data """ class Meta: model = Location geo_field = "point" # you can also explicitly declare which fields you want to include # as with a ModelSerializer. fields = ('id', 'address', 'city', 'state') Using GeometrySerializerMethodField as "geo_field" ################################################## ``geo_field`` may also be an instance of ``GeometrySerializerMethodField``. In this case you can compute its value during serialization. For example: .. code-block:: python from django.contrib.gis.geos import Point from rest_framework_gis.serializers import GeoFeatureModelSerializer, GeometrySerializerMethodField class LocationSerializer(GeoFeatureModelSerializer): """ A class to serialize locations as GeoJSON compatible data """ # a field which contains a geometry value and can be used as geo_field other_point = GeometrySerializerMethodField() def get_other_point(self, obj): return Point(obj.point.lat / 2, obj.point.lon / 2) class Meta: model = Location geo_field = 'other_point' Serializer for ``geo_field`` may also return ``None`` value, which will translate to ``null`` value for geojson ``geometry`` field. Specifying the ID: "id_field" ############################# The primary key of the model (usually the "id" attribute) is automatically used as the ``id`` field of each `GeoJSON Feature Object `_. The default behaviour follows the `GeoJSON RFC `_, but it can be disabled by setting ``id_field`` to ``False``: .. code-block:: python from rest_framework_gis.serializers import GeoFeatureModelSerializer class LocationSerializer(GeoFeatureModelSerializer): class Meta: model = Location geo_field = "point" id_field = False fields = ('id', 'address', 'city', 'state') The ``id_field`` can also be set to use some other unique field in your model, eg: ``slug``: .. code-block:: python from rest_framework_gis.serializers import GeoFeatureModelSerializer class LocationSerializer(GeoFeatureModelSerializer): class Meta: model = Location geo_field = 'point' id_field = 'slug' fields = ('slug', 'address', 'city', 'state') Bounding Box: "auto_bbox" and "bbox_geo_field" ############################################## The GeoJSON specification allows a feature to contain a `boundingbox of a feature `__. ``GeoFeatureModelSerializer`` allows two different ways to fill this property. The first is using the ``geo_field`` to calculate the bounding box of a feature. This only allows read access for a REST client and can be achieved using ``auto_bbox``. Example: .. code-block:: python from rest_framework_gis.serializers import GeoFeatureModelSerializer class LocationSerializer(GeoFeatureModelSerializer): class Meta: model = Location geo_field = 'geometry' auto_bbox = True The second approach uses the ``bbox_geo_field`` to specify an additional ``GeometryField`` of the model which will be used to calculate the bounding box. This allows boundingboxes differ from the exact extent of a features geometry. Additionally this enables read and write access for the REST client. Bounding boxes send from the client will be saved as Polygons. Example: .. code-block:: python from rest_framework_gis.serializers import GeoFeatureModelSerializer class LocationSerializer(GeoFeatureModelSerializer): class Meta: model = BoxedLocation geo_field = 'geometry' bbox_geo_field = 'bbox_geometry' Custom GeoJSON properties source ################################ In GeoJSON each feature can have a ``properties`` member containing the attributes of the feature. By default this field is filled with the attributes from your Django model, excluding the id, geometry and bounding box fields. It's possible to override this behaviour and implement a custom source for the ``properties`` member. The following example shows how to use a PostgreSQL HStore field as a source for the ``properties`` member: .. code-block:: python # models.py class Link(models.Model): """ Metadata is stored in a PostgreSQL HStore field, which allows us to store arbitrary key-value pairs with a link record. """ metadata = HStoreField(blank=True, null=True, default=dict) geo = models.LineStringField() objects = models.GeoManager() # serializers.py class NetworkGeoSerializer(GeoFeatureModelSerializer): class Meta: model = models.Link geo_field = 'geo' auto_bbox = True def get_properties(self, instance, fields): # This is a PostgreSQL HStore field, which django maps to a dict return instance.metadata def unformat_geojson(self, feature): attrs = { self.Meta.geo_field: feature["geometry"], "metadata": feature["properties"] } if self.Meta.bbox_geo_field and "bbox" in feature: attrs[self.Meta.bbox_geo_field] = Polygon.from_bbox(feature["bbox"]) return attrs When the serializer renders GeoJSON, it calls the method ``get_properties`` for each object in the database. This function should return a dictionary containing the attributes for the feature. In the case of a HStore field, this function is easily implemented. The reverse is also required: mapping a GeoJSON formatted structure to attributes of your model. This task is done by ``unformat_geojson``. It should return a dictionary with your model attributes as keys, and the corresponding values retrieved from the GeoJSON feature data. Pagination ---------- We provide a ``GeoJsonPagination`` class. GeoJsonPagination ~~~~~~~~~~~~~~~~~ Based on ``rest_framework.pagination.PageNumberPagination``. Code example: .. code-block:: python from rest_framework_gis.pagination import GeoJsonPagination # --- other omitted imports --- # class GeojsonLocationList(generics.ListCreateAPIView): # -- other omitted view attributes --- # pagination_class = GeoJsonPagination Example result response (cut to one element only instead of 10): .. code-block:: javascript { "type": "FeatureCollection", "count": 25, "next": "http://localhost:8000/geojson/?page=2", "previous": null, "features": [ { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 42.0, 50.0 ] }, "properties": { "name": "test" } } ] } Filters ------- **note**: this feature has been tested up to django-filter 1.0. We provide a ``GeometryFilter`` field as well as a ``GeoFilterSet`` for usage with ``django_filter``. You simply provide, in the query string, one of the textual types supported by ``GEOSGeometry``. By default, this includes WKT, HEXEWKB, WKB (in a buffer), and GeoJSON. GeometryFilter ~~~~~~~~~~~~~~ .. code-block:: python from rest_framework_gis.filterset import GeoFilterSet from rest_framework_gis.filters import GeometryFilter from django_filters import filters class RegionFilter(GeoFilterSet): slug = filters.CharFilter(name='slug', lookup_expr='istartswith') contains_geom = GeometryFilter(name='geom', lookup_expr='contains') class Meta: model = Region We can then filter in the URL, using GeoJSON, and we will perform a ``__contains`` geometry lookup, e.g. ``/region/?contains_geom={ "type": "Point", "coordinates": [ -123.26436996459961, 44.564178042345375 ] }``. GeoFilterSet ~~~~~~~~~~~~ The ``GeoFilterSet`` provides a ``django_filter`` compatible ``FilterSet`` that will automatically create ``GeometryFilters`` for ``GeometryFields``. InBBoxFilter ~~~~~~~~~~~~ Provides a ``InBBoxFilter``, which is a subclass of DRF ``BaseFilterBackend``. Filters a queryset to only those instances within a certain bounding box. ``views.py:`` .. code-block:: python from rest_framework_gis.filters import InBBoxFilter class LocationList(ListAPIView): queryset = models.Location.objects.all() serializer_class = serializers.LocationSerializer bbox_filter_field = 'point' filter_backends = (InBBoxFilter,) bbox_filter_include_overlapping = True # Optional We can then filter in the URL, using Bounding Box format (min Lon, min Lat, max Lon, max Lat), and we can search for instances within the bounding box, e.g.: ``/location/?in_bbox=-90,29,-89,35``. By default, InBBoxFilter will only return those instances entirely within the stated bounding box. To include those instances which overlap the bounding box, include ``bbox_filter_include_overlapping = True`` in your view. Note that if you are using other filters, you'll want to include your other filter backend in your view. For example: ``filter_backends = (InBBoxFilter, DjangoFilterBackend,)`` TMSTileFilter ~~~~~~~~~~~~~ Provides a ``TMSTileFilter``, which is a subclass of ``InBBoxFilter``. Filters a queryset to only those instances within a bounding box defined by a `TMS tile `__ address. ``views.py:`` .. code-block:: python from rest_framework_gis.filters import TMSTileFilter class LocationList(ListAPIView): queryset = models.Location.objects.all() serializer_class = serializers.LocationSerializer bbox_filter_field = 'point' filter_backends = (TMSTileFilter,) bbox_filter_include_overlapping = True # Optional We can then filter in the URL, using TMS tile addresses in the zoom/x/y format, eg:. ``/location/?tile=8/100/200`` which is equivalent to filtering on the bbox (-39.37500,-71.07406,-37.96875,-70.61261). For more information on configuration options see InBBoxFilter. Note that the tile address start in the upper left, not the lower left origin used by some implementations. DistanceToPointFilter ~~~~~~~~~~~~~~~~~~~~~ Provides a ``DistanceToPointFilter``, which is a subclass of DRF ``BaseFilterBackend``. Filters a queryset to only those instances within a certain distance of a given point. ``views.py:`` .. code-block:: python from rest_framework_gis.filters import DistanceToPointFilter class LocationList(ListAPIView): queryset = models.Location.objects.all() serializer_class = serializers.LocationSerializer distance_filter_field = 'geometry' filter_backends = (DistanceToPointFilter,) We can then filter in the URL, using a distance and a point in (lon, lat) format. The distance can be given in meters or in degrees. eg:. ``/location/?dist=4000&point=-122.4862,37.7694&format=json`` which is equivalent to filtering within 4000 meters of the point (-122.4862, 37.7694). By default, DistanceToPointFilter will pass the 'distance' in the URL directly to the database for the search. The effect depends on the srid of the database in use. If geo data is indexed in meters (srid 3875, aka 900913), a distance in meters can be passed in directly without conversion. For lat-lon databases such as srid 4326, which is indexed in degrees, the 'distance' will be interpreted as degrees. Set the flag, 'distance_filter_convert_meters' to 'True' in order to convert an input distance in meters to degrees. This conversion is approximate, and the errors at latitudes > 60 degrees are > 25%. DistanceToPointOrderingFilter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provides a ``DistanceToPointOrderingFilter``, **available on Django >= 3.0**, which is a subclass of ``DistanceToPointFilter``. Orders a queryset by distance to a given point, from the nearest to the most distant point. ``views.py:`` .. code-block:: python from rest_framework_gis.filters import DistanceToPointOrderingFilter class LocationList(ListAPIView): queryset = models.Location.objects.all() serializer_class = serializers.LocationSerializer distance_ordering_filter_field = 'geometry' filter_backends = (DistanceToPointOrderingFilter,) We can then order the results by passing a point in (lon, lat) format in the URL. eg:. ``/location/?point=-122.4862,37.7694&format=json`` will order the results by the distance to the point (-122.4862, 37.7694). We can also reverse the order of the results by passing ``order=desc``: ``/location/?point=-122.4862,37.7694&order=desc&format=json`` Schema Generation ----------------- Note: Schema generation support is available only for DRF >= 3.12. Simplest Approach would be, change ``DEFAULT_SCHEMA_CLASS`` to ``rest_framework_gis.schema.GeoFeatureAutoSchema``: .. code-block:: python REST_FRAMEWORK = { ... 'DEFAULT_SCHEMA_CLASS': 'rest_framework_gis.schema.GeoFeatureAutoSchema', ... } If you do not want to change default schema generator class: - You can pass this class as an argument to ``get_schema_view`` function `[Ref] `__. - You can pass this class as an argument to the ``generateschema`` command `[Ref] `__. Running the tests ----------------- Required setup ============== You need one of the `Spatial Database servers supported by GeoDjango `__, and create a database for the tests. The following can be used with PostgreSQL: .. code-block:: bash createdb django_restframework_gis psql -U postgres -d django_restframework_gis -c "CREATE EXTENSION postgis" You might need to tweak the DB settings according to your DB configuration. You can copy the file ``local_settings.example.py`` to ``local_settings.py`` and change the ``DATABASES`` and/or ``INSTALLED_APPS`` directives there. This should allow you to run the tests already. For reference, the following steps will setup a development environment for contributing to the project: - create a spatial database named "django\_restframework\_gis" - create ``local_settings.py``, eg: ``cp local_settings.example.py local_settings.py`` - tweak the ``DATABASES`` configuration directive according to your DB settings - uncomment ``INSTALLED_APPS`` - run ``python manage.py syncdb`` - run ``python manage.py collectstatic`` - run ``python manage.py runserver`` Using tox ========= The recommended way to run the tests is by using `tox `__, which can be installed using `pip install tox`. You can use ``tox -l`` to list the available environments, and then e.g. use the following to run all tests with Python 3.6 and Django 1.11: .. code-block:: bash tox -e py36-django111 By default Django's test runner is used, but there is a variation of tox's envlist to use pytest (using the ``-pytest`` suffix). You can pass optional arguments to the test runner like this: .. code-block:: bash tox -e py36-django111-pytest -- -k test_foo Running tests manually ====================== Please refer to the ``tox.ini`` file for reference/help in case you want to run tests manually / without tox. To run tests in docker use .. code-block:: bash docker-compose build docker-compose run --rm test Running QA-checks ================= Install the test requirements: .. code-block:: shell pip install -r requirements-test.txt Reformat the code according to `our coding style conventions with `_: .. code-block:: shell openwisp-qa-format Run the QA checks by using .. code-block:: shell ./run-qa-checks In docker testing, QA checks are executed automatically. Contributing ------------ 1. Join the `Django REST Framework GIS Mailing List `__ and announce your intentions 2. Follow the `PEP8 Style Guide for Python Code `__ 3. Fork this repo 4. Write code 5. Write tests for your code 6. Ensure all tests pass 7. Ensure test coverage is not under 90% 8. Document your changes 9. Send pull request .. |Build Status| image:: https://github.com/openwisp/django-rest-framework-gis/workflows/Django%20Rest%20Framework%20Gis%20CI%20Build/badge.svg?branch=master :target: https://github.com/openwisp/django-rest-framework-gis/actions?query=workflow%3A%22Django+Rest+Framework+Gis+CI+Build%22 .. |Coverage Status| image:: https://coveralls.io/repos/openwisp/django-rest-framework-gis/badge.svg :target: https://coveralls.io/r/openwisp/django-rest-framework-gis .. |Requirements Status| image:: https://img.shields.io/librariesio/release/github/openwisp/django-rest-framework-gis :target: https://libraries.io/github/openwisp/django-rest-framework-gis#repository_dependencies :alt: Dependency monitoring .. |PyPI version| image:: https://badge.fury.io/py/djangorestframework-gis.svg :target: http://badge.fury.io/py/djangorestframework-gis .. |PyPI downloads| image:: https://pepy.tech/badge/djangorestframework-gis/month :target: https://pepy.tech/project/djangorestframework-gis .. |Black| image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://pypi.org/project/black/ ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1641564397.0 djangorestframework-gis-0.18/djangorestframework_gis.egg-info/SOURCES.txt0000644000175000017500000000276500000000000027741 0ustar00nemesisnemesis00000000000000AUTHORS CHANGES.rst LICENSE MANIFEST.in README.rst setup.cfg setup.py djangorestframework_gis.egg-info/PKG-INFO djangorestframework_gis.egg-info/SOURCES.txt djangorestframework_gis.egg-info/dependency_links.txt djangorestframework_gis.egg-info/requires.txt djangorestframework_gis.egg-info/top_level.txt rest_framework_gis/__init__.py rest_framework_gis/apps.py rest_framework_gis/fields.py rest_framework_gis/filters.py rest_framework_gis/filterset.py rest_framework_gis/pagination.py rest_framework_gis/schema.py rest_framework_gis/serializers.py rest_framework_gis/tilenames.py tests/local_settings.example.py tests/manage.py tests/settings.py tests/urls.py tests/django_restframework_gis_tests/__init__.py tests/django_restframework_gis_tests/admin.py tests/django_restframework_gis_tests/models.py tests/django_restframework_gis_tests/serializers.py tests/django_restframework_gis_tests/test_bbox.py tests/django_restframework_gis_tests/test_fields.py tests/django_restframework_gis_tests/test_filters.py tests/django_restframework_gis_tests/test_performance.py tests/django_restframework_gis_tests/test_schema_generation.py tests/django_restframework_gis_tests/tests.py tests/django_restframework_gis_tests/urls.py tests/django_restframework_gis_tests/views.py tests/django_restframework_gis_tests/migrations/0001_initial.py tests/django_restframework_gis_tests/migrations/0002_nullable.py tests/django_restframework_gis_tests/migrations/0003_schema_models.py tests/django_restframework_gis_tests/migrations/__init__.py././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1641564397.0 djangorestframework-gis-0.18/djangorestframework_gis.egg-info/dependency_links.txt0000644000175000017500000000000100000000000032111 0ustar00nemesisnemesis00000000000000 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1641564397.0 djangorestframework-gis-0.18/djangorestframework_gis.egg-info/requires.txt0000644000175000017500000000002400000000000030437 0ustar00nemesisnemesis00000000000000djangorestframework ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1641564397.0 djangorestframework-gis-0.18/djangorestframework_gis.egg-info/top_level.txt0000644000175000017500000000002300000000000030570 0ustar00nemesisnemesis00000000000000rest_framework_gis ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1641564397.384531 djangorestframework-gis-0.18/rest_framework_gis/0000775000175000017500000000000000000000000023327 5ustar00nemesisnemesis00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1641563961.0 djangorestframework-gis-0.18/rest_framework_gis/__init__.py0000664000175000017500000000070700000000000025444 0ustar00nemesisnemesis00000000000000VERSION = (0, 18, 0, 'final') __version__ = VERSION # alias def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s' % (version, VERSION[3]) return version default_app_config = 'rest_framework_gis.apps.AppConfig' ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1598581253.0 djangorestframework-gis-0.18/rest_framework_gis/apps.py0000664000175000017500000000221400000000000024643 0ustar00nemesisnemesis00000000000000from django.apps import AppConfig as BaseConfig class AppConfig(BaseConfig): name = 'rest_framework_gis' def ready(self): """ update Django Rest Framework serializer mappings """ from django.contrib.gis.db import models from rest_framework.serializers import ModelSerializer from .fields import GeometryField try: # drf 3.0 field_mapping = ModelSerializer._field_mapping.mapping except AttributeError: # drf 3.1 field_mapping = ModelSerializer.serializer_field_mapping # map GeoDjango fields to drf-gis GeometryField field_mapping.update( { models.GeometryField: GeometryField, models.PointField: GeometryField, models.LineStringField: GeometryField, models.PolygonField: GeometryField, models.MultiPointField: GeometryField, models.MultiLineStringField: GeometryField, models.MultiPolygonField: GeometryField, models.GeometryCollectionField: GeometryField, } ) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1640553128.0 djangorestframework-gis-0.18/rest_framework_gis/fields.py0000664000175000017500000001237000000000000025152 0ustar00nemesisnemesis00000000000000import 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, **kwargs): self.precision = precision 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'] ) 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) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1611531918.0 djangorestframework-gis-0.18/rest_framework_gis/filters.py0000664000175000017500000002450400000000000025356 0ustar00nemesisnemesis00000000000000from math import cos, pi from django.contrib.gis import forms from django.contrib.gis.db import models from django.contrib.gis.geos import Point, Polygon from django.core.exceptions import ImproperlyConfigured from django.db.models import Q from rest_framework.exceptions import ParseError from rest_framework.filters import BaseFilterBackend from .tilenames import tile_edges try: import django_filters except ImportError: # pragma: no cover raise ImproperlyConfigured( 'restframework-gis filters depend on package "django-filter" ' 'which is missing. Install with "pip install django-filter".' ) try: # Django >= 2.0 from django.contrib.gis.db.models.fields import BaseSpatialField except ImportError: try: # pragma: no cover # django >= 1.8,<2.0 from django.contrib.gis.db.models.lookups import gis_lookups except ImportError: # pragma: no cover # django <= 1.7 gis_lookups = models.sql.query.ALL_TERMS else: gis_lookups = BaseSpatialField.get_lookups() try: # Django >= 3.0 from django.contrib.gis.db.models.functions import GeometryDistance except ImportError: GeometryDistance = None __all__ = [ 'InBBoxFilter', 'InBBOXFilter', 'GeometryFilter', 'GeoFilterSet', 'TMSTileFilter', 'DistanceToPointFilter', 'DistanceToPointOrderingFilter', ] class InBBoxFilter(BaseFilterBackend): bbox_param = 'in_bbox' # The URL query parameter which contains the bbox. def get_filter_bbox(self, request): bbox_string = request.query_params.get(self.bbox_param, None) if not bbox_string: return None try: p1x, p1y, p2x, p2y = (float(n) for n in bbox_string.split(',')) except ValueError: raise ParseError( 'Invalid bbox string supplied for parameter {0}'.format(self.bbox_param) ) x = Polygon.from_bbox((p1x, p1y, p2x, p2y)) return x def filter_queryset(self, request, queryset, view): filter_field = getattr(view, 'bbox_filter_field', None) include_overlapping = getattr(view, 'bbox_filter_include_overlapping', False) if include_overlapping: geoDjango_filter = 'bboverlaps' else: geoDjango_filter = 'contained' if not filter_field: return queryset bbox = self.get_filter_bbox(request) if not bbox: return queryset return queryset.filter(Q(**{'%s__%s' % (filter_field, geoDjango_filter): bbox})) def get_schema_operation_parameters(self, view): return [ { "name": self.bbox_param, "required": False, "in": "query", "description": "Specify a bounding box as filter: in_bbox=min_lon,min_lat,max_lon,max_lat", "schema": { "type": "array", "items": {"type": "float"}, "minItems": 4, "maxItems": 4, "example": [0, 0, 10, 10], }, "style": "form", "explode": False, }, ] # backward compatibility InBBOXFilter = InBBoxFilter class GeometryFilter(django_filters.Filter): field_class = forms.GeometryField def __init__(self, *args, **kwargs): kwargs.setdefault('widget', forms.TextInput) super().__init__(*args, **kwargs) class GeoFilterSet(django_filters.FilterSet): GEOFILTER_FOR_DBFIELD_DEFAULTS = { models.GeometryField: {'filter_class': GeometryFilter}, } def __new__(cls, *args, **kwargs): try: cls._meta.filter_overrides.update(cls.GEOFILTER_FOR_DBFIELD_DEFAULTS) # maintain compatibility for django-filter < 0.15 except AttributeError: # pragma: nocover cls.filter_overrides.update(cls.GEOFILTER_FOR_DBFIELD_DEFAULTS) cls.LOOKUP_TYPES = sorted(gis_lookups) return super().__new__(cls) class TMSTileFilter(InBBoxFilter): tile_param = 'tile' # The URL query parameter which contains the tile address def get_filter_bbox(self, request): tile_string = request.query_params.get(self.tile_param, None) if not tile_string: return None try: z, x, y = (int(n) for n in tile_string.split('/')) except ValueError: raise ParseError( 'Invalid tile string supplied for parameter {0}'.format(self.tile_param) ) bbox = Polygon.from_bbox(tile_edges(x, y, z)) return bbox def get_schema_operation_parameters(self, view): return [ { "name": self.tile_param, "required": False, "in": "query", "description": "Specify a bounding box filter defined by a TMS tile address: tile=Z/X/Y", "schema": {"type": "string", "example": "12/56/34"}, }, ] class DistanceToPointFilter(BaseFilterBackend): dist_param = 'dist' point_param = 'point' # The URL query parameter which contains the def get_filter_point(self, request, **kwargs): point_string = request.query_params.get(self.point_param, None) if not point_string: return None try: (x, y) = (float(n) for n in point_string.split(',')) except ValueError: raise ParseError( 'Invalid geometry string supplied for parameter {0}'.format( self.point_param ) ) p = Point(x, y, **kwargs) return p def dist_to_deg(self, distance, latitude): """ distance = distance in meters latitude = latitude in degrees at the equator, the distance of one degree is equal in latitude and longitude. at higher latitudes, a degree longitude is shorter in length, proportional to cos(latitude) http://en.wikipedia.org/wiki/Decimal_degrees This function is part of a distance filter where the database 'distance' is in degrees. There's no good single-valued answer to this problem. The distance/ degree is quite constant N/S around the earth (latitude), but varies over a huge range E/W (longitude). Split the difference: I'm going to average the the degrees latitude and degrees longitude corresponding to the given distance. At high latitudes, this will be too short N/S and too long E/W. It splits the errors between the two axes. Errors are < 25 percent for latitudes < 60 degrees N/S. """ # d * (180 / pi) / earthRadius ==> degrees longitude # (degrees longitude) / cos(latitude) ==> degrees latitude lat = latitude if latitude >= 0 else -1 * latitude rad2deg = 180 / pi earthRadius = 6378160.0 latitudeCorrection = 0.5 * (1 + cos(lat * pi / 180)) return distance / (earthRadius * latitudeCorrection) * rad2deg def filter_queryset(self, request, queryset, view): filter_field = getattr(view, 'distance_filter_field', None) convert_distance_input = getattr(view, 'distance_filter_convert_meters', False) geoDjango_filter = 'dwithin' # use dwithin for points if not filter_field: return queryset point = self.get_filter_point(request) if not point: return queryset # distance in meters dist_string = request.query_params.get(self.dist_param, 1000) try: dist = float(dist_string) except ValueError: raise ParseError( 'Invalid distance string supplied for parameter {0}'.format( self.dist_param ) ) if convert_distance_input: # Warning: assumes that the point is (lon,lat) dist = self.dist_to_deg(dist, point[1]) return queryset.filter( Q(**{'%s__%s' % (filter_field, geoDjango_filter): (point, dist)}) ) def get_schema_operation_parameters(self, view): return [ { "name": self.dist_param, "required": False, "in": "query", "schema": {"type": "number", "format": "float", "default": 1000}, "description": f"Represents **Distance** in **Distance to point** filter. " f"Default value is used only if ***{self.point_param}*** is passed.", }, { "name": self.point_param, "required": False, "in": "query", "description": "Point represented in **x,y** format. " "Represents **point** in **Distance to point filter**", "schema": { "type": "array", "items": {"type": "float"}, "minItems": 2, "maxItems": 2, "example": [0, 10], }, "style": "form", "explode": False, }, ] class DistanceToPointOrderingFilter(DistanceToPointFilter): srid = 4326 order_param = 'order' def filter_queryset(self, request, queryset, view): if not GeometryDistance: raise ValueError('GeometryDistance not available on this version of django') filter_field = getattr(view, 'distance_ordering_filter_field', None) if not filter_field: return queryset point = self.get_filter_point(request, srid=self.srid) if not point: return queryset order = request.query_params.get(self.order_param) if order == 'desc': return queryset.order_by(-GeometryDistance(filter_field, point)) else: return queryset.order_by(GeometryDistance(filter_field, point)) def get_schema_operation_parameters(self, view): params = super().get_schema_operation_parameters(view) params.append( { "name": self.order_param, "required": False, "in": "query", "description": "", "schema": { "type": "enum", "items": {"type": "string", "enum": ["asc", "desc"]}, "example": "desc", }, "style": "form", "explode": False, } ) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1575898946.0 djangorestframework-gis-0.18/rest_framework_gis/filterset.py0000644000175000017500000000005200000000000025675 0ustar00nemesisnemesis00000000000000from .filters import GeoFilterSet # noqa ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1611531918.0 djangorestframework-gis-0.18/rest_framework_gis/pagination.py0000664000175000017500000000207600000000000026037 0ustar00nemesisnemesis00000000000000from collections import OrderedDict from rest_framework import pagination from rest_framework.response import Response class GeoJsonPagination(pagination.PageNumberPagination): """ A geoJSON implementation of a pagination serializer. """ page_size_query_param = 'page_size' def get_paginated_response(self, data): return Response( OrderedDict( [ ('type', 'FeatureCollection'), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('features', data['features']), ] ) ) def get_paginated_response_schema(self, view): schema = super().get_paginated_response_schema(view) schema["properties"]["features"] = schema["properties"].pop("results") schema["properties"] = { "type": {"type": "string", "enum": ["FeatureCollection"]}, **schema["properties"], } return schema ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1640553128.0 djangorestframework-gis-0.18/rest_framework_gis/schema.py0000664000175000017500000001373700000000000025154 0ustar00nemesisnemesis00000000000000import warnings from django.contrib.gis.db import models from rest_framework.schemas.openapi import AutoSchema from rest_framework.utils import model_meta from rest_framework_gis.fields import GeometryField, GeometrySerializerMethodField from rest_framework_gis.serializers import ( GeoFeatureModelListSerializer, GeoFeatureModelSerializer, ) class GeoFeatureAutoSchema(AutoSchema): COORDINATES_SCHEMA_FOR_POINT = { "type": "array", "items": {"type": "number", "format": "float"}, "example": [12.9721, 77.5933], "minItems": 2, "maxItems": 3, } COORDINATES_SCHEMA_FOR_LINE_STRING = { "type": "array", "items": COORDINATES_SCHEMA_FOR_POINT, "example": [[22.4707, 70.0577], [12.9721, 77.5933]], "minItems": 2, } GEO_FIELD_TO_SCHEMA = { models.PointField: { "type": {"type": "string", "enum": ["Point"]}, "coordinates": COORDINATES_SCHEMA_FOR_POINT, }, models.LineStringField: { "type": {"type": "string", "enum": ["LineString"]}, "coordinates": COORDINATES_SCHEMA_FOR_LINE_STRING, }, models.PolygonField: { "type": {"type": "string", "enum": ["Polygon"]}, "coordinates": { "type": "array", "items": {**COORDINATES_SCHEMA_FOR_LINE_STRING, "minItems": 4}, "example": [ [0.0, 0.0], [0.0, 50.0], [50.0, 50.0], [50.0, 0.0], [0.0, 0.0], ], }, }, } GEO_FIELD_TO_SCHEMA[models.GeometryField] = { 'type': {'type': 'string'}, 'coordinates': { 'oneOf': [ # If you have custom subclass of GeometryField, Override `oneOf` property. GEO_FIELD_TO_SCHEMA[models.PointField], GEO_FIELD_TO_SCHEMA[models.LineStringField], GEO_FIELD_TO_SCHEMA[models.PolygonField], ], 'example': GEO_FIELD_TO_SCHEMA[models.PolygonField]['coordinates'][ 'example' ], }, } MULTI_FIELD_MAPPING = { models.PointField: models.MultiPointField, models.LineStringField: models.MultiLineStringField, models.PolygonField: models.MultiPolygonField, models.GeometryField: models.GeometryCollectionField, } for singular_field, multi_field in MULTI_FIELD_MAPPING.items(): GEO_FIELD_TO_SCHEMA[multi_field] = { "type": {"type": "string", "enum": [multi_field.geom_class.__name__]}, "coordinates": { "type": "array", "items": GEO_FIELD_TO_SCHEMA[singular_field]["coordinates"], "example": [ GEO_FIELD_TO_SCHEMA[singular_field]["coordinates"]["example"] ], }, } def _map_geo_field(self, serializer, geo_field_name): field = serializer.fields[geo_field_name] if isinstance(field, GeometrySerializerMethodField): warnings.warn( "Geometry generation for GeometrySerializerMethodField is not supported." ) return {} model_field_name = geo_field_name geo_field = model_meta.get_field_info(serializer.Meta.model).fields[ model_field_name ] try: return self.GEO_FIELD_TO_SCHEMA[geo_field.__class__] except KeyError: warnings.warn( "Geometry generation for {field} is not supported.".format(field=field) ) return {} def map_field(self, field): if isinstance(field, GeoFeatureModelListSerializer): return self._map_geo_feature_model_list_serializer(field) if isinstance(field, GeometryField): return { "type": "object", "properties": self._map_geo_field(field.parent, field.field_name), } return super().map_field(field) def _map_geo_feature_model_list_serializer(self, serializer): return { "type": "object", "properties": { "type": {"type": "string", "enum": ["FeatureCollection"]}, "features": { "type": "array", "items": self.map_serializer(serializer.child), }, }, } def _map_geo_feature_model_serializer(self, serializer): schema = super().map_serializer(serializer) geo_json_schema = { "type": "object", "properties": {"type": {"type": "string", "enum": ["Feature"]}}, } if serializer.Meta.id_field: geo_json_schema["properties"]["id"] = schema["properties"].pop( serializer.Meta.id_field ) geo_field = serializer.Meta.geo_field geo_json_schema["properties"]["geometry"] = { "type": "object", "properties": self._map_geo_field(serializer, geo_field), } schema["properties"].pop(geo_field) if serializer.Meta.auto_bbox or serializer.Meta.bbox_geo_field: geo_json_schema["properties"]["bbox"] = { "type": "array", "items": {"type": "number"}, "minItems": 4, "maxItems": 4, "example": [12.9721, 77.5933, 12.9721, 77.5933], } if serializer.Meta.bbox_geo_field in schema["properties"]: schema["properties"].pop(serializer.Meta.bbox_geo_field) geo_json_schema["properties"]["properties"] = schema return geo_json_schema def map_serializer(self, serializer): if isinstance(serializer, GeoFeatureModelListSerializer): return self._map_geo_feature_model_list_serializer(serializer) if isinstance(serializer, GeoFeatureModelSerializer): return self._map_geo_feature_model_serializer(serializer) return super().map_serializer(serializer) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1610572132.0 djangorestframework-gis-0.18/rest_framework_gis/serializers.py0000664000175000017500000001721600000000000026244 0ustar00nemesisnemesis00000000000000from collections import OrderedDict from django.contrib.gis.geos import Polygon from django.core.exceptions import ImproperlyConfigured from rest_framework.serializers import ( LIST_SERIALIZER_KWARGS, ListSerializer, ModelSerializer, ) from .fields import GeometryField, GeometrySerializerMethodField # noqa class GeoModelSerializer(ModelSerializer): """ Deprecated, will be removed in django-rest-framework-gis 1.0 """ class GeoFeatureModelListSerializer(ListSerializer): @property def data(self): return super(ListSerializer, self).data def to_representation(self, data): """ Add GeoJSON compatible formatting to a serialized queryset list """ return OrderedDict( ( ("type", "FeatureCollection"), ("features", super().to_representation(data)), ) ) class GeoFeatureModelSerializer(ModelSerializer): """ A subclass of ModelSerializer that outputs geojson-ready data as features and feature collections """ @classmethod def many_init(cls, *args, **kwargs): child_serializer = cls(*args, **kwargs) list_kwargs = {'child': child_serializer} list_kwargs.update( { key: value for key, value in kwargs.items() if key in LIST_SERIALIZER_KWARGS } ) meta = getattr(cls, 'Meta', None) list_serializer_class = getattr( meta, 'list_serializer_class', GeoFeatureModelListSerializer ) return list_serializer_class(*args, **list_kwargs) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) meta = getattr(self, 'Meta') default_id_field = None primary_key = self.Meta.model._meta.pk.name # use primary key as id_field when possible if ( not hasattr(meta, 'fields') or meta.fields == '__all__' or primary_key in meta.fields ): default_id_field = primary_key meta.id_field = getattr(meta, 'id_field', default_id_field) if not hasattr(meta, 'geo_field') or not meta.geo_field: raise ImproperlyConfigured("You must define a 'geo_field'.") def check_excludes(field_name, field_role): """make sure the field is not excluded""" if hasattr(meta, 'exclude') and field_name in meta.exclude: raise ImproperlyConfigured( "You cannot exclude your '{0}'.".format(field_role) ) def add_to_fields(field_name): """Make sure the field is included in the fields""" if hasattr(meta, 'fields') and meta.fields != '__all__': if field_name not in meta.fields: if type(meta.fields) is tuple: additional_fields = (field_name,) else: additional_fields = [field_name] meta.fields += additional_fields check_excludes(meta.geo_field, 'geo_field') add_to_fields(meta.geo_field) meta.bbox_geo_field = getattr(meta, 'bbox_geo_field', None) if meta.bbox_geo_field: check_excludes(meta.bbox_geo_field, 'bbox_geo_field') add_to_fields(meta.bbox_geo_field) meta.auto_bbox = getattr(meta, 'auto_bbox', False) if meta.bbox_geo_field and meta.auto_bbox: raise ImproperlyConfigured( "You must eiher define a 'bbox_geo_field' or " "'auto_bbox', but you can not set both" ) def to_representation(self, instance): """ Serialize objects -> primitives. """ # prepare OrderedDict geojson structure feature = OrderedDict() # keep track of the fields being processed processed_fields = set() # optional id attribute if self.Meta.id_field: field = self.fields[self.Meta.id_field] value = field.get_attribute(instance) feature["id"] = field.to_representation(value) processed_fields.add(self.Meta.id_field) # required type attribute # must be "Feature" according to GeoJSON spec feature["type"] = "Feature" # required geometry attribute # MUST be present in output according to GeoJSON spec field = self.fields[self.Meta.geo_field] geo_value = field.get_attribute(instance) feature["geometry"] = field.to_representation(geo_value) processed_fields.add(self.Meta.geo_field) # Bounding Box # if auto_bbox feature is enabled # bbox will be determined automatically automatically if self.Meta.auto_bbox and geo_value: feature["bbox"] = geo_value.extent # otherwise it can be determined via another field elif self.Meta.bbox_geo_field: field = self.fields[self.Meta.bbox_geo_field] value = field.get_attribute(instance) feature["bbox"] = value.extent if hasattr(value, 'extent') else None processed_fields.add(self.Meta.bbox_geo_field) # the list of fields that will be processed by get_properties # we will remove fields that have been already processed # to increase performance on large numbers fields = [ field_value for field_key, field_value in self.fields.items() if field_key not in processed_fields ] # GeoJSON properties feature["properties"] = self.get_properties(instance, fields) return feature def get_properties(self, instance, fields): """ Get the feature metadata which will be used for the GeoJSON "properties" key. By default it returns all serializer fields excluding those used for the ID, the geometry and the bounding box. :param instance: The current Django model instance :param fields: The list of fields to process (fields already processed have been removed) :return: OrderedDict containing the properties of the current feature :rtype: OrderedDict """ properties = OrderedDict() for field in fields: if field.write_only: continue value = field.get_attribute(instance) representation = None if value is not None: representation = field.to_representation(value) properties[field.field_name] = representation return properties def to_internal_value(self, data): """ Override the parent method to first remove the GeoJSON formatting """ if 'properties' in data: data = self.unformat_geojson(data) return super().to_internal_value(data) def unformat_geojson(self, feature): """ This function should return a dictionary containing keys which maps to serializer fields. Remember that GeoJSON contains a key "properties" which contains the feature metadata. This should be flattened to make sure this metadata is stored in the right serializer fields. :param feature: The dictionary containing the feature data directly from the GeoJSON data. :return: A new dictionary which maps the GeoJSON values to serializer fields """ attrs = feature["properties"] if 'geometry' in feature: attrs[self.Meta.geo_field] = feature['geometry'] if self.Meta.bbox_geo_field and 'bbox' in feature: attrs[self.Meta.bbox_geo_field] = Polygon.from_bbox(feature['bbox']) return attrs ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1598581253.0 djangorestframework-gis-0.18/rest_framework_gis/tilenames.py0000664000175000017500000000204400000000000025662 0ustar00nemesisnemesis00000000000000#!/usr/bin/env python # ------------------------------------------------------- # Translates between lat/long and the slippy-map tile # numbering scheme # # http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames # # Written by Oliver White, 2007 # This file is public-domain # ------------------------------------------------------- from math import atan, degrees, pi from math import pow as math_pow from math import sinh def num_tiles(z): return math_pow(2, z) def lat_edges(y, z): n = num_tiles(z) unit = 1 / n relY1 = y * unit relY2 = relY1 + unit lat1 = mercator_to_lat(pi * (1 - 2 * relY1)) lat2 = mercator_to_lat(pi * (1 - 2 * relY2)) return (lat1, lat2) def lon_edges(x, z): n = num_tiles(z) unit = 360 / n lon1 = -180 + x * unit lon2 = lon1 + unit return (lon1, lon2) def tile_edges(x, y, z): lat1, lat2 = lat_edges(y, z) lon1, lon2 = lon_edges(x, z) return (lon1, lat2, lon2, lat1) # w, s, e, n def mercator_to_lat(mercatorY): return degrees(atan(sinh(mercatorY))) ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1641564397.392531 djangorestframework-gis-0.18/setup.cfg0000664000175000017500000000043700000000000021260 0ustar00nemesisnemesis00000000000000[bdist_wheel] universal = 1 [flake8] exclude = ./tests/*settings*.py, docs/* max-line-length = 110 ignore = W605, W503, W504 [isort] multi_line_output = 3 use_parentheses = True include_trailing_comma = True force_grid_wrap = 0 line_length = 88 [egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1598581253.0 djangorestframework-gis-0.18/setup.py0000664000175000017500000000465300000000000021155 0ustar00nemesisnemesis00000000000000#!/usr/bin/env python import os import sys from setuptools import find_packages, setup from rest_framework_gis import get_version if sys.argv[-1] == 'publish': os.system("python setup.py sdist bdist_wheel") os.system("twine upload -s dist/*") os.system("rm -rf dist build") args = {'version': get_version()} print("You probably want to also tag the version now:") print(" git tag -a %(version)s -m 'version %(version)s'" % args) print(" git push --tags") sys.exit() here = os.path.abspath(os.path.dirname(__file__)) # Get the long description from the README file with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='djangorestframework-gis', version=get_version(), license='BSD', author='Douglas Meehan', author_email='django-rest-framework-gis@googlegroups.com', description='Geographic add-ons for Django Rest Framework', long_description=long_description, url='https://github.com/openwisp/django-rest-framework-gis', download_url='https://github.com/openwisp/django-rest-framework-gis/releases', platforms=['Platform Indipendent'], keywords=['django', 'rest-framework', 'gis', 'geojson'], packages=find_packages(exclude=['tests', 'tests.*']), install_requires=['djangorestframework'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Topic :: Internet :: WWW/HTTP', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Framework :: Django', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3 :: Only', ], project_urls={ 'Bug Reports': 'https://github.com/openwisp/django-rest-framework-gis/issues', 'Continuous Integration': 'https://travis-ci.org/openwisp/django-rest-framework-gis', 'Mailing List': 'https://groups.google.com/forum/#!forum/django-rest-framework-gis', 'Code Coverage': 'https://coveralls.io/github/openwisp/django-rest-framework-gis', 'Source Code': 'https://github.com/openwisp/django-rest-framework-gis', }, ) ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1641564397.384531 djangorestframework-gis-0.18/tests/0000775000175000017500000000000000000000000020575 5ustar00nemesisnemesis00000000000000././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1641564397.388531 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/0000775000175000017500000000000000000000000027076 5ustar00nemesisnemesis00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1575898946.0 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/__init__.py0000644000175000017500000000000000000000000031173 0ustar00nemesisnemesis00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1598581253.0 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/admin.py0000664000175000017500000000037500000000000030545 0ustar00nemesisnemesis00000000000000from django.contrib import admin from django.contrib.gis.admin import ModelAdmin as GeoModelAdmin from .models import Location class LocationAdmin(GeoModelAdmin): list_display = ('name', 'geometry') admin.site.register(Location, LocationAdmin) ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1641564397.388531 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/migrations/0000775000175000017500000000000000000000000031252 5ustar00nemesisnemesis00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1598581253.0 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/migrations/0001_initial.py0000664000175000017500000000576600000000000033733 0ustar00nemesisnemesis00000000000000# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-04-01 17:00 from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name='BoxedLocation', fields=[ ( 'id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID', ), ), ('name', models.CharField(max_length=32)), ('slug', models.SlugField(blank=True, max_length=128, unique=True)), ('timestamp', models.DateTimeField(blank=True, null=True)), ( 'geometry', django.contrib.gis.db.models.fields.GeometryField(srid=4326), ), ( 'bbox_geometry', django.contrib.gis.db.models.fields.PolygonField(srid=4326), ), ], options={'abstract': False}, ), migrations.CreateModel( name='LocatedFile', fields=[ ( 'id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID', ), ), ('name', models.CharField(max_length=32)), ('slug', models.SlugField(blank=True, max_length=128, unique=True)), ('timestamp', models.DateTimeField(blank=True, null=True)), ( 'geometry', django.contrib.gis.db.models.fields.GeometryField(srid=4326), ), ( 'file', models.FileField(blank=True, null=True, upload_to='located_files'), ), ], options={'abstract': False}, ), migrations.CreateModel( name='Location', fields=[ ( 'id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID', ), ), ('name', models.CharField(max_length=32)), ('slug', models.SlugField(blank=True, max_length=128, unique=True)), ('timestamp', models.DateTimeField(blank=True, null=True)), ( 'geometry', django.contrib.gis.db.models.fields.GeometryField(srid=4326), ), ], options={'abstract': False}, ), ] ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1598581253.0 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/migrations/0002_nullable.py0000664000175000017500000000222200000000000034061 0ustar00nemesisnemesis00000000000000# Generated by Django 2.2.9 on 2019-12-30 12:24 import django.contrib.gis.db.models.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('django_restframework_gis_tests', '0001_initial'), ] operations = [ migrations.CreateModel( name='Nullable', fields=[ ( 'id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID', ), ), ('name', models.CharField(max_length=32)), ('slug', models.SlugField(blank=True, max_length=128, unique=True)), ('timestamp', models.DateTimeField(blank=True, null=True)), ( 'geometry', django.contrib.gis.db.models.fields.GeometryField( blank=True, null=True, srid=4326 ), ), ], options={'abstract': False}, ), ] ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1611531918.0 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/migrations/0003_schema_models.py0000664000175000017500000001227500000000000035100 0ustar00nemesisnemesis00000000000000# Generated by Django 3.0.4 on 2020-04-03 06:52 import django.contrib.gis.db.models.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("django_restframework_gis_tests", "0002_nullable"), ] operations = [ migrations.CreateModel( name="LineStringModel", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("random_field1", models.CharField(max_length=32)), ("random_field2", models.IntegerField()), ( "points", django.contrib.gis.db.models.fields.LineStringField(srid=4326), ), ], options={"abstract": False}, ), migrations.CreateModel( name="MultiLineStringModel", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("random_field1", models.CharField(max_length=32)), ("random_field2", models.IntegerField()), ( "points", django.contrib.gis.db.models.fields.MultiLineStringField(srid=4326), ), ], options={"abstract": False}, ), migrations.CreateModel( name="MultiPointModel", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("random_field1", models.CharField(max_length=32)), ("random_field2", models.IntegerField()), ( "points", django.contrib.gis.db.models.fields.MultiPointField(srid=4326), ), ], options={"abstract": False}, ), migrations.CreateModel( name="MultiPolygonModel", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("random_field1", models.CharField(max_length=32)), ("random_field2", models.IntegerField()), ( "polygon", django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326), ), ], options={"abstract": False}, ), migrations.CreateModel( name="PointModel", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("random_field1", models.CharField(max_length=32)), ("random_field2", models.IntegerField()), ("location", django.contrib.gis.db.models.fields.PointField(srid=4326)), ], options={"abstract": False}, ), migrations.CreateModel( name="PolygonModel", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("random_field1", models.CharField(max_length=32)), ("random_field2", models.IntegerField()), ( "polygon", django.contrib.gis.db.models.fields.PolygonField(srid=4326), ), ], options={"abstract": False}, ), migrations.CreateModel( name="GeometryModel", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("random_field1", models.CharField(max_length=32)), ("random_field2", models.IntegerField()), ( "points", django.contrib.gis.db.models.fields.GeometryField(srid=4326), ), ], options={"abstract": False}, ), ] ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1575898946.0 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/migrations/__init__.py0000644000175000017500000000000000000000000033347 0ustar00nemesisnemesis00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1611531918.0 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/models.py0000664000175000017500000000405700000000000030741 0ustar00nemesisnemesis00000000000000from django.contrib.gis.db import models from django.utils.text import slugify __all__ = [ 'Location', 'LocatedFile', 'BoxedLocation', 'GeometryModel', 'Nullable', 'PointModel', 'LineStringModel', 'PolygonModel', 'MultiPolygonModel', 'MultiLineStringModel', 'MultiPointModel', ] class BaseModel(models.Model): name = models.CharField(max_length=32) slug = models.SlugField(max_length=128, unique=True, blank=True) timestamp = models.DateTimeField(null=True, blank=True) geometry = models.GeometryField() class Meta: abstract = True def __str__(self): return self.name def _generate_slug(self): if self.slug == '' or self.slug is None: try: name = str(self.name) except NameError: name = self.name self.slug = slugify(name) def clean(self): self._generate_slug() def save(self, *args, **kwargs): self._generate_slug() super().save(*args, **kwargs) class Location(BaseModel): pass class LocatedFile(BaseModel): file = models.FileField(upload_to='located_files', blank=True, null=True) class BoxedLocation(BaseModel): bbox_geometry = models.PolygonField() class Nullable(BaseModel): geometry = models.GeometryField(blank=True, null=True) class SchemaBaseModel(models.Model): random_field1 = models.CharField(max_length=32) random_field2 = models.IntegerField() class Meta: abstract = True class PointModel(SchemaBaseModel): location = models.PointField() class LineStringModel(SchemaBaseModel): points = models.LineStringField() class PolygonModel(SchemaBaseModel): polygon = models.PolygonField() class GeometryModel(SchemaBaseModel): points = models.GeometryField() class MultiPointModel(SchemaBaseModel): points = models.MultiPointField() class MultiLineStringModel(SchemaBaseModel): points = models.MultiLineStringField() class MultiPolygonModel(SchemaBaseModel): polygon = models.MultiPolygonField() ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1640553128.0 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/serializers.py0000664000175000017500000001547300000000000032016 0ustar00nemesisnemesis00000000000000from django.contrib.gis.geos import Point from rest_framework import pagination, serializers from rest_framework_gis import serializers as gis_serializers from rest_framework_gis.fields import GeometrySerializerMethodField from .models import ( BoxedLocation, GeometryModel, LineStringModel, Location, MultiLineStringModel, MultiPointModel, MultiPolygonModel, PointModel, PolygonModel, ) __all__ = [ 'LocationGeoSerializer', 'PaginatedLocationGeoSerializer', 'LocationGeoFeatureSerializer', 'LocationGeoFeatureSlugSerializer', 'LocationGeoFeatureFalseIdSerializer', 'LocationGeoFeatureNoIdSerializer', 'LocatedFileGeoFeatureSerializer', 'BoxedLocationGeoFeatureSerializer', 'LocationGeoFeatureBboxSerializer', 'LocationGeoFeatureMethodSerializer', 'NoneGeoFeatureMethodSerializer', 'PointSerializer', 'ChildPointSerializer', 'ListChildPointSerializer', 'LineStringSerializer', 'PolygonSerializer', 'MultiPolygonSerializer', 'MultiLineStringSerializer', 'MultiPointSerializer', 'GeometrySerializerMethodFieldSerializer', 'GeometrySerializer', 'BoxedLocationGeoFeatureWithBBoxGeoFieldSerializer', ] class LocationGeoSerializer(serializers.ModelSerializer): """ location geo serializer """ details = serializers.HyperlinkedIdentityField(view_name='api_location_details') class Meta: model = Location fields = '__all__' class PaginatedLocationGeoSerializer(pagination.PageNumberPagination): page_size_query_param = 'limit' page_size = 40 max_page_size = 10000 class LocationGeoFeatureSerializer(gis_serializers.GeoFeatureModelSerializer): """ location geo serializer """ details = serializers.HyperlinkedIdentityField( view_name='api_geojson_location_details' ) fancy_name = serializers.SerializerMethodField() def get_fancy_name(self, obj): return 'Kool %s' % obj.name class Meta: model = Location geo_field = 'geometry' fields = '__all__' class LocationGeoFeatureSlugSerializer(LocationGeoFeatureSerializer): """ use slug as id attribute """ class Meta: model = Location geo_field = 'geometry' id_field = 'slug' fields = ('name', 'slug', 'timestamp') class LocationGeoFeatureFalseIdSerializer(LocationGeoFeatureSerializer): """ id attribute set as False """ class Meta: model = Location geo_field = 'geometry' id_field = False fields = '__all__' class LocationGeoFeatureNoIdSerializer(LocationGeoFeatureSerializer): """ id attribute left out, issue #82 see: https://github.com/openwisp/django-rest-framework-gis/issues/82 """ class Meta: model = Location geo_field = 'geometry' fields = ('name',) class LocatedFileGeoFeatureSerializer(gis_serializers.GeoFeatureModelSerializer): """ located file geo serializer """ details = serializers.HyperlinkedIdentityField( view_name='api_geojson_located_file_details' ) fancy_name = serializers.SerializerMethodField() file = serializers.FileField(allow_empty_file=True) def get_fancy_name(self, obj): return 'Nice %s' % obj.name class Meta: model = Location geo_field = 'geometry' exclude = [] class BoxedLocationGeoFeatureSerializer(gis_serializers.GeoFeatureModelSerializer): """ location geo serializer """ details = serializers.HyperlinkedIdentityField( view_name='api_geojson_boxedlocation_details' ) class Meta: model = BoxedLocation geo_field = 'geometry' bbox_geo_field = 'bbox_geometry' fields = ['name', 'details', 'id', 'timestamp'] class LocationGeoFeatureBboxSerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = Location geo_field = 'geometry' auto_bbox = True exclude = [] class LocationGeoFeatureMethodSerializer(gis_serializers.GeoFeatureModelSerializer): new_geometry = gis_serializers.GeometrySerializerMethodField() def get_new_geometry(self, obj): if obj.name.startswith('hidden'): return Point(0.0, 0.0) else: return obj.geometry class Meta: model = Location geo_field = 'new_geometry' exclude = [] class NoneGeoFeatureMethodSerializer(gis_serializers.GeoFeatureModelSerializer): new_geometry = gis_serializers.GeometrySerializerMethodField() def get_new_geometry(self, obj): return None class Meta: model = Location geo_field = 'new_geometry' fields = ['name', 'slug', 'id'] class PointSerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = PointModel geo_field = 'location' fields = '__all__' class ChildPointSerializer(serializers.Serializer): point = PointSerializer() class ListChildPointSerializer(serializers.Serializer): points = PointSerializer(many=True) class LineStringSerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = LineStringModel geo_field = 'points' fields = '__all__' class PolygonSerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = PolygonModel geo_field = 'polygon' fields = '__all__' class PolygonModelSerializer(serializers.ModelSerializer): class Meta: model = PolygonModel fields = '__all__' class MultiPolygonSerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = MultiPolygonModel geo_field = 'polygon' fields = '__all__' class MultiLineStringSerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = MultiLineStringModel geo_field = 'points' fields = '__all__' class MultiPointSerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = MultiPointModel geo_field = 'points' fields = '__all__' auto_bbox = True class GeometrySerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = GeometryModel geo_field = 'points' fields = '__all__' auto_bbox = True class GeometrySerializerMethodFieldSerializer(PointSerializer): other_point = GeometrySerializerMethodField() @staticmethod def get_other_point(obj): return Point(obj.location.lat / 2, obj.location.lon / 2) class Meta: model = Location geo_field = 'other_point' fields = '__all__' class BoxedLocationGeoFeatureWithBBoxGeoFieldSerializer( BoxedLocationGeoFeatureSerializer ): class Meta(BoxedLocationGeoFeatureSerializer.Meta): fields = BoxedLocationGeoFeatureSerializer.Meta.fields + [ BoxedLocationGeoFeatureSerializer.Meta.bbox_geo_field ] ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1610572132.0 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/test_bbox.py0000664000175000017500000000720000000000000031440 0ustar00nemesisnemesis00000000000000import json from django.test import TestCase try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse from django.core.exceptions import ImproperlyConfigured from rest_framework_gis import serializers as gis_serializers from .models import BoxedLocation, Location class TestRestFrameworkGisBBox(TestCase): """ unit tests for bbox support in restframework_gis """ def setUp(self): self.geojson_boxedlocation_list_url = reverse('api_geojson_boxedlocation_list') self.geojson_location_bbox_list_url = reverse('api_geojson_location_bbox_list') def _create_locations(self): self.bl1 = BoxedLocation.objects.create( id=1, name='l1', slug='l1', geometry='POINT (13.007 42.423)', bbox_geometry='POLYGON((12.997 42.413,12.997 42.433,13.017 42.433,13.017 42.413,12.997 42.413))', ) self.bl2 = BoxedLocation.objects.create( id=2, name='l2', slug='l2', geometry='POINT (12.007 43.423)', bbox_geometry='POLYGON((11.997 43.413,11.997 43.433,12.017 43.433,12.017 43.413,11.997 43.413))', ) self.l1 = Location.objects.create( id=1, name='l1', slug='l1', geometry='POLYGON((12.997 42.413,12.997 42.433,13.017 42.433,13.017 42.413,12.997 42.413))', ) def test_list(self): self._create_locations() response = self.client.get(self.geojson_boxedlocation_list_url) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data['features']), 2) for feature in response.data['features']: self.assertIn('bbox', feature) fid = feature['id'] if fid == 1: self.assertEqual(feature['bbox'], self.bl1.bbox_geometry.extent) elif fid == 2: self.assertEqual(feature['bbox'], self.bl2.bbox_geometry.extent) else: self.fail("Unexpected id: {0}".format(fid)) BoxedLocation.objects.all().delete() def test_post_location_list_geojson(self): self.assertEqual(BoxedLocation.objects.count(), 0) data = { "properties": {"name": "geojson input test"}, "geometry": {"type": "Point", "coordinates": [12.49, 41.89]}, "bbox": [11.0, 40.0, 13.0, 42.0], } response = self.client.post( self.geojson_boxedlocation_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 201) self.assertEqual(BoxedLocation.objects.count(), 1) self.assertEqual( BoxedLocation.objects.all()[0].bbox_geometry.extent, (11.0, 40.0, 13.0, 42.0), ) def test_get_autogenerated_location_bbox_geojson(self): self._create_locations() response = self.client.get(self.geojson_location_bbox_list_url) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data['features']), 1) self.assertEqual(response.data['features'][0]['bbox'], self.l1.geometry.extent) def test_bbox_improperly_configured(self): self._create_locations() class LocationGeoFeatureSerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = Location geo_field = 'geometry' bbox_geo_field = 'geometry' auto_bbox = True with self.assertRaises(ImproperlyConfigured): LocationGeoFeatureSerializer(instance=self.l1) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1598581253.0 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/test_fields.py0000664000175000017500000004765400000000000031775 0ustar00nemesisnemesis00000000000000import json from django.contrib.gis.geos import GEOSGeometry from django.test import TestCase from rest_framework import serializers from rest_framework_gis import serializers as gis_serializers Point = {"type": "Point", "coordinates": [-105.0162, 39.5742]} MultiPoint = { "type": "MultiPoint", "coordinates": [ [-105.0162, 39.5742], [-80.6665, 35.0539], [-80.6665, 35.0539], # Dupe [-80.672, 35.049], ], } LineString = { "type": "LineString", "coordinates": [ [-101.7443, 39.3215], [-101.4021, 39.3300], [-101.4038, 39.3300], [-101.4038, 39.3300], # Dupe [-97.6354, 38.8739], ], } MultiLineString = { "type": "MultiLineString", "coordinates": [ [ [-105.0214, 39.5780], [-105.0215, 39.5778], [-105.0215, 39.5774], [-105.0215, 39.5771], [-105.0215, 39.5771], # Dupe [-105.0215, 39.5770], [-105.0215, 39.5767], ], [ [-105.0171, 39.5744], [-105.0169, 39.5743], [-105.0166, 39.5743], [-105.0166, 39.5743], # Dupe [-105.0165, 39.5744], [-105.0159, 39.5742], ], ], } Polygon = { "type": "Polygon", "coordinates": [ [ [-84.3228, 34.9895], [-82.6062, 36.0335], [-82.6062, 35.9913], [-82.6062, 35.9791], [-82.5787, 35.9613], [-82.5787, 35.9613], # Dupe [-82.5677, 35.9513], [-84.2211, 34.9850], [-84.3228, 34.9895], ], [ [-75.6903, 35.7420], [-75.5914, 35.7420], [-75.5914, 35.7420], # Dupe [-75.7067, 35.7420], [-75.6903, 35.7420], ], ], } MultiPolygon = { "type": "MultiPolygon", "coordinates": [ [ [ [-84.3228, 34.9895], [-84.3227, 34.9895], [-84.3227, 34.9895], # Dupe [-84.2211, 34.9850], [-84.3228, 34.9895], ], [ [-75.6903, 35.7420], [-75.5913, 35.7420], [-75.5913, 35.7420], # Dupe [-75.5914, 35.7420], [-75.6903, 35.7420], ], ], [ [ [-109.0283, 36.9850], [-102.0629, 40.9798], [-102.0629, 40.9798], # Dupe [-109.0283, 36.9851], [-109.0283, 36.9850], ], ], ], } GeometryCollection = { "type": "GeometryCollection", "geometries": [Point, Polygon, LineString], } class BaseTestCase(TestCase): @staticmethod def get_instance(data_dict): class Model(object): def __init__(self, geojson_dict): self.geometry = GEOSGeometry(json.dumps(geojson_dict)) return Model(data_dict) @staticmethod def create_serializer(**kwargs): class LocationGeoSerializer(serializers.Serializer): geometry = gis_serializers.GeometryField(**kwargs) return LocationGeoSerializer def normalize(self, data): """ To help with equality operators, cast nested inputted data from OrderedDict or GeoJsonDict to dict and from tuple to array. """ if isinstance(data, (tuple, list)): return [self.normalize(d) for d in data] if isinstance(data, dict): return {k: self.normalize(v) for k, v in data.items()} return data class TestPrecision(BaseTestCase): def test_precision_Point(self): model = self.get_instance(Point) Serializer = self.create_serializer(precision=2) data = Serializer(model).data self.assertEqual( self.normalize(data), {'geometry': {"type": "Point", "coordinates": [-105.02, 39.57]}}, ) def test_precision_MultiPoint(self): model = self.get_instance(MultiPoint) Serializer = self.create_serializer(precision=2) data = Serializer(model).data self.assertEqual( self.normalize(data), { 'geometry': { "type": "MultiPoint", "coordinates": [ [-105.02, 39.57], [-80.67, 35.05], [-80.67, 35.05], [-80.67, 35.05], ], } }, ) def test_precision_LineString(self): model = self.get_instance(LineString) Serializer = self.create_serializer(precision=2) data = Serializer(model).data self.assertEqual( self.normalize(data), { 'geometry': { "type": "LineString", "coordinates": [ [-101.74, 39.32], [-101.40, 39.33], [-101.40, 39.33], [-101.40, 39.33], [-97.64, 38.87], ], } }, ) def test_precision_MultiLineString(self): model = self.get_instance(MultiLineString) Serializer = self.create_serializer(precision=2) data = Serializer(model).data self.assertEqual( self.normalize(data), { 'geometry': { "type": "MultiLineString", "coordinates": [ [ [-105.02, 39.58], [-105.02, 39.58], [-105.02, 39.58], [-105.02, 39.58], [-105.02, 39.58], [-105.02, 39.58], [-105.02, 39.58], ], [ [-105.02, 39.57], [-105.02, 39.57], [-105.02, 39.57], [-105.02, 39.57], [-105.02, 39.57], [-105.02, 39.57], ], ], } }, ) def test_precision_Polygon(self): model = self.get_instance(Polygon) Serializer = self.create_serializer(precision=2) data = Serializer(model).data self.assertEqual( self.normalize(data), { 'geometry': { "type": "Polygon", "coordinates": [ [ [-84.32, 34.99], [-82.61, 36.03], [-82.61, 35.99], [-82.61, 35.98], [-82.58, 35.96], [-82.58, 35.96], [-82.57, 35.95], [-84.22, 34.98], [-84.32, 34.99], ], [ [-75.69, 35.74], [-75.59, 35.74], [-75.59, 35.74], [-75.71, 35.74], [-75.69, 35.74], ], ], } }, ) def test_precision_MultiPolygon(self): model = self.get_instance(MultiPolygon) Serializer = self.create_serializer(precision=2) data = Serializer(model).data self.assertEqual( self.normalize(data), { 'geometry': { "type": "MultiPolygon", "coordinates": [ [ [ [-84.32, 34.99], [-84.32, 34.99], [-84.32, 34.99], [-84.22, 34.98], [-84.32, 34.99], ], [ [-75.69, 35.74], [-75.59, 35.74], [-75.59, 35.74], [-75.59, 35.74], [-75.69, 35.74], ], ], [ [ [-109.03, 36.98], [-102.06, 40.98], [-102.06, 40.98], [-109.03, 36.99], [-109.03, 36.98], ], ], ], } }, ) def test_precision_GeometryCollection(self): model = self.get_instance(GeometryCollection) Serializer = self.create_serializer(precision=2) data = Serializer(model).data self.assertEqual( self.normalize(data), { "geometry": { "type": "GeometryCollection", "geometries": [ {"type": "Point", "coordinates": [-105.02, 39.57]}, { "type": "Polygon", "coordinates": [ [ [-84.32, 34.99], [-82.61, 36.03], [-82.61, 35.99], [-82.61, 35.98], [-82.58, 35.96], [-82.58, 35.96], [-82.57, 35.95], [-84.22, 34.98], [-84.32, 34.99], ], [ [-75.69, 35.74], [-75.59, 35.74], [-75.59, 35.74], [-75.71, 35.74], [-75.69, 35.74], ], ], }, { "type": "LineString", "coordinates": [ [-101.74, 39.32], [-101.4, 39.33], [-101.4, 39.33], [-101.4, 39.33], [-97.64, 38.87], ], }, ], } }, ) class TestRmRedundant(BaseTestCase): def test_rm_redundant_Point(self): model = self.get_instance({"type": "Point", "coordinates": [-1.1, -1.1]}) Serializer = self.create_serializer(remove_duplicates=True) data = Serializer(model).data self.assertEqual( self.normalize(data), {"geometry": {"type": "Point", "coordinates": [-1.1, -1.1]}}, ) def test_rm_redundant_MultiPoint(self): model = self.get_instance(MultiPoint) Serializer = self.create_serializer(remove_duplicates=True) data = Serializer(model).data self.assertEqual( self.normalize(data), { "geometry": { "type": "MultiPoint", "coordinates": [ [-105.0162, 39.5742], [-80.6665, 35.0539], # [-80.6665, 35.0539], # Dupe [-80.672, 35.049], ], } }, ) def test_rm_redundant_LineString(self): model = self.get_instance(LineString) Serializer = self.create_serializer(remove_duplicates=True) data = Serializer(model).data self.assertEqual( self.normalize(data), { "geometry": { "type": "LineString", "coordinates": [ [-101.7443, 39.3215], [-101.4021, 39.3300], [-101.4038, 39.3300], # [-101.4038, 39.3300], # Dupe [-97.6354, 38.8739], ], } }, ) def test_rm_redundant_MultiLineString(self): model = self.get_instance(MultiLineString) Serializer = self.create_serializer(remove_duplicates=True) data = Serializer(model).data self.assertEqual( self.normalize(data), { "geometry": { "type": "MultiLineString", "coordinates": [ [ [-105.0214, 39.5780], [-105.0215, 39.5778], [-105.0215, 39.5774], [-105.0215, 39.5771], # [-105.0215, 39.5771], # Dupe [-105.0215, 39.5770], [-105.0215, 39.5767], ], [ [-105.0171, 39.5744], [-105.0169, 39.5743], [-105.0166, 39.5743], # [-105.0166, 39.5743], # Dupe [-105.0165, 39.5744], [-105.0159, 39.5742], ], ], } }, ) def test_rm_redundant_Polygon(self): model = self.get_instance(Polygon) Serializer = self.create_serializer(remove_duplicates=True) data = Serializer(model).data self.assertEqual( self.normalize(data), { "geometry": { "type": "Polygon", "coordinates": [ [ [-84.3228, 34.9895], [-82.6062, 36.0335], [-82.6062, 35.9913], [-82.6062, 35.9791], [-82.5787, 35.9613], # [-82.5787, 35.9613], # Dupe [-82.5677, 35.9513], [-84.2211, 34.985], [-84.3228, 34.9895], ], [ [-75.6903, 35.742], [-75.5914, 35.742], # [-75.5914, 35.7420], # Dupe [-75.7067, 35.742], [-75.6903, 35.742], ], ], } }, ) def test_rm_redundant_MultiPolygon(self): model = self.get_instance(MultiPolygon) Serializer = self.create_serializer(remove_duplicates=True) data = Serializer(model).data self.assertEqual( self.normalize(data), { 'geometry': { "type": "MultiPolygon", "coordinates": [ [ [ [-84.3228, 34.9895], [-84.3227, 34.9895], # [-84.3227, 34.9895], # Dupe [-84.2211, 34.9850], [-84.3228, 34.9895], ], [ [-75.6903, 35.7420], [-75.5913, 35.7420], # [-75.5913, 35.7420], # Dupe [-75.5914, 35.7420], [-75.6903, 35.7420], ], ], [ [ [-109.0283, 36.9850], [-102.0629, 40.9798], # [-102.0629, 40.9798], # Dupe [-109.0283, 36.9851], [-109.0283, 36.9850], ], ], ], } }, ) def test_rm_redundant_MultiPolygon_single_polygon(self): MultiPolygon = { "type": "MultiPolygon", "coordinates": [ [ [ [-109.17227935791, 45.0041122436525], [-109.218215942383, 45.0039901733398], [-109.218215942383, 45.0039901733398], [-109.175567626953, 45.0041999816896], [-109.17227935791, 45.0041122436525], ] ] ], } model = self.get_instance(MultiPolygon) Serializer = self.create_serializer(remove_duplicates=True) data = Serializer(model).data self.assertEqual( self.normalize(data), { 'geometry': { "type": "MultiPolygon", "coordinates": [ [ [ [-109.17227935791, 45.0041122436525], [-109.218215942383, 45.0039901733398], # [-109.218215942383, 45.0039901733398], # Dupe [-109.175567626953, 45.0041999816896], [-109.17227935791, 45.0041122436525], ] ] ], } }, ) def test_rm_redundant_GeometryCollection(self): model = self.get_instance(GeometryCollection) Serializer = self.create_serializer(remove_duplicates=True) data = Serializer(model).data self.assertEqual( self.normalize(data), { "geometry": { "type": "GeometryCollection", "geometries": [ {"type": "Point", "coordinates": [-105.0162, 39.5742]}, { "type": "Polygon", "coordinates": [ [ [-84.3228, 34.9895], [-82.6062, 36.0335], [-82.6062, 35.9913], [-82.6062, 35.9791], [-82.5787, 35.9613], # [-82.5787, 35.9613], # Dupe [-82.5677, 35.9513], [-84.2211, 34.985], [-84.3228, 34.9895], ], [ [-75.6903, 35.742], [-75.5914, 35.742], # [-75.5914, 35.7420], # Dupe [-75.7067, 35.742], [-75.6903, 35.742], ], ], }, { "type": "LineString", "coordinates": [ [-101.7443, 39.3215], [-101.4021, 39.3300], [-101.4038, 39.3300], # [-101.4038, 39.3300], # Dupe [-97.6354, 38.8739], ], }, ], } }, ) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1611531918.0 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/test_filters.py0000664000175000017500000005313600000000000032167 0ustar00nemesisnemesis00000000000000import json import urllib from unittest import skipIf from django.conf import settings from django.contrib.gis.geos import GEOSGeometry, Polygon from django.test import TestCase try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse from .models import Location from .views import ( GeojsonLocationContainedInBBoxList, GeojsonLocationOrderDistanceToPointList, GeojsonLocationWithinDistanceOfPointList, ) has_spatialite = ( settings.DATABASES['default']['ENGINE'] == 'django.contrib.gis.db.backends.spatialite' ) try: from django.contrib.gis.db.models.functions import GeometryDistance has_geometry_distance = GeometryDistance and True except ImportError: has_geometry_distance = False class TestRestFrameworkGisFilters(TestCase): """ unit tests for filters feature in restframework_gis """ def setUp(self): self.location_contained_in_bbox_list_url = reverse( 'api_geojson_location_list_contained_in_bbox_filter' ) self.location_overlaps_bbox_list_url = reverse( 'api_geojson_location_list_overlaps_bbox_filter' ) self.location_contained_in_tile_list_url = reverse( 'api_geojson_location_list_contained_in_tile_filter' ) self.location_overlaps_tile_list_url = reverse( 'api_geojson_location_list_overlaps_tile_filter' ) self.location_within_distance_of_point_list_url = reverse( 'api_geojson_location_list_within_distance_of_point_filter' ) self.location_within_degrees_of_point_list_url = reverse( 'api_geojson_location_list_within_degrees_of_point_filter' ) self.geojson_contained_in_geometry = reverse( 'api_geojson_contained_in_geometry' ) self.location_order_distance_to_point = reverse( 'api_geojson_location_order_distance_to_point_list_filter' ) treasure_island_geojson = """{ "type": "Polygon", "coordinates": [ [ [ -122.44640350341795, 37.86103094116189 ], [ -122.44262695312501, 37.85506751416839 ], [ -122.43481636047363, 37.853305500228025 ], [ -122.42975234985352, 37.854660899304704 ], [ -122.41953849792479, 37.852627791344894 ], [ -122.41807937622069, 37.853305500228025 ], [ -122.41868019104004, 37.86211514878027 ], [ -122.42391586303711, 37.870584971740065 ], [ -122.43035316467285, 37.8723465726078 ], [ -122.43515968322752, 37.86963639998042 ], [ -122.43953704833984, 37.86882332875222 ], [ -122.44640350341795, 37.86103094116189 ] ] ] }""" self.treasure_island_geom = GEOSGeometry(treasure_island_geojson) ggpark_geojson = """{ "type": "Polygon", "coordinates": [ [ [ -122.5111198425293, 37.77125750792944 ], [ -122.51026153564452, 37.76447260365713 ], [ -122.45309829711913, 37.76677954095475 ], [ -122.45481491088867, 37.77424266859531 ], [ -122.5111198425293, 37.77125750792944 ] ] ] }""" self.ggpark_geom = GEOSGeometry(ggpark_geojson) def test_inBBOXFilter_filtering(self): """ Checks that the inBBOXFilter returns only objects strictly contained in the bounding box given by the in_bbox URL parameter """ self.assertEqual(Location.objects.count(), 0) # Bounding box xmin = 0 ymin = 0 xmax = 10 ymax = 10 url_params = '?in_bbox=%d,%d,%d,%d&format=json' % (xmin, ymin, xmax, ymax) # Square with bottom left at (1,1), top right at (9,9) isContained = Location() isContained.name = 'isContained' isContained.geometry = Polygon(((1, 1), (9, 1), (9, 9), (1, 9), (1, 1))) isContained.save() isEqualToBounds = Location() isEqualToBounds.name = 'isEqualToBounds' isEqualToBounds.geometry = Polygon(((0, 0), (10, 0), (10, 10), (0, 10), (0, 0))) isEqualToBounds.save() # Rectangle with bottom left at (-1,1), top right at (5,5) overlaps = Location() overlaps.name = 'overlaps' overlaps.geometry = Polygon(((-1, 1), (5, 1), (5, 5), (-1, 5), (-1, 1))) overlaps.save() # Rectangle with bottom left at (-3,-3), top right at (-1,2) nonIntersecting = Location() nonIntersecting.name = 'nonIntersecting' nonIntersecting.geometry = Polygon( ((-3, -3), (-1, -3), (-1, 2), (-3, 2), (-3, -3)) ) nonIntersecting.save() # Make sure we only get back the ones strictly contained in the bounding box response = self.client.get( self.location_contained_in_bbox_list_url + url_params ) self.assertEqual(len(response.data['features']), 2) for result in response.data['features']: self.assertEqual( result['properties']['name'] in ('isContained', 'isEqualToBounds'), True ) # Make sure we get overlapping results for the view which allows bounding box overlaps. response = self.client.get(self.location_overlaps_bbox_list_url + url_params) self.assertEqual(len(response.data['features']), 3) for result in response.data['features']: self.assertEqual( result['properties']['name'] in ('isContained', 'isEqualToBounds', 'overlaps'), True, ) @skipIf(has_spatialite, 'Skipped test for spatialite backend: not accurate enough') def test_TileFilter_filtering(self): """ Checks that the TMSTileFilter returns only objects strictly contained in the bounding box given by the tile URL parameter """ self.assertEqual(Location.objects.count(), 0) # Bounding box z = 1 x = 1 y = 0 url_params = '?tile=%d/%d/%d&format=json' % (z, x, y) # Square with bottom left at (1,1), top right at (9,9) isContained = Location() isContained.name = 'isContained' isContained.geometry = Polygon(((1, 1), (9, 1), (9, 9), (1, 9), (1, 1))) isContained.save() isEqualToBounds = Location() isEqualToBounds.name = 'isEqualToBounds' isEqualToBounds.geometry = Polygon( ((0, 0), (0, 85.05113), (180, 85.05113), (180, 0), (0, 0)) ) isEqualToBounds.save() # Rectangle with bottom left at (-1,1), top right at (5,5) overlaps = Location() overlaps.name = 'overlaps' overlaps.geometry = Polygon(((-1, 1), (5, 1), (5, 5), (-1, 5), (-1, 1))) overlaps.save() # Rectangle with bottom left at (-3,-3), top right at (-1,2) nonIntersecting = Location() nonIntersecting.name = 'nonIntersecting' nonIntersecting.geometry = Polygon( ((-3, -3), (-1, -3), (-1, 2), (-3, 2), (-3, -3)) ) nonIntersecting.save() # Make sure we only get back the ones strictly contained in the bounding box response = self.client.get( self.location_contained_in_tile_list_url + url_params ) self.assertEqual(len(response.data['features']), 2) for result in response.data['features']: self.assertEqual( result['properties']['name'] in ('isContained', 'isEqualToBounds'), True ) # Make sure we get overlapping results for the view which allows bounding box overlaps. response = self.client.get(self.location_overlaps_tile_list_url + url_params) self.assertEqual(len(response.data['features']), 3) for result in response.data['features']: self.assertEqual( result['properties']['name'] in ('isContained', 'isEqualToBounds', 'overlaps'), True, ) @skipIf( has_spatialite, 'Skipped test for spatialite backend: missing feature "dwithin"' ) def test_DistanceToPointFilter_filtering(self): """ Checks that the DistanceFilter returns only objects within the given distance of the given geometry defined by the URL parameters """ self.assertEqual(Location.objects.count(), 0) # Filter parameters distance = 5000 # meters point_on_alcatraz = [-122.4222, 37.82667] url_params = '?dist=%0.4f&point=hello&format=json' % (distance,) response = self.client.get( '%s%s' % (self.location_within_distance_of_point_list_url, url_params) ) self.assertEqual(response.status_code, 400) url_params = '?dist=%0.4f&point=%0.4f,%0.4f&format=json' % ( distance, point_on_alcatraz[0], point_on_alcatraz[1], ) treasure_island = Location() treasure_island.name = "Treasure Island" treasure_island.geometry = self.treasure_island_geom treasure_island.full_clean() treasure_island.save() ggpark = Location() ggpark.name = "Golden Gate Park" ggpark.geometry = self.ggpark_geom ggpark.save() # Make sure we only get back the ones within the distance response = self.client.get( '%s%s' % (self.location_within_distance_of_point_list_url, url_params) ) self.assertEqual(len(response.data['features']), 1) for result in response.data['features']: self.assertEqual(result['properties']['name'], treasure_island.name) # Make sure we get back all the ones within the distance distance = 7000 url_params = '?dist=%0.4f&point=%0.4f,%0.4f&format=json' % ( distance, point_on_alcatraz[0], point_on_alcatraz[1], ) response = self.client.get( '%s%s' % (self.location_within_distance_of_point_list_url, url_params) ) self.assertEqual(len(response.data['features']), 2) for result in response.data['features']: self.assertIn( result['properties']['name'], (ggpark.name, treasure_island.name) ) # Make sure we only get back the ones within the distance degrees = 0.05 url_params = '?dist=%0.4f&point=%0.4f,%0.4f&format=json' % ( degrees, point_on_alcatraz[0], point_on_alcatraz[1], ) response = self.client.get( self.location_within_degrees_of_point_list_url + url_params ) self.assertEqual(len(response.data['features']), 1) for result in response.data['features']: self.assertEqual(result['properties']['name'], treasure_island.name) @skipIf( has_spatialite, 'Skipped test for spatialite backend: missing feature "GeometryDistance"', ) @skipIf( not has_geometry_distance, 'Skipped test for Django < 3.0: missing feature "GeometryDistance"', ) def test_DistanceToPointOrderingFilter_filtering(self): """ Checks that the DistanceOrderingFilter returns the objects in the correct order given the geometry defined by the URL parameters """ self.assertEqual(Location.objects.count(), 0) url_params = '?point=hello&format=json' response = self.client.get( '%s%s' % (self.location_order_distance_to_point, url_params) ) self.assertEqual(response.status_code, 400) Location.objects.create( name='Houston', geometry='SRID=4326;POINT (-95.363151 29.763374)' ) Location.objects.create( name='Dallas', geometry='SRID=4326;POINT (-96.801611 32.782057)' ) Location.objects.create( name='Oklahoma City', geometry='SRID=4326;POINT (-97.521157 34.464642)' ) Location.objects.create( name='Wellington', geometry='SRID=4326;POINT (174.783117 -41.315268)' ) Location.objects.create( name='Pueblo', geometry='SRID=4326;POINT (-104.609252 38.255001)' ) Location.objects.create( name='Lawrence', geometry='SRID=4326;POINT (-95.235060 38.971823)' ) Location.objects.create( name='Chicago', geometry='SRID=4326;POINT (-87.650175 41.850385)' ) Location.objects.create( name='Victoria', geometry='SRID=4326;POINT (-123.305196 48.462611)' ) point = [-90, 40] url_params = '?point=%i,%i&format=json' % (point[0], point[1]) response = self.client.get( '%s%s' % (self.location_order_distance_to_point, url_params) ) self.assertEqual(len(response.data['features']), 8) self.assertEqual( [city['properties']['name'] for city in response.data['features']], [ 'Chicago', 'Lawrence', 'Oklahoma City', 'Dallas', 'Houston', 'Pueblo', 'Victoria', 'Wellington', ], ) url_params = '?point=%i,%i&order=desc&format=json' % (point[0], point[1]) response = self.client.get( '%s%s' % (self.location_order_distance_to_point, url_params) ) self.assertEqual(len(response.data['features']), 8) self.assertEqual( [city['properties']['name'] for city in response.data['features']], [ 'Wellington', 'Victoria', 'Pueblo', 'Houston', 'Dallas', 'Oklahoma City', 'Lawrence', 'Chicago', ], ) @skipIf( has_spatialite, 'Skipped test for spatialite backend: missing feature "contains_properly"', ) def test_GeometryField_filtering(self): """Checks that the GeometryField allows sane filtering.""" self.assertEqual(Location.objects.count(), 0) treasure_island = Location() treasure_island.name = "Treasure Island" treasure_island.geometry = self.treasure_island_geom treasure_island.full_clean() treasure_island.save() ggpark = Location() ggpark.name = "Golden Gate Park" ggpark.geometry = self.ggpark_geom ggpark.save() point_inside_ggpark_geojson = """ { "type": "Point", "coordinates": [ -122.49034881591797, 37.76949349270407 ] } """ try: quoted_param = urllib.quote(point_inside_ggpark_geojson) except AttributeError: quoted_param = urllib.parse.quote(point_inside_ggpark_geojson) url_params = "?contains_properly=%s" % (quoted_param,) response = self.client.get( '{0}{1}'.format(self.geojson_contained_in_geometry, url_params) ) self.assertEqual(len(response.data), 1) geometry_response = GEOSGeometry(json.dumps(response.data[0]['geometry'])) self.assertTrue(geometry_response.equals_exact(self.ggpark_geom)) self.assertEqual(response.data[0]['name'], ggpark.name) # try without any param, should return both response = self.client.get(self.geojson_contained_in_geometry) self.assertEqual(len(response.data), 2) def test_inBBOXFilter_filtering_none(self): url_params = '?in_bbox=&format=json' response = self.client.get( self.location_contained_in_bbox_list_url + url_params ) self.assertDictEqual( response.data, {'type': 'FeatureCollection', 'features': []} ) def test_inBBOXFilter_ValueError(self): url_params = '?in_bbox=0&format=json' response = self.client.get( self.location_contained_in_bbox_list_url + url_params ) self.assertEqual( response.data['detail'], 'Invalid bbox string supplied for parameter in_bbox', ) def test_inBBOXFilter_filter_field_none(self): original_value = GeojsonLocationContainedInBBoxList.bbox_filter_field GeojsonLocationContainedInBBoxList.bbox_filter_field = None url_params = '?in_bbox=0,0,0,0&format=json' response = self.client.get( self.location_contained_in_bbox_list_url + url_params ) self.assertDictEqual( response.data, {'type': 'FeatureCollection', 'features': []} ) GeojsonLocationContainedInBBoxList.bbox_filter_field = original_value def test_TileFilter_filtering_none(self): url_params = '?tile=&format=json' response = self.client.get( self.location_contained_in_tile_list_url + url_params ) self.assertEqual(response.data, {'type': 'FeatureCollection', 'features': []}) def test_TileFilter_ValueError(self): url_params = '?tile=1/0&format=json' response = self.client.get( self.location_contained_in_tile_list_url + url_params ) self.assertEqual( response.data['detail'], 'Invalid tile string supplied for parameter tile' ) def test_DistanceToPointFilter_filtering_none(self): url_params = '?dist=5000&point=&format=json' response = self.client.get( '%s%s' % (self.location_within_distance_of_point_list_url, url_params) ) self.assertDictEqual( response.data, {'type': 'FeatureCollection', 'features': []} ) def test_DistanceToPointFilter_filter_field_none(self): original_value = GeojsonLocationWithinDistanceOfPointList.distance_filter_field GeojsonLocationWithinDistanceOfPointList.distance_filter_field = None url_params = '?dist=5000&point=&format=json' response = self.client.get( '%s%s' % (self.location_within_distance_of_point_list_url, url_params) ) self.assertDictEqual( response.data, {'type': 'FeatureCollection', 'features': []} ) GeojsonLocationWithinDistanceOfPointList.distance_filter_field = original_value def test_DistanceToPointFilter_ValueError_point(self): url_params = '?dist=500.0&point=hello&format=json' response = self.client.get( '%s%s' % (self.location_within_distance_of_point_list_url, url_params) ) self.assertEqual( response.data['detail'], 'Invalid geometry string supplied for parameter point', ) def test_DistanceToPointFilter_ValueError_distance(self): url_params = '?dist=wrong&point=12.0,42.0&format=json' response = self.client.get( '%s%s' % (self.location_within_distance_of_point_list_url, url_params) ) self.assertEqual( response.data['detail'], 'Invalid distance string supplied for parameter dist', ) @skipIf( not has_geometry_distance, 'Skipped test for Django < 3.0: missing feature "GeometryDistance"', ) def test_DistanceToPointOrderingFilter_filtering_none(self): url_params = '?point=&format=json' response = self.client.get( '%s%s' % (self.location_order_distance_to_point, url_params) ) self.assertDictEqual( response.data, {'type': 'FeatureCollection', 'features': []} ) @skipIf( not has_geometry_distance, 'Skipped test for Django < 3.0: missing feature "GeometryDistance"', ) def test_DistanceToPointOrderingFilter_ordering_filter_field_none(self): original_value = ( GeojsonLocationOrderDistanceToPointList.distance_ordering_filter_field ) GeojsonLocationOrderDistanceToPointList.distance_ordering_filter_field = None url_params = '?point=&format=json' response = self.client.get( '%s%s' % (self.location_order_distance_to_point, url_params) ) self.assertDictEqual( response.data, {'type': 'FeatureCollection', 'features': []} ) GeojsonLocationOrderDistanceToPointList.distance_ordering_filter_field = ( original_value ) @skipIf(has_geometry_distance, 'Skipped test for Django >= 3.0') def test_DistanceToPointOrderingFilter_not_available(self): url_params = '?point=12,42&format=json' with self.assertRaises(ValueError): self.client.get( '%s%s' % (self.location_order_distance_to_point, url_params) ) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1598581253.0 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/test_performance.py0000664000175000017500000000363500000000000033017 0ustar00nemesisnemesis00000000000000import sys from django.conf import settings # this test must be run explicitly # either by calling: # django test --keepdb django_restframework_gis_tests.test_performance # or by setting ``settings.TEST_PERFORMANCE`` to ``True`` if ( 'django_restframework_gis_tests.test_performance' in sys.argv or settings.TEST_PERFORMANCE ): from contexttimer import Timer from django.test import TestCase from rest_framework.renderers import JSONRenderer from rest_framework_gis import serializers as gis_serializers from .models import Location class TestRestFrameworkGisPerformance(TestCase): NUMBER_OF_LOCATIONS = 10000 def _create_data(self): """ creates a bunch of gis models instances """ locations = [] name = 'l{0}' slug = 'l{0}' wkt = 'POINT (13.{0}125000020002 42.{0}565179379999)' for n in range(1, self.NUMBER_OF_LOCATIONS): locations.append( Location( name=name.format(n), slug=slug.format(n), geometry=wkt.format(n) ) ) Location.objects.bulk_create(locations) def test_geojson_performance(self): class PerfSerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = Location geo_field = 'geometry' fields = '__all__' # create data self._create_data() # initialize serializer serializer = PerfSerializer(Location.objects.all(), many=True) with Timer() as t: JSONRenderer().render(serializer.data) # print results msg = 'GeoJSON rendering of {0} objects ' 'completed in {1}'.format( self.NUMBER_OF_LOCATIONS, t.elapsed ) print('\n\033[95m{0}\033[0m'.format(msg)) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1640553128.0 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/test_schema_generation.py0000664000175000017500000006332600000000000034174 0ustar00nemesisnemesis00000000000000from unittest import SkipTest import rest_framework from django.test import RequestFactory, TestCase from packaging import version from rest_framework.generics import RetrieveAPIView from rest_framework.request import Request from rest_framework.schemas.openapi import SchemaGenerator from rest_framework_gis.pagination import GeoJsonPagination from rest_framework_gis.schema import GeoFeatureAutoSchema from .serializers import ( BoxedLocationGeoFeatureWithBBoxGeoFieldSerializer, ChildPointSerializer, GeometrySerializer, GeometrySerializerMethodFieldSerializer, LineStringSerializer, ListChildPointSerializer, MultiLineStringSerializer, MultiPointSerializer, MultiPolygonSerializer, PointSerializer, ) from .views import ( GeojsonBoxedLocationDetails, GeojsonLocationContainedInBBoxList, GeojsonLocationContainedInTileList, GeojsonLocationWithinDistanceOfPointList, ModelViewWithPolygon, geojson_location_list, ) is_pre_drf_312 = version.parse(rest_framework.VERSION) < version.parse('3.12') if is_pre_drf_312: raise SkipTest('Skip this test if DRF < 3.12') def create_request(path): factory = RequestFactory() request = Request(factory.get(path)) return request def create_view(view_cls, method, request): generator = SchemaGenerator() view = generator.create_view(view_cls.as_view(), method, request) return view class TestSchemaGeneration(TestCase): def test_point_field_outer_most_gis_serializer(self): class TestPointFieldView(RetrieveAPIView): serializer_class = PointSerializer path = "/" method = "GET" view = create_view(TestPointFieldView, "POST", create_request("/")) inspector = GeoFeatureAutoSchema() inspector.view = view serializer = inspector.get_serializer(path, method) content = inspector.map_serializer(serializer) content.pop("type", None) content["properties"]["properties"].pop("type", None) self.assertEqual( content, { "properties": { "type": {"type": "string", "enum": ["Feature"]}, "id": {"type": "integer", "readOnly": True}, "geometry": { "type": "object", "properties": { "type": {"type": "string", "enum": ["Point"]}, "coordinates": { "type": "array", "items": {"type": "number", "format": "float"}, "example": [12.9721, 77.5933], "minItems": 2, "maxItems": 3, }, }, }, "properties": { "properties": { "random_field1": {"type": "string", "maxLength": 32}, "random_field2": { "type": "integer", "maximum": 2147483647, "minimum": -2147483648, }, }, "required": ["random_field1", "random_field2", "location"], }, } }, ) def test_point_field_inner_geo_serializer(self): class TestPointFieldView(RetrieveAPIView): serializer_class = ChildPointSerializer path = "/" method = "GET" view = create_view(TestPointFieldView, "POST", create_request("/")) inspector = GeoFeatureAutoSchema() inspector.view = view serializer = inspector.get_serializer(path, method) content = inspector.map_serializer(serializer) content.pop("type", None) content["properties"]["point"].pop("type", None) content["properties"]["point"]["properties"]["properties"].pop("type", None) self.assertEqual( content, { "properties": { "point": { "properties": { "type": {"type": "string", "enum": ["Feature"]}, "id": {"type": "integer", "readOnly": True}, "geometry": { "type": "object", "properties": { "type": {"type": "string", "enum": ["Point"]}, "coordinates": { "type": "array", "items": {"type": "number", "format": "float"}, "example": [12.9721, 77.5933], "minItems": 2, "maxItems": 3, }, }, }, "properties": { "properties": { "random_field1": { "type": "string", "maxLength": 32, }, "random_field2": { "type": "integer", "maximum": 2147483647, "minimum": -2147483648, }, }, "required": [ "random_field1", "random_field2", "location", ], }, } } }, "required": ["point"], }, ) def test_point_field_inner_geo_list_serializer(self): class TestPointFieldView(RetrieveAPIView): serializer_class = ListChildPointSerializer path = "/" method = "GET" view = create_view(TestPointFieldView, "POST", create_request("/")) inspector = GeoFeatureAutoSchema() inspector.view = view serializer = inspector.get_serializer(path, method) content = inspector.map_serializer(serializer) content.pop("type", None) content["properties"]["points"].pop("type", None) content["properties"]["points"]["properties"]["features"]["items"][ "properties" ]["properties"].pop("type", None) self.assertEqual( content, { "properties": { "points": { "properties": { "type": {"type": "string", "enum": ["FeatureCollection"]}, "features": { "type": "array", "items": { "type": "object", "properties": { "type": {"type": "string", "enum": ["Feature"]}, "id": {"type": "integer", "readOnly": True}, "geometry": { "type": "object", "properties": { "type": { "type": "string", "enum": ["Point"], }, "coordinates": { "type": "array", "items": { "type": "number", "format": "float", }, "example": [12.9721, 77.5933], "minItems": 2, "maxItems": 3, }, }, }, "properties": { "properties": { "random_field1": { "type": "string", "maxLength": 32, }, "random_field2": { "type": "integer", "maximum": 2147483647, "minimum": -2147483648, }, }, "required": [ "random_field1", "random_field2", "location", ], }, }, }, }, } } }, "required": ["points"], }, ) def test_line_string_field(self): class TestLineStringFieldView(RetrieveAPIView): serializer_class = LineStringSerializer path = "/" method = "GET" view = create_view(TestLineStringFieldView, "POST", create_request("/")) inspector = GeoFeatureAutoSchema() inspector.view = view serializer = inspector.get_serializer(path, method) content = inspector.map_serializer(serializer) geometry_schema = content["properties"]["geometry"] geometry_schema.pop("type", None) self.assertEqual( geometry_schema, { "properties": { "type": {"type": "string", "enum": ["LineString"]}, "coordinates": { "type": "array", "items": { "type": "array", "items": {"type": "number", "format": "float"}, "example": [12.9721, 77.5933], "minItems": 2, "maxItems": 3, }, "example": [[22.4707, 70.0577], [12.9721, 77.5933]], "minItems": 2, }, } }, ) def test_multi_polygon(self): class TestMultiPolygonFieldView(RetrieveAPIView): serializer_class = MultiPolygonSerializer path = "/" method = "GET" view = create_view(TestMultiPolygonFieldView, "POST", create_request("/")) inspector = GeoFeatureAutoSchema() inspector.view = view serializer = inspector.get_serializer(path, method) content = inspector.map_serializer(serializer) geometry_schema = content["properties"]["geometry"] geometry_schema.pop("type", None) self.assertEqual( geometry_schema, { "properties": { "type": {"type": "string", "enum": ["MultiPolygon"]}, "coordinates": { "type": "array", "items": { "type": "array", "items": { "type": "array", "items": { "type": "array", "items": {"type": "number", "format": "float"}, "example": [12.9721, 77.5933], "minItems": 2, "maxItems": 3, }, "example": [[22.4707, 70.0577], [12.9721, 77.5933]], "minItems": 4, }, "example": [ [0.0, 0.0], [0.0, 50.0], [50.0, 50.0], [50.0, 0.0], [0.0, 0.0], ], }, "example": [ [ [0.0, 0.0], [0.0, 50.0], [50.0, 50.0], [50.0, 0.0], [0.0, 0.0], ] ], }, } }, ) def test_multi_line_string_field(self): class TestMultiLineStringFieldView(RetrieveAPIView): serializer_class = MultiLineStringSerializer path = "/" method = "GET" view = create_view(TestMultiLineStringFieldView, "POST", create_request("/")) inspector = GeoFeatureAutoSchema() inspector.view = view serializer = inspector.get_serializer(path, method) content = inspector.map_serializer(serializer) geometry_schema = content["properties"]["geometry"] geometry_schema.pop("type", None) self.assertEqual( geometry_schema, { "properties": { "type": {"type": "string", "enum": ["MultiLineString"]}, "coordinates": { "type": "array", "items": { "type": "array", "items": { "type": "array", "items": {"type": "number", "format": "float"}, "example": [12.9721, 77.5933], "minItems": 2, "maxItems": 3, }, "example": [[22.4707, 70.0577], [12.9721, 77.5933]], "minItems": 2, }, "example": [[[22.4707, 70.0577], [12.9721, 77.5933]]], }, } }, ) def test_multi_point(self): class TestMultiLineStringFieldView(RetrieveAPIView): serializer_class = MultiPointSerializer path = "/" method = "GET" view = create_view(TestMultiLineStringFieldView, "POST", create_request("/")) inspector = GeoFeatureAutoSchema() inspector.view = view serializer = inspector.get_serializer(path, method) content = inspector.map_serializer(serializer) geometry_schema = content["properties"]["geometry"] geometry_schema.pop("type", None) self.assertEqual( geometry_schema, { "properties": { "type": {"type": "string", "enum": ["MultiPoint"]}, "coordinates": { "type": "array", "items": { "type": "array", "items": {"type": "number", "format": "float"}, "example": [12.9721, 77.5933], "minItems": 2, "maxItems": 3, }, "example": [[12.9721, 77.5933]], }, } }, ) def test_geometry_field(self): class GeometrySerializerFieldView(RetrieveAPIView): serializer_class = GeometrySerializer path = "/" method = "GET" view = create_view(GeometrySerializerFieldView, "POST", create_request("/")) inspector = GeoFeatureAutoSchema() inspector.view = view serializer = inspector.get_serializer(path, method) content = inspector.map_serializer(serializer) geometry_schema = content["properties"]["geometry"] geometry_schema.pop("type", None) geometry_schema['properties'].pop("coordinates", None) self.assertEqual(geometry_schema, {"properties": {"type": {"type": "string"}}}) def check_bbox_schema(self): class TestMultiLineStringFieldView(RetrieveAPIView): serializer_class = MultiPointSerializer path = "/" method = "GET" view = create_view(TestMultiLineStringFieldView, "POST", create_request("/")) inspector = GeoFeatureAutoSchema() inspector.view = view serializer = inspector.get_serializer(path, method) content = inspector.map_serializer(serializer) bbox_schema = content["properties"]["bbox"] self.assertEqual( bbox_schema, { "type": "array", "items": {"type": "number"}, "minItems": 4, "maxItems": 4, "example": [12.9721, 77.5933, 12.9721, 77.5933], }, ) def test_warning_for_geometry_serializer_method_field(self): class TestGeometrySerializerMethodField(RetrieveAPIView): serializer_class = GeometrySerializerMethodFieldSerializer path = "/" method = "GET" view = create_view( TestGeometrySerializerMethodField, "POST", create_request("/") ) inspector = GeoFeatureAutoSchema() inspector.view = view serializer = inspector.get_serializer(path, method) with self.assertWarns(Warning): inspector.map_serializer(serializer) def test_schema_for_bbox_geo_field(self): path = "/" method = "GET" class GeojsonBoxedLocationDetailsWithBBoxGeoFieldView( GeojsonBoxedLocationDetails ): serializer_class = BoxedLocationGeoFeatureWithBBoxGeoFieldSerializer view = create_view( GeojsonBoxedLocationDetailsWithBBoxGeoFieldView, "GET", create_request("/") ) inspector = GeoFeatureAutoSchema() inspector.view = view serializer = inspector.get_serializer(path, method) content = inspector.map_serializer(serializer) bbox_schema = content["properties"]["bbox"] self.assertNotIn( "bbox_geometry", content["properties"]["properties"]["properties"] ) self.assertEqual( bbox_schema, { "type": "array", "items": {"type": "number"}, "minItems": 4, "maxItems": 4, "example": [12.9721, 77.5933, 12.9721, 77.5933], }, ) class TestPaginationSchemaGeneration(TestCase): def test_geo_json_pagination_schema(self): generated_schema = GeoJsonPagination().get_paginated_response_schema( geojson_location_list ) self.assertIn("features", generated_schema["properties"]) generated_schema["properties"].pop("features") self.assertDictEqual( generated_schema, { "type": "object", "properties": { "type": {"type": "string", "enum": ["FeatureCollection"]}, "count": {"type": "integer", "example": 123}, "next": { "type": "string", "nullable": True, "format": "uri", "example": "http://api.example.org/accounts/?page=4", }, "previous": { "type": "string", "nullable": True, "format": "uri", "example": "http://api.example.org/accounts/?page=2", }, }, }, ) class TestRestFrameworkGisFiltersSchema(TestCase): def test_in_BBox_filter_schema(self): path = "/" method = "GET" view = create_view( GeojsonLocationContainedInBBoxList, "GET", create_request("/") ) inspector = GeoFeatureAutoSchema() inspector.view = view generated_schema = inspector.get_filter_parameters(path, method) self.assertDictEqual( generated_schema[0], { "name": "in_bbox", "required": False, "in": "query", "description": "Specify a bounding box as filter: in_bbox=min_lon,min_lat,max_lon,max_lat", "schema": { "type": "array", "items": {"type": "float"}, "minItems": 4, "maxItems": 4, "example": [0, 0, 10, 10], }, "style": "form", "explode": False, }, ) def test_in_TMS_filter_schema(self): path = "/" method = "GET" view = create_view( GeojsonLocationContainedInTileList, "GET", create_request("/") ) inspector = GeoFeatureAutoSchema() inspector.view = view generated_schema = inspector.get_filter_parameters(path, method) self.assertDictEqual( generated_schema[0], { "name": "tile", "required": False, "in": "query", "description": "Specify a bounding box filter defined by a TMS tile address: tile=Z/X/Y", "schema": {"type": "string", "example": "12/56/34"}, }, ) def test_distance_to_point_filter(self): path = "/" method = "GET" view = create_view( GeojsonLocationWithinDistanceOfPointList, "GET", create_request("/") ) inspector = GeoFeatureAutoSchema() inspector.view = view generated_schema = inspector.get_filter_parameters(path, method) self.assertListEqual( generated_schema, [ { "name": "dist", "required": False, "in": "query", "schema": {"type": "number", "format": "float", "default": 1000}, "description": "Represents **Distance** in **Distance to point** filter. " "Default value is used only if ***point*** is passed.", }, { "name": "point", "required": False, "in": "query", "description": "Point represented in **x,y** format. " "Represents **point** in **Distance to point filter**", "schema": { "type": "array", "items": {"type": "float"}, "minItems": 2, "maxItems": 2, "example": [0, 10], }, "style": "form", "explode": False, }, ], ) def test_geometry_field(self): path = "/" method = "GET" view = create_view(ModelViewWithPolygon, "GET", create_request("/")) inspector = GeoFeatureAutoSchema() inspector.view = view serializer = inspector.get_serializer(path, method) content = inspector.map_serializer(serializer) self.assertEqual( content, { "type": "object", "properties": { "id": {'type': 'integer', 'readOnly': True}, 'polygon': { 'properties': { 'coordinates': { 'example': [ [0.0, 0.0], [0.0, 50.0], [50.0, 50.0], [50.0, 0.0], [0.0, 0.0], ], 'items': { 'example': [[22.4707, 70.0577], [12.9721, 77.5933]], 'items': { 'example': [12.9721, 77.5933], 'items': {'format': 'float', 'type': 'number'}, 'maxItems': 3, 'minItems': 2, 'type': 'array', }, 'minItems': 4, 'type': 'array', }, 'type': 'array', }, 'type': {'enum': ['Polygon'], 'type': 'string'}, }, 'type': 'object', }, "random_field1": {"type": "string", "maxLength": 32}, "random_field2": { "type": "integer", "maximum": 2147483647, "minimum": -2147483648, }, }, "required": ["random_field1", "random_field2", "polygon"], }, ) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1640553128.0 djangorestframework-gis-0.18/tests/django_restframework_gis_tests/tests.py0000664000175000017500000007462300000000000030626 0ustar00nemesisnemesis00000000000000""" unit tests for restframework_gis """ import json import pickle import sys from unittest import skipIf import django from django.contrib.gis.geos import GEOSGeometry, Point from django.test import TestCase try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse import rest_framework from django.core.exceptions import ImproperlyConfigured from rest_framework_gis import serializers as gis_serializers from rest_framework_gis.fields import GeoJsonDict from .models import LocatedFile, Location, Nullable from .serializers import LocationGeoSerializer is_pre_drf_39 = not rest_framework.VERSION.startswith('3.9') class TestRestFrameworkGis(TestCase): def setUp(self): self.location_list_url = reverse('api_location_list') self.geojson_location_list_url = reverse('api_geojson_location_list') self.geos_error_message = ( 'Invalid format: string or unicode input unrecognized as GeoJSON,' ' WKT EWKT or HEXEWKB.' ) self.gdal_error_message = ( 'Unable to convert to python object:' ' Invalid geometry pointer returned from "OGR_G_CreateGeometryFromJson".' ) if django.VERSION >= (2, 0, 0): self.value_error_message = ( "Unable to convert to python object:" " String input unrecognized as WKT EWKT, and HEXEWKB." ) else: self.value_error_message = ( "Unable to convert to python object:" " String or unicode input unrecognized as WKT EWKT, and HEXEWKB." ) self.type_error_message = ( "Unable to convert to python object: Improper geometry input type:" ) def _create_locations(self): self.l1 = Location.objects.create( id=1, name='l1', slug='l1', geometry='POINT (13.0078125000020002 42.4234565179379999)', ) self.l2 = Location.objects.create( id=2, name='l2', slug='l2', geometry='POINT (12.0078125000020002 43.4234565179379999)', ) def test_get_location_list(self): response = self.client.get(self.location_list_url) self.assertEqual(response.status_code, 200) def test_post_location_list_geojson(self): self.assertEqual(Location.objects.count(), 0) data = { "name": "geojson input test", "geometry": { "type": "GeometryCollection", "geometries": [ {"type": "Point", "coordinates": [12.492324113849, 41.890307434153]} ], }, } response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) data = { "name": "geojson input test2", "geometry": { "type": "Point", "coordinates": [12.492324113849, 41.890307434153], }, } response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 2) def test_post_location_list_geojson_as_multipartformdata(self): """ emulate sending geojson string in webform """ self.assertEqual(Location.objects.count(), 0) data = { "name": "geojson input test", "geometry": json.dumps( { "type": "GeometryCollection", "geometries": [ { "type": "Point", "coordinates": [12.492324113849, 41.890307434153], } ], } ), } response = self.client.post(self.location_list_url, data) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) def test_post_HTML_browsable_api(self): self.assertEqual(Location.objects.count(), 0) data = { "name": "geojson input test2", "slug": "prova", "geometry": json.dumps( { "type": "GeometryCollection", "geometries": [ { "type": "Point", "coordinates": [12.492324113849, 41.890307434153], } ], } ), } response = self.client.post( self.location_list_url, data, HTTP_ACCEPT='text/html' ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) location = Location.objects.all()[0] self.assertEqual(location.name, 'geojson input test2') self.assertEqual(location.slug, 'prova') def test_post_location_list_WKT(self): self.assertEqual(Location.objects.count(), 0) data = { 'name': 'WKT input test', 'geometry': 'POINT (12.492324113849 41.890307434153)', } response = self.client.post(self.location_list_url, data) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) def test_post_location_list_EWKT(self): self.assertEqual(Location.objects.count(), 0) data = { 'name': 'EWKT input test', 'geometry': 'SRID=28992;POINT(221160 600204)', } response = self.client.post(self.location_list_url, data) expected_coords = (6.381495826183805, 53.384066927384985) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) for lat, lon in zip( Location.objects.get(name='EWKT input test').geometry.coords, expected_coords, ): self.assertAlmostEqual(lat, lon, places=5) def test_post_location_list_WKT_as_json(self): self.assertEqual(Location.objects.count(), 0) data = { 'name': 'WKT input test', 'geometry': 'POINT (12.492324113849 41.890307434153)', } response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) def test_post_location_list_empty_geometry(self): data = {'name': 'empty input test'} response = self.client.post(self.location_list_url, data) self.assertEqual(response.data['geometry'][0], 'This field is required.') data = {'name': 'empty input test', 'geometry': ''} response = self.client.post(self.location_list_url, data) self.assertEqual(response.data['geometry'][0], 'This field is required.') data = {'name': 'empty input test'} response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.data['geometry'][0], 'This field is required.') data = {'name': 'empty input test', 'geometry': ''} response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.data['geometry'][0], 'This field is required.') def test_post_location_list_invalid_WKT(self): data = {'name': 'WKT wrong input test', 'geometry': 'I AM OBVIOUSLY WRONG'} response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 400) self.assertEqual(Location.objects.count(), 0) self.assertEqual(response.data['geometry'][0], self.value_error_message) # repeat as multipart form data response = self.client.post(self.location_list_url, data) self.assertEqual(response.data['geometry'][0], self.value_error_message) data = { 'name': 'I AM MODERATELY WRONG', 'geometry': 'POINT (12.492324113849, 41.890307434153)', } response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.data['geometry'][0], self.geos_error_message) # repeat as multipart form data response = self.client.post(self.location_list_url, data) self.assertEqual(response.data['geometry'][0], self.geos_error_message) def test_post_location_list_invalid_geojson(self): data = { "name": "quite wrong", "geometry": { "type": "ARRRR", "dasdas": [{"STtype": "PTUAMAoint", "NNAare": "rgon"}], }, } response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.data['geometry'][0], self.gdal_error_message) data = {"name": "very wrong", "geometry": ['a', 'b', 'c']} response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.data['geometry'][0][0:65], self.type_error_message) data = {"name": "very wrong", "geometry": False} response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.data['geometry'][0][0:65], self.type_error_message) data = {"name": "very wrong", "geometry": {"value": {"nested": ["yo"]}}} response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.data['geometry'][0], self.gdal_error_message) def test_geojson_format(self): """ test geojson format """ location = Location.objects.create( name='geojson test', geometry='POINT (135.0 45.0)' ) url = reverse('api_geojson_location_details', args=[location.id]) expected = { 'id': location.id, 'type': 'Feature', 'properties': { 'details': "http://testserver/geojson/%s/" % location.id, 'name': 'geojson test', 'fancy_name': 'Kool geojson test', 'timestamp': None, 'slug': 'geojson-test', }, 'geometry': {'type': 'Point', 'coordinates': [135.0, 45.0]}, } response = self.client.get(url) if sys.version_info > (3, 0, 0): self.assertCountEqual(json.dumps(response.data), json.dumps(expected)) else: self.assertItemsEqual(json.dumps(response.data), json.dumps(expected)) response = self.client.get(url, HTTP_ACCEPT='text/html') self.assertContains(response, "Kool geojson test") def test_geojson_id_attribute(self): location = Location.objects.create( name='geojson test', geometry='POINT (10.1 10.1)' ) url = reverse('api_geojson_location_details', args=[location.id]) response = self.client.get(url) self.assertEqual(response.data['id'], location.id) def test_geojson_id_attribute_slug(self): location = Location.objects.create( name='geojson test', geometry='POINT (10.1 10.1)' ) url = reverse('api_geojson_location_slug_details', args=[location.slug]) response = self.client.get(url) self.assertEqual(response.data['id'], location.slug) def test_geojson_false_id_attribute_slug(self): location = Location.objects.create( name='falseid test', geometry='POINT (10.1 10.1)' ) url = reverse('api_geojson_location_falseid_details', args=[location.id]) response = self.client.get(url) self.assertEqual(response.data['properties']['name'], 'falseid test') with self.assertRaises(KeyError): response.data['id'] def test_geojson_no_id_attribute_slug(self): location = Location.objects.create( name='noid test', geometry='POINT (10.1 10.1)' ) url = reverse('api_geojson_location_noid_details', args=[location.id]) response = self.client.get(url) self.assertEqual(response.data['properties']['name'], 'noid test') with self.assertRaises(KeyError): response.data['id'] def test_geojson_filefield_attribute(self): located_file = LocatedFile.objects.create( name='geojson filefield test', geometry='POINT (10.1 10.1)' ) url = reverse('api_geojson_located_file_details', args=[located_file.id]) response = self.client.get(url) self.assertEqual(response.data['properties']['file'], None) def test_post_geojson_location_list(self): self.assertEqual(Location.objects.count(), 0) data = { "type": "Feature", "properties": {"name": "point?", "details": "ignore this"}, "geometry": {"type": "Point", "coordinates": [10.1, 10.1]}, } response = self.client.post( self.geojson_location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) url = reverse( 'api_geojson_location_details', args=[Location.objects.order_by('-id')[0].id], ) response = self.client.get(url) self.assertEqual(response.data['properties']['name'], "point?") self.assertEqual(response.data['geometry']['type'], "Point") self.assertEqual( json.dumps(response.data['geometry']['coordinates']), "[10.1, 10.1]" ) self.assertNotEqual(response.data['properties']['details'], "ignore this") def test_post_geojson_location_list_HTML(self): self.assertEqual(Location.objects.count(), 0) data = { "type": "Feature", "properties": {"name": "point?", "details": "ignore this"}, "geometry": {"type": "Point", "coordinates": [10.1, 10.1]}, } response = self.client.post( self.geojson_location_list_url, data=json.dumps(data), content_type='application/json', HTTP_ACCEPT='text/html', ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) url = reverse( 'api_geojson_location_details', args=[Location.objects.order_by('-id')[0].id], ) response = self.client.get(url) self.assertEqual(response.data['properties']['name'], "point?") self.assertEqual(response.data['geometry']['type'], "Point") self.assertEqual( json.dumps(response.data['geometry']['coordinates']), "[10.1, 10.1]" ) self.assertNotEqual(response.data['properties']['details'], "ignore this") def test_post_invalid_geojson_location_list(self): data = { "type": "Feature", "properties": {"details": "ignore this"}, "geometry": {"type": "Point", "coordinates": [10.1, 10.1]}, } response = self.client.post( self.geojson_location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 400) self.assertEqual(Location.objects.count(), 0) self.assertEqual(response.data['name'][0], "This field is required.") data = { "type": "Feature", "properties": {"name": "point?"}, "geometry": {"type": "Point", "WRONG": {}}, } response = self.client.post( self.geojson_location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 400) self.assertEqual(Location.objects.count(), 0) self.assertEqual(response.data['geometry'][0], self.gdal_error_message) def test_post_geojson_location_list_WKT(self): self.assertEqual(Location.objects.count(), 0) data = { "type": "Feature", "properties": {"name": "point?"}, "geometry": "POINT (10.1 10.1)", } response = self.client.post( self.geojson_location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) url = reverse( 'api_geojson_location_details', args=[Location.objects.order_by('-id')[0].id], ) response = self.client.get(url) self.assertEqual(response.data['properties']['name'], "point?") self.assertEqual(response.data['geometry']['type'], "Point") self.assertEqual( json.dumps(response.data['geometry']['coordinates']), "[10.1, 10.1]" ) def test_geofeatured_model_serializer_compatible_with_geomodel_serializer(self): self.assertEqual(Location.objects.count(), 0) data = { "name": "geojson input test", "geometry": { "type": "GeometryCollection", "geometries": [ {"type": "Point", "coordinates": [12.492324113849, 41.890307434153]} ], }, } response = self.client.post( self.geojson_location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) def test_geofeatured_model_post_as_multipartformdata(self): """ emulate sending geojson string in webform """ self.assertEqual(Location.objects.count(), 0) data = { "name": "geojson input test", "geometry": json.dumps( {"type": "Point", "coordinates": [12.492324113849, 41.890307434153]} ), } response = self.client.post(self.location_list_url, data) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) self.assertEqual(response.data['geometry']['type'], "Point") def test_HTML_browsable_geojson_location_list(self): response = self.client.get( self.geojson_location_list_url, HTTP_ACCEPT='text/html' ) self.assertEqual(response.status_code, 200) self._create_locations() response = self.client.get( self.geojson_location_list_url, HTTP_ACCEPT='text/html' ) self.assertContains(response, 'l1') self.assertContains(response, 'l2') def test_post_geojson_location_list_HTML_web_form(self): self.assertEqual(Location.objects.count(), 0) data = { "name": "HTML test", "geometry": json.dumps({"type": "Point", "coordinates": [10.1, 10.1]}), } response = self.client.post( self.geojson_location_list_url, data, HTTP_ACCEPT='text/html' ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) location = Location.objects.all()[0] self.assertEqual(location.name, "HTML test") self.assertEqual(location.geometry.geom_type, "Point") def test_post_geojson_location_list_HTML_web_form_WKT(self): self.assertEqual(Location.objects.count(), 0) data = {"name": "HTML test WKT", "geometry": "POINT (10.1 10.1)"} response = self.client.post( self.geojson_location_list_url, data, HTTP_ACCEPT='text/html' ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) location = Location.objects.all()[0] self.assertEqual(location.name, "HTML test WKT") @skipIf(is_pre_drf_39, 'Skip this test if DRF < 3.9') def test_geojson_HTML_widget_value(self): self._create_locations() response = self.client.get( self.geojson_location_list_url, HTTP_ACCEPT='text/html' ) self.assertContains(response, '