2008-12-26 88 views
15

这一定是一个非常简单的问题,但我似乎无法弄清楚。Python POST数据使用mod_wsgi

我使用apache + mod_wsgi来承载我的python应用程序,并且我希望获得以其中一种形式提交的发布内容 - 但是,既不是环境值,也不是sys.stdin包含任何这些数据。介意给我一个快速的手?

编辑: 尝试已:

  • ENVIRON [ “CONTENT_TYPE”] = '应用程序/ x WWW的形式进行了urlencoded'(无数据)
  • ENVIRON [ “wsgi.input”]似乎一个合理的方法,但是,environ [“wsgi.input”] .read()和environ [“wsgi.input”]。read(-1)返回一个空字符串(是的,内容已发布,并且environ [ “REQUEST_METHOD”] = “邮报”

回答

22

PEP 333说:you must read 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 
+0

我们赢了!谢谢:) – 2008-12-27 01:27:18

13

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

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