Geoprocessing with OGR and PyWPS
PyWPS is a neat Python package supporting the OGC Web Processing Service standard. Basic setup and configuration can be found in the documentation, or Tim’s useful post.
I’ve been working on a demo to expose the OGR Python bindings for geoprocessing (buffer, centroid, etc.).
Here’s an example process to buffer a geometry (input as WKT), and output either GML, JSON, or WKT:
from pywps.Process import WPSProcess import osgeo.ogr as ogr class Buffer(WPSProcess): def __init__(self): WPSProcess.__init__(self, identifier='buffer', title='Buffer generator', metadata=['http://www.kralidis.ca/'], profile='OGR / GEOS geoprocessing', abstract='Buffer generator', version='0.0.1', storeSupported='true', statusSupported='true') self.wkt = self.addLiteralInput(identifier='wkt', \ title='Well Known Text', type=type('string')) self.format = self.addLiteralInput(identifier='format', \ title='Output format', type=type('string')) self.buffer = self.addLiteralInput(identifier='buffer', \ title='Buffer Value', type=type(1)) self.out = self.addLiteralOutput(identifier='output', \ title='Buffered Feature', type=type('string')) def execute(self): buffer = ogr.CreateGeometryFromWkt( \ self.wkt.getValue()).Buffer(self.buffer.getValue()) self.out.setValue(_genOutputFormat(buffer, self.format.getValue())) buffer.Destroy()
def _setNamespace(xml, prefix, uri):
return xml.replace('>', ' xmlns:%s="%s">' % (prefix, uri), 1)
def _genOutputFormat(geom, format):
if format == 'gml':
return _setNamespace(geom.ExportToGML(), 'gml', \ 'http://www.opengis.net/gml')
if format == 'json':
return geom.ExportToJson()
if format == 'wkt':
return geom.ExportToWkt()
Notes:
- _setNamespace is a workaround, as OGR’s ExportToGML doesn’t declare a namespace prefix / uri in the output, which would make the ExecuteResponse XML choke parsers
- _genOutputFormat is a utility method, which can be applied to any OGR geometry object
As you can see, very easy to pull off, integrates and extends easy. Kudos to the OGR and PyWPS teams!