使用mod_wsgi的Python POST数据

Sil*_*gon 15 python mod-wsgi

这一定是一个非常简单的问题,但我似乎无法弄明白.

我正在使用apache + mod_wsgi来托管我的python应用程序,并且我希望以其中一个表单提交帖子内容 - 但是,环境值和sys.stdin都不包含任何此类数据.介意给我一个快速的手?

编辑:已经尝试过:

  • environ ["CONTENT_TYPE"] ='application/x-www-form-urlencoded'(无数据)
  • 然而,environ ["wsgi.input"]似乎是合理的方式,environ ["wsgi.input"].read()和environ ["wsgi.input"].read(-1)返回一个空字符串(是的) ,内容已发布,environ ["request_method"] ="发布"

nos*_*klo 22

PEP 333你必须阅读environ ['wsgi.input'].

我刚刚保存了以下代码并使apache的mod_wsgi运行它.有用.

你一定做错了.

from pprint import pformat

def application(environ, start_response):
    # show the environment:
    output = ['<pre>']
    output.append(pformat(environ))
    output.append('</pre>')

    #create a simple form:
    output.append('<form method="post">')
    output.append('<input type="text" name="test">')
    output.append('<input type="submit">')
    output.append('</form>')

    if environ['REQUEST_METHOD'] == 'POST':
        # show form data as received by POST:
        output.append('<h1>FORM DATA</h1>')
        output.append(pformat(environ['wsgi.input'].read()))

    # send results
    output_len = sum(len(line) for line in output)
    start_response('200 OK', [('Content-type', 'text/html'),
                              ('Content-Length', str(output_len))])
    return output
Run Code Online (Sandbox Code Playgroud)

  • 这对我来说是封锁的.这是通过读取确切的字节数来解决的:`length = int(environ.get('CONTENT_LENGTH','0'))`和`... read(length)`.这与链接的文档确实*不*提及`read()`(无长度)必须得到支持这一事实是一致的. (2认同)

Gra*_*ton 13

请注意,从技术上讲,在wsgi.input上调用read()或read(-1)是违反WSGI规范的,即使Apache/mod_wsgi允许它.这是因为WSGI规范要求提供有效的长度参数.WSGI规范还说您不应该读取比CONTENT_LENGTH指定的数据更多的数据.

因此,上面的代码可以在Apache/mod_wsgi中工作,但它不是可移植的WSGI代码,并且在其他一些WSGI实现上会失败.为了正确,确定请求内容长度并将该值提供给read().