仅从python中的POST请求接受参数

时间:2011-06-28 21:12:39

标签: python post cgi

有没有办法只接受来自POST请求的参数? 如果我从cgi模块使用cgi.FieldStorage(),它接受来自GET和POST请求的参数。

2 个答案:

答案 0 :(得分:2)

默认情况下,cgi模块中的大多数内容合并os.environ['QUERY_STRING']sys.stdin(采用os.environ['CONTENT_TYPE']建议的格式)。因此,简单的解决方案是修改os.environ,或者更确切地说,提供一个没有查询字符串的替代方法。

# make a COPY of the environment
environ = dict(os.environ)
# remove the query string from it
del environ['QUERY_STRING']
# parse the environment
form = cgi.FieldStorage(environ=environ)
# form contains no arguments from the query string!

Ignacio Vazquez-Abrams建议完全避开cgi模块;现代python web应该通常应该遵循WSGI界面。这可能看起来像:

import webob
def application(environ, start_response):
    req = webob.Request(environ)
    if req.method == 'POST':
        # do something with req.POST

# still a CGI application:
if __name__ == '__main__':
    import wsgiref.handlers
    wsgiref.handlers.CGIHandler().run(application)

答案 1 :(得分:0)

从文档中,我认为您可以执行以下操作:

form = cgi.FieldStorage()
if isinstance(form["key"], cgi.FieldStorage):
     pass #handle field

此代码未经测试。