Accessing POST Data from WSGI

2019-01-16 16:43发布

I can't seem to figure out how to access POST data using WSGI. I tried the example on the wsgi.org website and it didn't work. I'm using Python 3.0 right now. Please don't recommend a WSGI framework as that is not what I'm looking for.

I would like to figure out how to get it into a fieldstorage object.

5条回答
来,给爷笑一个
2楼-- · 2019-01-16 16:51

This worked for me (in Python 3.0):

import urllib.parse

post_input = urllib.parse.parse_qs(environ['wsgi.input'].readline().decode(),True)
查看更多
We Are One
3楼-- · 2019-01-16 16:51

I would suggest you look at how some frameworks do it for an example. (I am not recommending any single one, just using them as an example.)

Here is the code from Werkzeug:

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

which calls

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

It's a bit complicated to summarize here, so I won't.

查看更多
爷的心禁止访问
4楼-- · 2019-01-16 17:04

Even shorter

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

This code works in production.

查看更多
The star\"
5楼-- · 2019-01-16 17:05
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)

Note that WSGI is not yet fully-specified for Python 3.0, and much of the popular WSGI infrastructure has not been converted (or has been 2to3d, but not properly tested). (Even wsgiref.simple_server won't run.) You're in for a rough time doing WSGI on 3.0 today.

查看更多
迷人小祖宗
6楼-- · 2019-01-16 17:08

Assuming you are trying to get just the POST data into a FieldStorage object:

# 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
)
查看更多
登录 后发表回答