Posted by: dresstosurvive | August 20, 2007

Retrieving GET and POST Variables with Mod_python

Painlessly retrieve information from forms and queries.

If you’re frustrated trying to retrieve the GET and POST variables you’re used to with PHP or some other language, check out get_env.

An important thing to note is that a POST variable of the same name as a GET variable in a request will overwrite the GET value.

Under the hood, get_env uses a few tricks to maximize performance. First, it tries to use the version of parse_qsl provided by Mod_python instead of the standard one provided by cgi as it is much faster. Next, the GET values are retrieved, but not automatically parsed. If the method was not POST, get_env does not attempt to find any POST variables. If it was, the values are appended to the query string containing any possible GET values. Finally, the query string is parsed and transformed into a dictionary using the standard dictionary constructor. You might consider another option, but this is the fastest in this case.

options = {"content_type": "text/plain"}

from mod_python import apache
try:
    from mod_python.util import parse_qsl
except ImportError:
    from cgi import parse_qsl

def get_env(req):
    #   grab GET variables
    req.add_common_vars()
    req.content_type    = options['content_type']
    query               = req.subprocess_env['QUERY_STRING']

    #   grab POST variables
    if req.subprocess_env['REQUEST_METHOD'] == ‘POST’:
        query += ‘&’ + req.read()

    #   break down the urlencoded query string
    query       = parse_qsl(query)
    http_var    = dict(query)

    return http_var

def handler(req):
    http_env = get_env(req)

    #   lookie ma, we got an environment!
    for key, value in http_env.items():
        req.write(”%s: %s\n” % (key, value))

    return apache.OK

Responses

What’s wrong with mod_python.util.FieldStorage class?

Your method will only work for POST of content type ‘application/x-www-form-urlencoded’ where as the FieldStorage class properly handles other POST content types for submitting forms.

See ‘http://www.modpython.org/live/current/doc-html/pyapi-util-fstor.html’.

Leave a response

Your response:

Categories