如何在Python中处理POST和GET变量?

问题:如何在Python中处理POST和GET变量?

在PHP中,您只能将其$_POST用于POST和$_GETGET(查询字符串)变量。Python中的等效功能是什么?

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


回答 0

假设您正在发布带有以下内容的html表单:

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

如果使用原始cgi

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

如果使用DjangoPylonsFlaskPyramid

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

使用TurbogearsCherrypy

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

Web.py

form = web.input()
print form.username

Werkzeug

print request.form['username']

如果使用Cherrypy或Turbogears,还可以直接使用参数定义处理程序函数:

def index(self, username):
    print username

Google App Engine

class SomeHandler(webapp2.RequestHandler):
    def post(self):
        name = self.request.get('username') # this will get the value from the field named username
        self.response.write(name) # this will write on the document

因此,您实际上必须选择这些框架之一。

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, Pylons, Flask or Pyramid:

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

Google App Engine:

class SomeHandler(webapp2.RequestHandler):
    def post(self):
        name = self.request.get('username') # this will get the value from the field named username
        self.response.write(name) # this will write on the document

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


回答 1

我知道这是一个老问题。然而令人惊讶的是,没有给出好的答案。

首先,这个问题是完全有效的,而无需提及框架。CONTEXT是PHP语言的等效项。尽管有很多方法可以在Python中获取查询字符串参数,但是可以方便地填充框架变量。在PHP中,$_GET并且$_POST也方便变量。它们分别从QUERY_URI和php:// input解析。

在Python中,这些函数将是os.getenv('QUERY_STRING')sys.stdin.read()。记住要导入os和sys模块。

我们在这里必须小心使用“ CGI”一词,尤其是在谈论两种语言及其与Web服务器接口时的通用性时。1. CGI作为协议,定义了HTTP协议中的数据传输机制。2.可以将Python配置为在Apache中作为CGI脚本运行。3. Python中的CGI模块提供了一些便利功能。

由于HTTP协议与语言无关,并且Apache的CGI扩展也与语言无关,因此获取GET和POST参数仅应具有跨语言的语法差异。

这是填充GET字典的Python例程:

GET={}
args=os.getenv("QUERY_STRING").split('&')

for arg in args: 
    t=arg.split('=')
    if len(t)>1: k,v=arg.split('='); GET[k]=v

对于POST:

POST={}
args=sys.stdin.read().split('&')

for arg in args: 
    t=arg.split('=')
    if len(t)>1: k, v=arg.split('='); POST[k]=v

您现在可以按以下方式访问字段:

print GET.get('user_id')
print POST.get('user_name')

我还必须指出,CGI模块不能很好地工作。考虑以下HTTP请求:

POST / test.py?user_id=6

user_name=Bob&age=30

使用CGI.FieldStorage().getvalue('user_id')将导致空指针异常,因为该模块盲目检查POST数据,而忽略了POST请求也可以携带GET参数的事实。

I know this is an old question. Yet it’s surprising that no good answer was given.

First of all the question is completely valid without mentioning the framework. The CONTEXT is a PHP language equivalence. Although there are many ways to get the query string parameters in Python, the framework variables are just conveniently populated. In PHP, $_GET and $_POST are also convenience variables. They are parsed from QUERY_URI and php://input respectively.

In Python, these functions would be os.getenv('QUERY_STRING') and sys.stdin.read(). Remember to import os and sys modules.

We have to be careful with the word “CGI” here, especially when talking about two languages and their commonalities when interfacing with a web server. 1. CGI, as a protocol, defines the data transport mechanism in the HTTP protocol. 2. Python can be configured to run as a CGI-script in Apache. 3. The CGI module in Python offers some convenience functions.

Since the HTTP protocol is language-independent, and that Apache’s CGI extension is also language-independent, getting the GET and POST parameters should bear only syntax differences across languages.

Here’s the Python routine to populate a GET dictionary:

GET={}
args=os.getenv("QUERY_STRING").split('&')

for arg in args: 
    t=arg.split('=')
    if len(t)>1: k,v=arg.split('='); GET[k]=v

and for POST:

POST={}
args=sys.stdin.read().split('&')

for arg in args: 
    t=arg.split('=')
    if len(t)>1: k, v=arg.split('='); POST[k]=v

You can now access the fields as following:

print GET.get('user_id')
print POST.get('user_name')

I must also point out that the CGI module doesn’t work well. Consider this HTTP request:

POST / test.py?user_id=6

user_name=Bob&age=30

Using CGI.FieldStorage().getvalue('user_id') will cause a null pointer exception because the module blindly checks the POST data, ignoring the fact that a POST request can carry GET parameters too.


回答 2

我发现nosklo的答案非常广泛且有用!对于像我这样的人,他们可能会发现直接访问原始请求数据也很有用,我想添加一种方法:

import os, sys

# the query string, which contains the raw GET data
# (For example, for http://example.com/myscript.py?a=b&c=d&e
# this is "a=b&c=d&e")
os.getenv("QUERY_STRING")

# the raw POST data
sys.stdin.read()

I’ve found nosklo’s answer very extensive and useful! For those, like myself, who might find accessing the raw request data directly also useful, I would like to add the way to do that:

import os, sys

# the query string, which contains the raw GET data
# (For example, for http://example.com/myscript.py?a=b&c=d&e
# this is "a=b&c=d&e")
os.getenv("QUERY_STRING")

# the raw POST data
sys.stdin.read()

回答 3

它们存储在CGI fieldtorage对象中。

import cgi
form = cgi.FieldStorage()

print "The user entered %s" % form.getvalue("uservalue")

They are stored in the CGI fieldstorage object.

import cgi
form = cgi.FieldStorage()

print "The user entered %s" % form.getvalue("uservalue")

回答 4

它在某种程度上取决于您用作CGI框架的方式,但是在程序可访问的字典中可以找到它们。我会向您指出这些文档,但现在还没有到达python.org。但是mail.python.org上的此注释将为您提供第一个指针。查看CGI和URLLIB Python库以获取更多信息。

更新资料

好的,该链接无效。这是基本的wsgi参考

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.

Update

Okay, that link busted. Here’s the basic wsgi ref


回答 5

Python仅是一种语言,要获取GET和POST数据,您需要使用Python编写的Web框架或工具包。查理指出,Django是一个,cgi和urllib标准模块是另一个。也可以使用Turbogears,Pylons,CherryPy,web.py,mod_python,fastcgi等。

在Django中,您的视图函数会接收一个带有request.GET和request.POST的请求参数。其他框架将采取不同的方式。

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.