Accessing POST Data from WSGI

后端 未结 5 655
萌比男神i
萌比男神i 2020-12-08 00:45

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\

相关标签:
5条回答
  • 2020-12-08 01:11

    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
    )
    
    0 讨论(0)
  • 2020-12-08 01:21

    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.

    0 讨论(0)
  • 2020-12-08 01:22
    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.

    0 讨论(0)
  • 2020-12-08 01:22

    This worked for me (in Python 3.0):

    import urllib.parse
    
    post_input = urllib.parse.parse_qs(environ['wsgi.input'].readline().decode(),True)
    
    0 讨论(0)
  • 2020-12-08 01:25

    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.

    0 讨论(0)
提交回复
热议问题