Search code examples
python-2.7apache2cgi

How do I access the URL's Query String in a Python CGI script?


I'm trying to access the query string in a python script: in bash I'd access it using the ${QUERY_STRING} environment variable.

I've come across things like this:https://stackoverflow.com/a/2764822/32836, but this script, as run by Apache2:

#!/usr/bin/python

print self.request.query_string

prints nothing, and at the command line, the same produces this error:

$ ./testing.py
Traceback (most recent call last):
  File "./testing.py", line 3, in <module>
    print self.request.query_string
NameError: name 'self' is not defined

How do I read the query_string?


Solution

  • First of all, the 'self' keyword is only available once defined in a function, typically an object's. It is normally used the same way 'this' is used in other OOP languages.

    Now, the snippet of code you were trying to use was intended for the Google App Engine, which you have not imported (nor installed, I presume). Since you are accustomed to using environment variables, here's what you can do:

    #!/usr/bin/python
    import os
    
    print os.environ.get("QUERY_STRING", "No Query String in url")
    

    However, I would advise you to use the cgi module instead. Read more about it here: http://docs.python.org/2/library/cgi.html