我似乎无法找出如何使用WSGI访问POST数据。我试过wsgi.org网站上的例子,它没有工作。我使用Python 3.0现在。请不要推荐WSGI框架,因为这是不是我要找的。

我想找出如何让它进入一个的FieldStorage对象。

有帮助吗?

解决方案

假设你正在试图让刚刚POST数据到的FieldStorage对象:

# env is the environment handed to you by the WSGI server.
# I am removing the query string from the env before passing it to the
# FieldStorage so we only have POST data in there.
post_env = env.copy()
post_env['QUERY_STRING'] = ''
post = cgi.FieldStorage(
    fp=env['wsgi.input'],
    environ=post_env,
    keep_blank_values=True
)

其他提示

body= ''  # b'' for consistency on Python 3.0
try:
    length= int(environ.get('CONTENT_LENGTH', '0'))
except ValueError:
    length= 0
if length!=0:
    body= environ['wsgi.input'].read(length)

请注意WSGI不是用于Python 3.0尚未完全指定的,并且许多流行WSGI基础设施的尚未转换(或已被2to3d,但不能正确测试)。 (即使wsgiref.simple_server将无法运行。)你有一个难熬的时间今天3.0做WSGI。

这个工作对我来说(在Python 3.0):

import urllib.parse

post_input = urllib.parse.parse_qs(environ['wsgi.input'].readline().decode(),True)

甚至更短的

l = int(env.get('CONTENT_LENGTH')) if env.get('CONTENT_LENGTH') else 0
body = env['wsgi.input'].read(l) if l > 0 else ''

这个代码在生产。

我建议你看一些框架是如何做到这一点的例子。 (我不建议任何单独一个,只是使用它们,例如,)

下面是从代码 WERKZEUG

http://dev.pocoo.org/projects /werkzeug/browser/werkzeug/wrappers.py#L150

它调用

http://dev.pocoo.org/projects /werkzeug/browser/werkzeug/utils.py#L1420

这是一个有点复杂在这里总结一下,所以我不会。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top