2008-12-26 81 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實現上失敗。要正確,請確定請求內容的長度並提供該值以讀取()。