4

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?

Community
  • 1
  • 1
Jamie
  • 7,075
  • 12
  • 56
  • 86

4 Answers4

7

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

  • Currently the link is broken. Thanks for explaining what 'self' in the example was referring too. – Jamie Jul 16 '13 at 00:30
6

Just like to add an alternate method to accessing the QUERY_STRING value if you're running a cgi script, you could just do the following:

import os
print "content-type: text/html\n" # so we can print to the webpage
print os.environ['QUERY_STRING']

My testing and understanding is that this also works when there aren't any query strings in the URL, you'd just get an empty string.

This is confirmed to be working on 2.7.6, view all environment variables like so:

#!/usr/bin/python

import os

print "Content-type: text/html\r\n\r\n";
print "<font size=+1>Environment</font><\br>";
for param in os.environ.keys():
    print "<b>%20s</b>: %s<\br>" % (param, os.environ[param])

This snippet of code was obtained from a TutorialsPoint tutorial on CGI Programming with Python.

Although, as zombie_raptor_jesus mentioned, it's probably better to use Python's CGI module, with FieldStorage to make things easier.

Again from the above tutorial:

# Import modules for CGI handling 
import cgi, cgitb 

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
first_name = form.getvalue('first_name')
last_name  = form.getvalue('last_name')

Will save values from the Query String first_name=Bobby&last_name=Ray

matrixanomaly
  • 6,627
  • 2
  • 35
  • 58
  • I ended up going the `cgi` route in the end as it also provides abstraction/insulation between the `GET` and `POST` form methods. – Jamie Oct 28 '15 at 18:42
  • @Jamie yep, just thought I'd document my findings here since I found this question too when working on CGI stuff! Totally saw it was a 2013 question haha – matrixanomaly Oct 29 '15 at 02:50
1

This is how I capture in Python 3 from CGI (A) URL, (B) GET parameters and (C) POST data:

I am using these methods on Windows Server running Python 3 using CGI via MIIS.

import sys, os, io

# CAPTURE URL

myDomainSelf = os.environ.get('SERVER_NAME')

myPathSelf = os.environ.get('PATH_INFO')

myURLSelf = myDomainSelf + myPathSelf


# CAPTURE GET DATA

myQuerySelf = os.environ.get('QUERY_STRING')

# CAPTURE POST DATA

myTotalBytesStr=(os.environ.get('HTTP_CONTENT_LENGTH'))

if (myTotalBytesStr == None):

    myJSONStr = '{"error": {"value": true, "message": "No (post) data received"}}'

else:

    myTotalBytes=int(os.environ.get('HTTP_CONTENT_LENGTH'))

    myPostDataRaw = io.open(sys.stdin.fileno(),"rb").read(myTotalBytes)

    myPostData = myPostDataRaw.decode("utf-8")


# Write RAW to FILE

mySpy = "myURLSelf: [" + str(myURLSelf) + "]\n"

mySpy = mySpy + "myQuerySelf: [" + str(myQuerySelf) + "]\n"

mySpy = mySpy + "myPostData: [" + str(myPostData) + "]\n"


# You need to define your own myPath here
myFilename = "spy.txt"

myFilePath = myPath + "\\" + myFilename

myFile = open(myFilePath, "w")

myFile.write(mySpy)

myFile.close()

=======================================================

Here are some other useful CGI environment vars:

AUTH_TYPE

CONTENT_LENGTH

CONTENT_TYPE

GATEWAY_INTERFACE

PATH_INFO

PATH_TRANSLATED

QUERY_STRING

REMOTE_ADDR

REMOTE_HOST

REMOTE_IDENT

REMOTE_USER

REQUEST_METHOD

SCRIPT_NAME

SERVER_NAME

SERVER_PORT

SERVER_PROTOCOL

SERVER_SOFTWARE

============================================

Hope this can help you.

Al-Noor Ladhani
  • 2,413
  • 1
  • 22
  • 14
0
import os
print('Content-Type: text/html\n\n<h1>Search query/h1>')
query_string = os.environ['QUERY_STRING']
SearchParams = [i.split('=') for i in query_string.split('&')] #parse query string
# SearchParams is an array of type [['key','value'],['key','value']]
# for example 'k1=val1&data=test' will transform to 
#[['k1','val1'],['data','test']]
for key, value in SearchParams:
    print('<b>' + key + '</b>: ' + value + '<br>\n')

with query_string = 'k1=val1&data=test' it will echo:

<h1>Search query</h1>
<b>k1</b>: val1<br>
<b>data</b>: test<br>

image output