Creating a service using Python
Using a Python CGI script to create a simple resource
So, first we need to define a resource as a physical URL. For this exercise, we will create a resource that delivers some spatial data, namely a POINT object in GeoJSON format:
Create an empty Python file called create_geojson.py
and insert the code in listing
1. Then save it in a sub-directory of your website named services
(you should have created this
directory in the earlier exercise Introduction to server-side
Python). Test it by pointing your browser to its URL https://gisedu.itc.utwente.nl/student/<yoursnum>/create_geosjon.py
...
1 2 3 4 5 6 7 8 9 |
#create a point in geojson format: gjStr = '{"type": "Point", "coordinates": [-10, 52]}' % (lon, lat) # use correct http header for json: print ('Content-type: application/json; charset=utf-8') print ('') # note the empty print line is required! #print the GeoJSON to the CGI output (response object): print(gjStr) |
In line 2, we create a string that contains the GeoJSON object of type Point
, with
the [lat,lon] coordinates [-10, 52]
. Because our script is running on the server, we have
to make sure the output is delivered to the CGI Response
object, which we can do by simply using
print()
. Notice that now in line 5 the content type is set to
application/json
(in earlier exercises we used text/html).
Note that the GeoJSON standard prescribes the order of coordinates to be[x,y]
, and therefore when using geographic coordinate systems (such as WGS84, which is the default for GeoJSON), the order is[lon, lat]
, NOT the more appropriate [lat, lon]...!
Adding parameters
Of course having a service always returning the exact same GeoJSON point is rather useless, we'd rather have it return a point with coordinates based on some input from the user. And of course that can be done!
You now should enhance your service to accept parameters: The latitude and longitude of the point
to be created can be included in parameters of the Request object, e.g.: ../create_geosjon_params.py?lat=52&lon=-10
.
Then your service should created a Point using those parameters.
A possible solution is in listing 2, but
do first try to figure it out yourself! Refer to the earlier exercises with the formreceiver.py
and try to apply those techniques to this case....
Make sure to create this service as a different physical URL (e.g. create_geojson_params.py
) than the one in Task 1,
because we will need that parameter-less one later...