Papyrus provides a GeoJSON renderer, based on Sean Gillies' geojson package.
To use it the GeoJSON renderer factory must be added to the application configuration.
For that you can either pass the factory to the Configurator
constructor:
from pyramid.mako_templating import renderer_factory as mako_renderer_factory
from papyrus.renderers import GeoJSON
config = Configurator(
renderers=(('.mako', mako_renderer_factory),
('geojson', GeoJSON()))
)
Or you can apply the add_renderer method to the Configurator instance:
from papyrus.renderers import GeoJSON
config.add_renderer('geojson', GeoJSON())
Make sure that add_renderer is called before any add_view call that
names geojson as an argument.
To use the GeoJSON renderer in a view set renderer to geojson in the
view config. Here is a simple example:
@view_config(renderer='geojson')
def hello_world(request):
return {
'type': 'Feature',
'id': 1,
'geometry': {'type': 'Point', 'coordinates': [53, -4]},
'properties': {'title': 'Dict 1'},
}
Views configured with the geojson renderer must return objects that
implement the Python Geo Interface.
Here's another example where the returned object is an SQLAlchemy (or GeoAlchemy) mapped object:
@view_config(renderer='geojson')
def features(request):
return Session().query(Spot).all()
In the above example the Spot objects returned by the query call must
implement the Python Geo Interface.
Notes:
The GeoJSON renderer supports JSONP. The renderer indeed checks if there's a
callbackparameter in the query string, and if there's one it wraps the response in a JavaScript call and sets the response content type totext/javascript.The application developer can also specify the name of the JSONP callback parameter, using this:
from papyrus.renderers import GeoJSON config.add_renderer('geojson', GeoJSON(jsonp_param_name='cb'))With this, if there's a parameter named
cbin the query string, the renderer will return a JSONP response.By default, lists and tuples passed to the renderer will be rendered as FeatureCollection. You can change this using the
collection_typeargument:from papyrus.renderers import GeoJSON config.add_renderer('geojson', GeoJSON(collection_type='GeometryCollection'))
.. autoclass:: papyrus.renderers.GeoJSON