├── example ├── app │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ │ └── 0001_initial.py │ ├── tests.py │ ├── views.py │ ├── admin.py │ └── models.py ├── example │ ├── __init__.py │ ├── wsgi.py │ ├── urls.py │ └── settings.py └── manage.py ├── wfs ├── __init__.py ├── tests.py ├── apps.py ├── urls.py ├── templates │ ├── exception.xml │ ├── getFeature.xml │ ├── describeFeatureType.xml │ └── getCapabilities.xml ├── admin.py ├── models.py └── views.py ├── MANIFEST.in ├── setup.py ├── README.md └── LICENSE /example/app/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /example/example/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /example/app/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /wfs/__init__.py: -------------------------------------------------------------------------------- 1 | default_app_config = 'wfs.apps.WFSConfig' -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.md 3 | recursive-include wfs/templates * -------------------------------------------------------------------------------- /wfs/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /example/app/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /example/app/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | # Create your views here. 4 | -------------------------------------------------------------------------------- /example/app/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from app.models import MyGeoClass 3 | 4 | 5 | admin.site.register(MyGeoClass) 6 | -------------------------------------------------------------------------------- /wfs/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class WFSConfig(AppConfig): 5 | name = "wfs" 6 | verbose_name = "WFS" 7 | -------------------------------------------------------------------------------- /example/app/models.py: -------------------------------------------------------------------------------- 1 | from django.contrib.gis.db import models 2 | 3 | 4 | class MyGeoClass(models.Model): 5 | geopoint = models.PointField() 6 | objects = models.GeoManager() 7 | -------------------------------------------------------------------------------- /wfs/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import patterns, url 2 | from wfs.views import global_handler 3 | 4 | # APP 5 | urlpatterns = patterns('', 6 | url(r'^(?P\d+)/$', global_handler, name='wfs'), 7 | ) 8 | -------------------------------------------------------------------------------- /example/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings") 7 | 8 | from django.core.management import execute_from_command_line 9 | 10 | execute_from_command_line(sys.argv) 11 | -------------------------------------------------------------------------------- /wfs/templates/exception.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | {{ text }} 8 | -------------------------------------------------------------------------------- /example/example/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for example project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /example/app/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models, migrations 5 | import django.contrib.gis.db.models.fields 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='MyGeoClass', 16 | fields=[ 17 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), 18 | ('geopoint', django.contrib.gis.db.models.fields.PointField(srid=4326)), 19 | ], 20 | ), 21 | ] 22 | -------------------------------------------------------------------------------- /wfs/templates/getFeature.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | {% for ftype, feature in features %} 9 | {% if feature.gml %} 10 | 11 | <{{ ftype.name }} fid="{{ ftype.name }}.{{ feature.id }}"> 12 | {{ feature.xml|safe }} 13 | 14 | 15 | {% endif %} 16 | {% endfor %} 17 | 18 | 19 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | 4 | setup( 5 | name='django-wfs', 6 | packages=find_packages(), 7 | include_package_data=True, 8 | package_dir={'wfs': 'wfs'}, 9 | version='0.0.10', 10 | description='A WFS (web feature service) implementation as a Django application.', 11 | author='Vasco Pinho', 12 | author_email='vascogpinho@gmail.com', 13 | url='https://github.com/vascop/django-wfs', 14 | download_url='https://github.com/vascop/django-wfs/tarball/master', 15 | long_description=open('README.md', 'r').read(), 16 | license='Apache 2.0', 17 | keywords=['wfs', 'geo', 'django'], 18 | classifiers=[ 19 | 'Environment :: Web Environment', 20 | 'Framework :: Django', 21 | 'Intended Audience :: Developers', 22 | ], 23 | ) 24 | -------------------------------------------------------------------------------- /wfs/templates/describeFeatureType.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | {% for featuretype in featuretypes %} 11 | 12 | 13 | 14 | 15 | 16 | {{ featuretype.xml|safe }} 17 | 18 | 19 | 20 | 21 | {% endfor %} 22 | -------------------------------------------------------------------------------- /example/example/urls.py: -------------------------------------------------------------------------------- 1 | """example URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.8/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Add an import: from blog import urls as blog_urls 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) 15 | """ 16 | from django.conf.urls import include, url 17 | from django.contrib import admin 18 | 19 | urlpatterns = [ 20 | url(r'^admin/', include(admin.site.urls)), 21 | url(r'^wfs/', include('wfs.urls')), 22 | ] 23 | -------------------------------------------------------------------------------- /wfs/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from wfs.models import Service, FeatureType, MetadataURL, BoundingBox 3 | from django import forms 4 | 5 | 6 | class MetadataURLInline(admin.StackedInline): 7 | model = MetadataURL 8 | extra = 0 9 | 10 | 11 | class BBoxInline(admin.StackedInline): 12 | model = BoundingBox 13 | extra = 0 14 | 15 | 16 | class FeatureTypeForm(forms.ModelForm): 17 | fields = forms.MultipleChoiceField(required=False, choices=(), widget=forms.CheckboxSelectMultiple, help_text="Must contain a geometry field. Fields only appear for selection after you select a model. If no field is selected ALL fields will be displayed.") 18 | 19 | def __init__(self, *args, **kwargs): 20 | super(FeatureTypeForm, self).__init__(*args, **kwargs) 21 | if hasattr(self.instance, "model"): 22 | self.fields['fields'].choices = [(field.name, field.name) for field in self.instance.model.model_class()._meta.fields] 23 | if self.instance.fields: 24 | self.initial['fields'] = [str(field) for field in self.instance.fields.split(",")] 25 | 26 | class Meta: 27 | model = FeatureType 28 | exclude = () 29 | 30 | def clean_fields(self): 31 | data = self.cleaned_data['fields'] 32 | cleaned_data = ",".join(data) 33 | return cleaned_data 34 | 35 | 36 | class FeatureTypeAdmin(admin.ModelAdmin): 37 | model = FeatureType 38 | form = FeatureTypeForm 39 | inlines = [BBoxInline, MetadataURLInline] 40 | 41 | 42 | admin.site.register(Service) 43 | admin.site.register(FeatureType, FeatureTypeAdmin) 44 | -------------------------------------------------------------------------------- /wfs/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.core.urlresolvers import reverse 3 | from django.contrib.sites.models import Site 4 | from django.contrib.contenttypes.models import ContentType 5 | 6 | 7 | class Service(models.Model): 8 | name = models.CharField(max_length=254) 9 | title = models.CharField(max_length=254) 10 | keywords = models.CharField(null=True, blank=True, max_length=254, help_text='Comma separated list of keywords.') 11 | abstract = models.TextField(null=True, blank=True) 12 | fees = models.CharField(null=True, blank=True, max_length=254) 13 | access_constraints = models.CharField(null=True, blank=True, max_length=254) 14 | 15 | def online_resource(self): 16 | return 'http://%s%s' % (Site.objects.get_current().domain, self.get_absolute_url()) 17 | 18 | def get_absolute_url(self): 19 | return reverse('wfs', kwargs={'service_id': self.pk}) 20 | 21 | def __unicode__(self): 22 | return self.name 23 | 24 | 25 | class FeatureType(models.Model): 26 | service = models.ForeignKey(Service) 27 | name = models.CharField(max_length=254) 28 | title = models.CharField(null=True, blank=True, max_length=254) 29 | keywords = models.CharField(null=True, blank=True, max_length=254) 30 | abstract = models.TextField(null=True, blank=True) 31 | srs = models.CharField(max_length=254, default="EPSG:4326") 32 | model = models.ForeignKey(ContentType) 33 | fields = models.CharField(max_length=254, null=True, blank=True) 34 | query = models.TextField(default="{}", help_text="JSON containing the query to be passed to a Django queryset .filter()") 35 | 36 | def __unicode__(self): 37 | return self.name 38 | 39 | def save(self, *args, **kwargs): 40 | if self.pk is not None: 41 | orig = FeatureType.objects.get(pk=self.pk) 42 | if orig.model != self.model: 43 | self.fields = "" 44 | super(FeatureType, self).save(*args, **kwargs) 45 | 46 | 47 | class MetadataURL(models.Model): 48 | featuretype = models.ForeignKey(FeatureType) 49 | url = models.URLField() 50 | 51 | def __unicode__(self): 52 | return self.url 53 | 54 | 55 | class BoundingBox(models.Model): 56 | featuretype = models.ForeignKey(FeatureType) 57 | minx = models.CharField(max_length=254) 58 | miny = models.CharField(max_length=254) 59 | maxx = models.CharField(max_length=254) 60 | maxy = models.CharField(max_length=254) 61 | 62 | def __unicode__(self): 63 | return "((" + self.minx + ", ", self.miny + "), (" + self.maxx + ", " + self.maxy + "))" 64 | -------------------------------------------------------------------------------- /example/example/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for example project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.8.2. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.8/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.8/ref/settings/ 11 | """ 12 | 13 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 14 | import os 15 | 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '@w$0wlo^g!22i*mqsq0f73&yg3g4icnr+ilp8_pzt+k7q$bp11' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = ( 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'django.contrib.gis', 41 | 'django.contrib.sites', 42 | 'wfs', 43 | 'app' 44 | ) 45 | 46 | MIDDLEWARE_CLASSES = ( 47 | 'django.contrib.sessions.middleware.SessionMiddleware', 48 | 'django.middleware.common.CommonMiddleware', 49 | 'django.middleware.csrf.CsrfViewMiddleware', 50 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 51 | 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 52 | 'django.contrib.messages.middleware.MessageMiddleware', 53 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 54 | 'django.middleware.security.SecurityMiddleware', 55 | ) 56 | 57 | ROOT_URLCONF = 'example.urls' 58 | 59 | TEMPLATES = [ 60 | { 61 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 62 | 'DIRS': [], 63 | 'APP_DIRS': True, 64 | 'OPTIONS': { 65 | 'context_processors': [ 66 | 'django.template.context_processors.debug', 67 | 'django.template.context_processors.request', 68 | 'django.contrib.auth.context_processors.auth', 69 | 'django.contrib.messages.context_processors.messages', 70 | ], 71 | }, 72 | }, 73 | ] 74 | 75 | WSGI_APPLICATION = 'example.wsgi.application' 76 | 77 | 78 | # Database 79 | # https://docs.djangoproject.com/en/1.8/ref/settings/#databases 80 | DATABASES = { 81 | 'default': { 82 | 'ENGINE': 'django.contrib.gis.db.backends.postgis', 83 | 'NAME': 'django-wfs', 84 | 'USER': 'vasco', 85 | 'PASSWORD': '', 86 | 'HOST': '127.0.0.1', 87 | 'PORT': '5432', 88 | } 89 | } 90 | 91 | # Internationalization 92 | # https://docs.djangoproject.com/en/1.8/topics/i18n/ 93 | 94 | LANGUAGE_CODE = 'en-us' 95 | 96 | TIME_ZONE = 'UTC' 97 | 98 | USE_I18N = True 99 | 100 | USE_L10N = True 101 | 102 | USE_TZ = True 103 | 104 | SITE_ID = 1 105 | 106 | # Static files (CSS, JavaScript, Images) 107 | # https://docs.djangoproject.com/en/1.8/howto/static-files/ 108 | 109 | STATIC_URL = '/static/' 110 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # django-wfs 2 | A WFS (web feature service) implementation as a Django application. 3 | 4 | This implementation of WFS (currently) **very loosely** follows the [1.0.0 spec](http://www.opengeospatial.org/standards/wfs). It is currently **only tested with a PostGIS backend**. 5 | 6 | What you can expect: 7 | - GetCapabilities 8 | - DescribeFeatureType 9 | - GetFeature 10 | - Django Queryset filtering 11 | 12 | What is not here yet: 13 | - Transactional requests 14 | - Native WFS filtering (bbox and friends) 15 | 16 | # Requirements 17 | - Django 18 | - Django sites framework 19 | - PostgreSQL + PostGIS 20 | 21 | # Example app 22 | An example application can be found in the "example" folder of this repository. 23 | 24 | # Installation 25 | 26 | pip install django-wfs 27 | 28 | Add these to your `INSTALLED_APPS` setting: 29 | 30 | INSTALLED_APPS = ( 31 | ... 32 | 'django.contrib.gis', 33 | 'django.contrib.sites', 34 | 'wfs', 35 | ... 36 | ) 37 | 38 | And define a `SITE_ID` if you haven't yet: 39 | 40 | SITE_ID = 1 41 | 42 | In your `urls.py` add (the actual regex can be anything, it doesn't have to be `^wfs/`): 43 | 44 | url(r'^wfs/', include('wfs.urls')), 45 | 46 | 47 | Make sure you have a working PostGIS GeoDjango installation. Generally, if your database engine is `'django.contrib.gis.db.backends.postgis'`, stuff will probably not break too much. 48 | 49 | # WFS Service and Feature Types 50 | 51 | In the admin you'll now have a WFS section with Services and Feature Types. These are the concepts present in the WFS spec but generally you can have multiple feature types in each service. 52 | 53 | A Service is an endpoint like `/wfs/1` (service with ID 1). It has the parameters defined in the spec: 54 | 55 | - Name 56 | - Title 57 | - Keywords 58 | - Abstract 59 | - Fees 60 | - Access constraints 61 | 62 | After you create a Service in the Django Admin you can then associate a Feature Type to the created service. A Feature Type has the following parameters: 63 | - Service (foreign key) 64 | - Name (**no spaces!!**) 65 | - Title 66 | - Keywords 67 | - Abstract 68 | - SRS: Spatial Reference System used by the Feature Type. Defaults to WGS 84 (EPSG:4326) 69 | - Model (any model present in your Django project which contains a geo field) 70 | - Fields (after selecting a Model and pressing the "Save and continue editing" button and you'll see its fields. The ones you select will be exposed through the service) 71 | - Query (JSON representation of Django queryset filters. Example follows) 72 | 73 | ### Query 74 | 75 | The JSON representation of Django queryset filters allow you cut down results presented by a Feature Type. Some examples: 76 | 77 | Only display entries from a model if they belong to the "vascop" user: 78 | 79 | {"user__username":"vascop"} 80 | 81 | Only display entries from a model if they belong to the "vascop" user and are published: 82 | 83 | {"user__username":"vascop", "published": true} 84 | 85 | 86 | # Possible problems 87 | 88 | If you have `APPEND_SLASH = True` (which is the Django default) and you're adding your WFS service to QGIS be sure to insert the connection with an appended slash, otherwise Django replies with a 301 code and QGIS won't display your layer. 89 | 90 | Be sure to use Feature Type names which have no spaces or special characters. The title can have whatever you want. 91 | 92 | Any other problem, submit an issue and I'll try to take a look at it. 93 | 94 | -------------------------------------------------------------------------------- /wfs/templates/getCapabilities.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | {{ service.name }} 14 | {{ service.title }} 15 | {% if service.abstract %}{{ service.abstract }}{% endif %} 16 | {% if service.keywords %}{{ service.keywords }}{% endif %} 17 | {{ service.online_resource }} 18 | {% if service.fees %}{{ service.fees }}{% endif %} 19 | {% if service.access_constraints %}{{ service.access_constraints{% endif %} 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | {% for feature in service.featuretype_set.all %} 78 | 79 | {{ feature.name }} 80 | {{ feature.title }} 81 | {{ feature.abstract }} 82 | {{ feature.keywords }} 83 | {{ feature.srs }} 84 | {% for bbox in feature.boundingbox_set.all %} 85 | 86 | {% endfor %} 87 | 88 | {% endfor %} 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /wfs/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.views.decorators.csrf import csrf_exempt 3 | from django.contrib.sites.models import Site 4 | from wfs.models import Service, FeatureType 5 | import json 6 | 7 | # xmllint --schema wfs/validation_schemas/WFS-capabilities.xsd 8 | # "http://localhost:8000/wfs/?SERVICE=WFS&REQUEST=GetCapabilities&VERSION=99.99.99&bbox=1.2,3,4.5,-7" --noout 9 | 10 | 11 | @csrf_exempt 12 | def global_handler(request, service_id): 13 | request_type = None 14 | version = None 15 | service = None 16 | available_requests = ("getcapabilities", "describefeaturetype", "getfeature") 17 | available_services = ("wfs",) 18 | 19 | try: 20 | wfs = Service.objects.get(id=service_id) 21 | except Service.DoesNotExist: 22 | return wfs_exception(request, "UnknownService", "", service_id) 23 | 24 | for key, value in request.GET.items(): 25 | low_key = key.lower() 26 | low_value = value.lower() 27 | 28 | if low_key == "request": 29 | request_type = low_value 30 | if request_type not in available_requests: 31 | return wfs_exception(request, "InvalidRequest", "request", value) 32 | 33 | if low_key == "version": 34 | try: 35 | version = map(int, value.split(".")) 36 | except: 37 | return wfs_exception(request, "VersionNegotiationFailed", "version", value) 38 | else: 39 | if len(version) != 3: 40 | return wfs_exception(request, "VersionNegotiationFailed", "version", value) 41 | 42 | if low_key == "service": 43 | service = low_value 44 | if service not in available_services: 45 | return wfs_exception(request, "InvalidService", "service", service) 46 | 47 | if request_type is None: 48 | return wfs_exception(request, "MissingParameter", "request") 49 | 50 | if service is None: 51 | return wfs_exception(request, "MissingParameter", "service") 52 | 53 | if request_type == "getcapabilities": 54 | return getcapabilities(request, wfs) 55 | elif request_type == "describefeaturetype": 56 | return describefeaturetype(request, wfs) 57 | elif request_type == "getfeature": 58 | return getfeature(request, wfs) 59 | 60 | return wfs_exception(request, "UnknownError", "") 61 | 62 | 63 | def getcapabilities(request, service): 64 | context = {} 65 | context['service'] = service 66 | context['namespaces'] = [Site.objects.get_current()] 67 | 68 | return render(request, 'getCapabilities.xml', context, content_type="text/xml") 69 | 70 | 71 | # PostgreSQL generate xml schema 72 | # SELET * FROM table_to_xml(tbl regclass, nulls boolean, tableforest boolean, targetns text) 73 | def describefeaturetype(request, service): 74 | typename = None 75 | outputformat = None 76 | available_formats = ("xmlschema",) 77 | 78 | for key, value in request.GET.items(): 79 | low_key = key.lower() 80 | low_value = value.lower() 81 | 82 | if low_key == "typename": 83 | typename = value 84 | 85 | if low_key == "outputformat": 86 | outputformat = low_value 87 | if outputformat not in available_formats: 88 | return wfs_exception(request, "InvalidParameterValue", "outputformat", value) 89 | 90 | if typename is None: 91 | ft = service.featuretype_set.all() 92 | else: 93 | ft = service.featuretype_set.filter(name__in=typename.split(",")) 94 | 95 | if len(ft) < 1: 96 | return wfs_exception(request, "InvalidParameterValue", "typename", typename) 97 | 98 | featuretype_to_xml(ft) 99 | 100 | context = {} 101 | context['featuretypes'] = ft 102 | 103 | return render(request, 'describeFeatureType.xml', context, content_type="text/xml") 104 | 105 | 106 | def getfeature(request, service): 107 | context = {} 108 | propertyname = None 109 | featureversion = None 110 | maxfeatures = None 111 | typename = None 112 | featureid = None 113 | filtr = None 114 | bbox = None 115 | 116 | for key, value in request.GET.items(): 117 | low_key = key.lower() 118 | low_value = value.lower() 119 | 120 | if low_key == "propertyname": 121 | propertyname = low_value 122 | 123 | if low_key == "featureversion": 124 | featureversion = low_value 125 | 126 | if low_key == "maxfeatures": 127 | try: 128 | maxfeatures = int(low_value) 129 | except: 130 | return wfs_exception(request, "InvalidParameterValue", "maxfeatures", value) 131 | else: 132 | if maxfeatures < 1: 133 | return wfs_exception(request, "InvalidParameterValue", "maxfeatures", value) 134 | 135 | if low_key == "typename": 136 | typename = low_value 137 | 138 | if low_key == "featureid": 139 | featureid = low_value 140 | 141 | if low_key == "filter": 142 | filtr = low_value 143 | 144 | if low_key == "bbox": 145 | bbox = low_value 146 | 147 | if propertyname is not None: 148 | raise NotImplementedError 149 | 150 | if featureversion is not None: 151 | raise NotImplementedError 152 | 153 | if filtr is not None: 154 | raise NotImplementedError 155 | 156 | if bbox is not None: 157 | raise NotImplementedError 158 | 159 | feature_list = [] 160 | # If FeatureID is present we return every feature on the list of ID's 161 | if featureid is not None: 162 | # we assume every feature is identified by its Featuretype name + its object ID like "name.id" 163 | for feature in featureid.split(","): 164 | try: 165 | ftname, fid = get_feature_from_parameter(feature) 166 | except ValueError: 167 | return wfs_exception(request, "InvalidParameterValue", "featureid", feature) 168 | try: 169 | ft = service.featuretype_set.get(name=ftname) 170 | flter = json.loads(ft.query) 171 | try: 172 | f = ft.model.model_class().objects.filter(**flter).filter(id=fid).gml() 173 | feature_list.append((ft, f[0])) 174 | except: 175 | return wfs_exception(request, "MalformedJSONQuery", "query") 176 | except FeatureType.DoesNotExist: 177 | return wfs_exception(request, "InvalidParameterValue", "featureid", feature) 178 | # If FeatureID isn't present we rely on TypeName and return every feature present it the requested FeatureTypes 179 | elif typename is not None: 180 | for typen in typename.split(","): 181 | try: 182 | ft = service.featuretype_set.get(name__iexact=typen) 183 | except FeatureType.DoesNotExist: 184 | return wfs_exception(request, "InvalidParameterValue", "typename", typen) 185 | try: 186 | flter = json.loads(ft.query) 187 | for i in ft.model.model_class().objects.all().filter(**flter).gml(): 188 | feature_list.append((ft, i)) 189 | except: 190 | return wfs_exception(request, "MalformedJSONQuery", "query") 191 | else: 192 | return wfs_exception(request, "MissingParameter", "typename") 193 | 194 | context['features'] = features_to_xml(feature_list) 195 | return render(request, 'getFeature.xml', context, content_type="text/xml") 196 | 197 | 198 | def wfs_exception(request, code, locator, parameter=None): 199 | context = {} 200 | context['code'] = code 201 | context['locator'] = locator 202 | 203 | text = "" 204 | if code == "InvalidParameterValue": 205 | text = "Invalid value '" + str(parameter) + "' in parameter '" + str(locator) + "'." 206 | elif code == "VersionNegotiationFailed": 207 | text = "'" + str(parameter) + "' is an invalid version number." 208 | elif code == "InvalidRequest": 209 | text = "'" + str(parameter) + "' is an invalid request." 210 | elif code == "InvalidService": 211 | text = "'" + str(parameter) + "' is an invalid service." 212 | elif code == "MissingParameter": 213 | text = "Missing required '" + str(locator) + "' parameter." 214 | elif code == "UnknownService": 215 | text = "No available WFS service with id '" + str(parameter) + "'." 216 | elif code == "MalformedJSONQuery": 217 | text = "The JSON query defined for this feature type is malformed." 218 | elif code == "UnknownError": 219 | text = "Something went wrong." 220 | 221 | context['text'] = text 222 | return render(request, 'exception.xml', context, content_type="text/xml") 223 | 224 | 225 | def featuretype_to_xml(featuretypes): 226 | for ft in featuretypes: 227 | ft.xml = "" 228 | fields = ft.model.model_class()._meta.fields 229 | for field in fields: 230 | if len(ft.fields) == 0 or field.name in ft.fields.split(","): 231 | ft.xml += '' 236 | 237 | 238 | def features_to_xml(feature_list): 239 | for (ftype, feature) in feature_list: 240 | feature.xml = "" 241 | for field in feature._meta.fields: 242 | if len(ftype.fields) == 0 or field.name in ftype.fields.split(","): 243 | if hasattr(field, "geom_type"): 244 | if feature.gml: 245 | feature.xml += "" + feature.gml + "" 246 | else: 247 | feature.xml += u"<{}>{}".format(field.name, getattr(feature, field.name), field.name) 248 | 249 | return feature_list 250 | 251 | 252 | def get_feature_from_parameter(parameter): 253 | dot = 0 254 | for c in parameter: 255 | if c == ".": 256 | dot += 1 257 | if dot > 1: 258 | break 259 | if dot != 1: 260 | raise ValueError 261 | 262 | return parameter.split(".") 263 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | --------------------------------------------------------------------------------