3

Client-side code submits an object (in the POST request body) or query string (if using GET method) via ajax request to a python cgi script. Please note that the object/query string parameters are not coming from a

<form> or <isindex>.

How can I retrieve these parameters from within the server-side python script using standard library modules (e.g., cgi)?

Thanks very much

EDIT:
@codeape: Thanks, but wouldn't that work only for submitted forms? In my case, no form is being submitted, just an asynchronous request.
Using your script, len(f.keys()) returns 0 if no form is submitted! I can probably recast the request as a form submission, but is there a better way?

3 Answers 3

5

You use the cgi.FieldStorage class. Example CGI script:

#! /usr/bin/python

import cgi
from os import environ
import cgitb
cgitb.enable()

print "Content-type: text/plain"
print
print "REQUEST_METHOD:", environ["REQUEST_METHOD"]
print "Values:"
f = cgi.FieldStorage()
for k in f.keys():
    print "%s: %s" % (k, f.getfirst(k))
Sign up to request clarification or add additional context in comments.

Comments

0

codeape already answered on this. Just for the record, please understand that how the HTTP request is emitted is totally orthogonal - what the server get is an HTTP request, period.

Comments

0

@codeape , @bruno desthuilliers:

Indeed, cgi.FieldStorage() retrieves the parameters. The output I was getting earlier was apparently due to my passing the parameters as a string (JSON.stringify() object) in the body of the request -- rather than as key-value pairs.
Thanks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.