Saturday 29 June 2019

python - Sending long JSON objects (polygon geometry, table rows) in POST request to Geoprocessing Service?


I am seeking to understand my options for sending long JSON objects in a request to a Geoprocessing Service.


In particular, I am looking for some example code to illustrate how to include two long JSON objects (one a polygon geometry as a coordinate string, the other a table as rows of ASCII text with the first row being the column headings) into a POST request to my Geoprocessing Service, and then hints as to how best to read them as parameters in the Python script that I've published as my Geoprocessing Service.


At http://help.arcgis.com/en/arcgisserver/10.0/apis/rest/gettingstarted.html it says:



When using the REST API, you will normally use an HTML GET method in a form. When you use GET, the entire request is encoded in the URL. This is the preferred method to use whenever possible. However, in this mode, a URL is limited to as few as 1024 characters depending on the browser. Thus, if you have a long JSON object to include in the request, you will need to use POST.


A second option, when using certain Geometry Service and Geoprocessing Service operations, is to continue to use GET and to specify a URL to the input JSON object contained in a file on a public server.



I'm familiar with using a GET method when the parameters can all fit into a URL that I can paste into a browser.



I'm also comfortable with the idea of using GET to specify a URL to input JSON objects that are contained in files on a public server. However, I am prevented from using this method this because my client does not want files placed on a public server.


That leaves me with having two long JSON objects to include in the request and having to use POST which is a method beyond my current level of understanding.


Is any example code readily available?



Answer



It's fairly easy with urllib2. Say you've got a gigantic url like this:


http://myserver/path/to/a/thing?json1={"data":[1,2,3,4,5]}&json2={"data":[1,2,3,4,5]}&json3={"data":[1,2,3,4,5]}


All you need to do is take the query (everything after the ?) and jam it in the data argument to urlopen.


import urllib2
import urlparse


# GET
return_data = urllib2.urlopen(url).read()

# POST
url_parts = urlparse.urlsplit(url)
base_url = urlparse.urlunsplit(url_parts[:3] + (None, None))
return_data = urllib2.urlopen(base_url, url_parts.query).read()

Then there's Requests, which is not in the standard library but it is really, really nice and intuitive to use.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...