Python - GET and POST?

bazzie

New Member
Messages
2
Reaction score
0
Points
0
Yes, I'm someone who actually got python working :p

So, how do I get data via GET or POST? The latter is not absolutely necessary but would be nice to know too. I've only sys.argv so far, but that only returns the filename.

Thanks in advance.
 

descalzo

Grim Squeaker
Community Support
Messages
9,373
Reaction score
326
Points
83
Code:
#!/usr/bin/env python
import os
import sys


print("Content-type: text/html")
print("")

print("<html>")
print("<body>")

print( "GET / POST Information")
print("<pre>")

print "Request method: " , os.environ[ 'REQUEST_METHOD' ]
print "Query string: " ,  os.environ[ 'QUERY_STRING' ]
count = 0 
for line in sys.stdin:
    count = count + 1
    print line
    if count > 100:
        break
print ""

print("</pre>")
print("</body>")
print("</html>")

This will dump the information.
QUERY_STRING is mostly for GET (a POST can have a query string too)
sys.stdin gives you the data from the POST
You then have to parse the info, splitting first on '&' to separate the fields, then on '=' to make key-value pairs.
Then you would have to un-urlencode them too.
That is the low-level way to do it. I would assume there is a CGI module that would be easier to use.
 
Last edited:

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
That is the low-level way to do it. I would assume there is a CGI module that would be easier to use.
Indeed there is.
Code:
#!/usr/bin/env python

import cgi, cgitb
cgitb.enable()

print "Content-type: text/html"
print
print '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">'
print '<html><head><title>Python CGI</title></head><body>'

form = cgi.FieldStorage()

print '<h3>Headers</h3><dl>'
for header in form.headers:
    print '<dt>%s</dt><dd>%s</dd>' % (header, form.headers[header])
print '</dl>'

print '<h3>Input</h3><dl>'
for name in form:
    print '<dt>%s</dt><dd>%s</dd>' % (name, form.getvalue(name))
    # or:
    #print '<dt>%s</dt><dd>%s</dd>' % (name, form[name].value)
print '</dl>'

cgi.print_form(form)

print '</body></html>'
 
Last edited:
Top