djangorestframework-gis-0.14/0000775000175000017500000000000013400751456017433 5ustar nemesisnemesis00000000000000djangorestframework-gis-0.14/djangorestframework_gis.egg-info/0000775000175000017500000000000013400751456026045 5ustar nemesisnemesis00000000000000djangorestframework-gis-0.14/djangorestframework_gis.egg-info/top_level.txt0000664000175000017500000000002313400751456030572 0ustar nemesisnemesis00000000000000rest_framework_gis djangorestframework-gis-0.14/djangorestframework_gis.egg-info/dependency_links.txt0000664000175000017500000000000113400751456032113 0ustar nemesisnemesis00000000000000 djangorestframework-gis-0.14/djangorestframework_gis.egg-info/PKG-INFO0000664000175000017500000007500013400751456027144 0ustar nemesisnemesis00000000000000Metadata-Version: 1.1 Name: djangorestframework-gis Version: 0.14 Summary: Geographic add-ons for Django Rest Framework Home-page: https://github.com/djangonauts/django-rest-framework-gis Author: Douglas Meehan Author-email: django-rest-framework-gis@googlegroups.com License: BSD Download-URL: https://github.com/djangonauts/django-rest-framework-gis/releases Project-URL: Bug Reports, https://github.com/djangonauts/django-rest-framework-gis/issues Project-URL: Source Code, https://github.com/djangonauts/django-rest-framework-gis Project-URL: Code Coverage, https://coveralls.io/github/djangonauts/django-rest-framework-gis Project-URL: Mailing List, https://groups.google.com/forum/#!forum/django-rest-framework-gis Project-URL: Continuous Integration, https://travis-ci.org/djangonauts/django-rest-framework-gis Description: django-rest-framework-gis ========================= |Build Status| |Coverage Status| |Requirements Status| |PyPI version| 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/djangonauts/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.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`` 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 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], } } 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": { "point": { "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": { "point": { "type": "Point", "coordinates": [-123.0208, 44.0464], } }, "properties": { "address": "742 Evergreen Terrace", "city": "Springfield", "state": "Oregon", } } { "id": 2, "type": "Feature", "geometry": { "point": { "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 disbaled 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 equivalant 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, ) bbox_filter_include_overlapping = True # Optional 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 equivalant 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%. Projects using this package --------------------------- - `Nodeshot `__: Extensible Django web application for management of community-led georeferenced data 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 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://travis-ci.org/djangonauts/django-rest-framework-gis.svg?branch=master :target: https://travis-ci.org/djangonauts/django-rest-framework-gis .. |Coverage Status| image:: https://coveralls.io/repos/djangonauts/django-rest-framework-gis/badge.svg :target: https://coveralls.io/r/djangonauts/django-rest-framework-gis .. |Requirements Status| image:: https://requires.io/github/djangonauts/django-rest-framework-gis/requirements.svg?branch=master :target: https://requires.io/github/djangonauts/django-rest-framework-gis/requirements/?branch=master .. |PyPI version| image:: https://badge.fury.io/py/djangorestframework-gis.svg :target: http://badge.fury.io/py/djangorestframework-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 djangorestframework-gis-0.14/djangorestframework_gis.egg-info/SOURCES.txt0000664000175000017500000000244313400751456027734 0ustar nemesisnemesis00000000000000AUTHORS CHANGES.rst LICENSE MANIFEST.in README.rst requirements.txt 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/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/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/__init__.pydjangorestframework-gis-0.14/djangorestframework_gis.egg-info/requires.txt0000664000175000017500000000002413400751456030441 0ustar nemesisnemesis00000000000000djangorestframework djangorestframework-gis-0.14/tests/0000775000175000017500000000000013400751456020575 5ustar nemesisnemesis00000000000000djangorestframework-gis-0.14/tests/settings.py0000664000175000017500000000404513270704234023007 0ustar nemesisnemesis00000000000000import os TEST_PERFORMANCE = False DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'django_restframework_gis', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': '', 'PORT': '' }, } SECRET_KEY = 'fn)t*+$)ugeyip6-#txyy$5wf2ervc0d2n#h)qb)y5@ly$t*@w' INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', # rest framework 'rest_framework', 'rest_framework_gis', # test app 'django_restframework_gis_tests' ) MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ROOT_URLCONF = 'urls' TIME_ZONE = 'Europe/Rome' LANGUAGE_CODE = 'en-gb' USE_TZ = True USE_I18N = False USE_L10N = False SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) MEDIA_ROOT = '%s/media/' % SITE_ROOT MEDIA_URL = '/media/' STATIC_ROOT = '%s/static/' % SITE_ROOT STATIC_URL = '/static/' TEMPLATE_STRING_IF_INVALID = 'INVALID_TEMPLATE: %s END_INVALID_TEMPLATE' # local settings must be imported before test runner otherwise they'll be ignored try: from local_settings import * except ImportError: pass djangorestframework-gis-0.14/tests/urls.py0000664000175000017500000000105013270704234022125 0ustar nemesisnemesis00000000000000try: from django.urls import include, url except ImportError: from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles import views urlpatterns = [ # Uncomment the next line to enable the admin: url(r'^admin/', admin.site.urls), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'', include('django_restframework_gis_tests.urls')), url(r'^static/(?P.*)$', views.serve), ] djangorestframework-gis-0.14/tests/local_settings.example.py0000664000175000017500000000147013270704234025612 0ustar nemesisnemesis00000000000000# RENAME THIS FILE TO local_settings.py IF YOU NEED TO CUSTOMIZE SOME SETTINGS # BUT DO NOT COMMIT TEST_PERFORMANCE = True #DATABASES = { # 'default': { # 'ENGINE': 'django.contrib.gis.db.backends.postgis', # 'NAME': 'django_restframework_gis', # 'USER': 'postgres', # 'PASSWORD': 'password', # 'HOST': '127.0.0.1', # 'PORT': '5433' # }, #} # #INSTALLED_APPS = ( # 'django.contrib.auth', # 'django.contrib.contenttypes', # 'django.contrib.sessions', # 'django.contrib.messages', # 'django.contrib.staticfiles', # 'django.contrib.gis', # # # geodjango widgets # # admin # #'grappelli', # 'django.contrib.admin', # # # rest framework # 'rest_framework', # 'rest_framework_gis', # # # test app # 'django_restframework_gis_tests' #) djangorestframework-gis-0.14/tests/manage.py0000775000175000017500000000061313270704234022377 0ustar nemesisnemesis00000000000000#!/usr/bin/env python import os import sys if __name__ == "__main__": try: import local_settings settings_module = 'local_settings' except ImportError: settings_module = 'settings' os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) djangorestframework-gis-0.14/tests/django_restframework_gis_tests/0000775000175000017500000000000013400751456027076 5ustar nemesisnemesis00000000000000djangorestframework-gis-0.14/tests/django_restframework_gis_tests/test_performance.py0000664000175000017500000000400113270704234033000 0ustar nemesisnemesis00000000000000import 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 django.test import TestCase try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse from rest_framework.renderers import JSONRenderer from rest_framework_gis import serializers as gis_serializers from contexttimer import Timer 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)) djangorestframework-gis-0.14/tests/django_restframework_gis_tests/models.py0000664000175000017500000000214413270704234030731 0ustar nemesisnemesis00000000000000from django.contrib.gis.db import models from django.utils.text import slugify __all__ = [ 'Location', 'LocatedFile', 'BoxedLocation' ] 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 __unicode__(self): return self.name def _generate_slug(self): if self.slug == '' or self.slug is None: try: name = unicode(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(BaseModel, self).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() djangorestframework-gis-0.14/tests/django_restframework_gis_tests/tests.py0000664000175000017500000007202613400750651030615 0ustar nemesisnemesis00000000000000""" unit tests for restframework_gis """ import django import urllib import sys import json import pickle from unittest import skipIf from django.test import TestCase from django.contrib.gis.geos import GEOSGeometry, Polygon, Point try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse from django.core.exceptions import ImproperlyConfigured import rest_framework from rest_framework_gis import serializers as gis_serializers from rest_framework_gis.fields import GeoJsonDict from .models import Location, LocatedFile 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[0] == 2: 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 l, e in zip(Location.objects.get(name='EWKT input test').geometry.coords, expected_coords): self.assertAlmostEqual(l, e, 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, '