tags:

views:

4468

answers:

4

In PHP you can just use $_POST for POST and $_GET for GET (Query string) variables. What's the equivalent in Python?

+1  A: 

It somewhat depends on what you use as a CGI framework, but they are available in dictionaries accessible to the program. I'd point you to the docs, but I'm not getting through to python.org right now. But this note on mail.python.org will give you a first pointer. Look at the CGI and URLLIB Python libs for more.

Charlie Martin
If you're not ambitious enough to follow a link, I'm not ambitious enough to cut and paste if from the link.
Charlie Martin
+1  A: 

Python is only a language, to get GET and POST data, you need a web framework or toolkit written in Python. Django is one, as Charlie points out, the cgi and urllib standard modules are others. Also available are Turbogears, Pylons, CherryPy, web.py, mod_python, fastcgi, etc, etc.

In Django, your view functions receive a request argument which has request.GET and request.POST. Other frameworks will do it differently.

Ned Batchelder
+2  A: 

They are stored in the CGI fieldstorage object.

import cgi
form = cgi.FieldStorage()

print "The user entered %s" % form.getvalue("uservalue")
Evan Fosmark
-1. there are quite a few representation of the request object, depending on the libs/framework used.
bruno desthuilliers
I'm not sure why you did -1. I mean, what I gave works. Perhaps he is unable to use a framework. ALso, don't most frameworks just use this in the background?
Evan Fosmark
+19  A: 

suppose you're posting a html form with this:

<input type="text" name="username">

If using raw cgi:

import cgi
form = cgi.FieldStorage()
print form["username"]

If using Django or Pylons:

print request.GET['username'] # for GET form method
print request.POST['username'] # for POST form method

Using Turbogears, Cherrypy:

from cherrypy import request
print request.params['username']

Web.py:

form = web.input()
print form.username

Werkzeug:

print request.form['username']

If using Cherrypy or Turbogears, you can also define your handler function taking a parameter directly:

def index(self, username):
    print username

So you really will have to choose one of those frameworks.

nosklo