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?

1

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Currently the link is broken. Thanks for explaining what 'self' in the example was referring too.
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

2 Comments

I ended up going the cgi route in the end as it also provides abstraction/insulation between the GET and POST form methods.
@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
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.

Comments

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

1 Comment

Please edit your question to support/explain your code.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.