仅接受Python中POST请求的参数

1 投票
2 回答
928 浏览
提问于 2025-04-16 20:29

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

2 个回答

0

根据文档,我觉得你可以这样做:

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

这段代码还没有经过测试。

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网页应用通常应该遵循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)

撰写回答