pythonwsgimod-pythonquery-string

How to access a query parameter ("$_GET") in mod_python?


I want to know how to show requests ($_GET) on a python script ?

Note that i am using mod_python as basic web server running with apache2 on UBUNTU server.

If you have any idea your help will be very appreciated :)

Other python web server like Django etc ... note needed in my case because i am running only one python script for a specific task :)


Solution

  • For a simple script to respond to a web request, I'd not use mod_python; you probably want to switch to mod_wsgi instead here.

    You'll have to parse the QUERY_STRING WSGI variable yourself; you can do so with the urlparse.parse_qs() function:

    from urlparse import parse_qs
    
    def application(environ, start_response):
        params = parse_qs(environ['QUERY_STRING'])
        foo = params.get('foo', [None])[0]
    

    parse_qs parses out the query string and sets the value in the resulting dictionary to a list per key, because keys can occur more than once in a query string.

    The above will pick out the first value in the list, or None if the key isn't present at all.

    If you are going to stick to plain-vanilla WSGI, read a decent tutorial to understand how it works. I strongly recommend you use a framework however; even just Werkzeug can make your life as a developer vastly simpler, even for a simple script.

    If you are going to stick with a mod_python request handler, replace environ['QUERY_STRING'] with request.args():

    from urlparse import parse_qs
    
    def requesthandler(req):
        params = parse_qs(req.args)
        foo = params.get('foo', [None])[0]