Can parse GET params from URL

90 views Asked by At

I have file test.py:

import cgi, cgitb                                      # Import modules for CGI handling    

form = cgi.FieldStorage() 
person_name = form.getvalue('person_name')


print ("Content-type:text/html\n\n")
print ("<html>")
print ("<head>")
print ("</head>")
print ("<body>")
print (" hello world <br/>")
print(person_name)
print ("</body>")
print ("</html>")

When I go to www.myexample.com/test.py?person_name=john, the result I get is:

hello world

None

meaning that I could not get the param "person_name" from the url.

p.s. It works perfect in my localhost server, but when upload it to online webserver, somewhy cant parse the param from url.

How can I fix it?

1

There are 1 answers

6
Rohit Barnwal On BEST ANSWER

Use this then

form_arguments = cgi.FieldStorage(environ={'REQUEST_METHOD':'GET', 'QUERY_STRING':qs})

for i in form_arguments.keys():
    print form_arguments[i].value

In my previous answer I assumed you have webapp2. I think this will solve your purpose.

Alternatively you can try:

import urlparse
url = 'www.myexample.com/test.py?person_name=john'
par = urlparse.parse_qs(urlparse.urlparse(url).query)

person_name= par['person_name']

And to get the current url, use this:

url = os.environ['HTTP_HOST']
uri = os.environ['REQUEST_URI']
url = url + uri
par = urlparse.parse_qs( urlparse.urlparse(url).query )