2011-09-27 45 views
1

我找到了我的(啞)問題的解決方案,並列在下面。爲什麼environ ['QUERY_STRING']返回零長度字符串?

我在Ubuntu 11.04上使用Python 2.7.1+。客戶機/服務器位於同一臺計算機上。

從Wing調試器,我知道服務器代碼被調用,我可以一次一行地通過代碼行。在這種情況下,我知道傳輸了22個字節。

在Firebug中,我看到網帖標籤下這樣的數據:

Parameter application/x-www-form-urlencoded 
fname first 
lname last 
Source 
Content-Type: application/x-www-form-urlencoded 
Content-Length: 22 fname=first&lname=last 

這是我使用的客戶端代碼:

<html> 
    <form action="addGraphNotes.wsgi" method="post"> 
     First name: <input type="text" name="fname" /><br /> 
     Last name: <input type="text" name="lname" /><br /> 
     <input type="submit" value="Submit" /> 
    </form> 
</html> 

這是服務器代碼:

import urlparse 

def application(environ, start_response): 
    output = [] 

    # the environment variable CONTENT_LENGTH may be empty or missing 
    try: 
    # NOTE: THIS WORKS. I get a value > 0 and the size appears correct (22 bytes in this case) 
     request_body_size = int(environ.get('CONTENT_LENGTH', 0)) 
    except (ValueError): 
     request_body_size = 0 

    try: 
     # environ['QUERY_STRING'] returns "" 
     **values = urlparse.parse_qs(environ['QUERY_STRING'])** 
    except: 
     output = ["parse error"] 

在Wing調試器中,我已驗證數據正在從客戶端傳遞到服務器:

>>> environ['wsgi.input'].read() 
'fname=first&lname=last' 

找到了我的問題。我複製並在錯誤的代碼中進行了處理。這是我用於表單的代碼,但是當我開始使用AJAX並停止使用表單時停止添加它。現在,一切工作正常。

# When the method is POST the query string will be sent 
# in the HTTP request body which is passed by the WSGI server 
# in the file like wsgi.input environment variable. 
request_body = environ['wsgi.input'].read(request_body_size) 

values = parse_qs(request_body) 
+0

您是否嘗試過打印出整個'environ'字典? –

+0

有關更多詳細信息,請參閱編輯的問題。 – Jarek

回答

3

你正在做一個POST查詢,以便將QUERY_STRING確實將是空的,因爲它代表了GET請求的查詢字符串(它也可以出現在其他請求類型,但它無關的問題在手)。您應該通過使用wsgi.input流解析POST數據。

+0

我嘗試'得到'但沒有改變任何東西。我之前編寫的所有其他表單/提交代碼都使用「發佈」,代碼運行良好。這臺機器上似乎有些「破損」,我無法弄清楚它是什麼。 – Jarek

+0

我一直在我的表單中使用帖子一直提交,一切正常。直到我開始使用這臺電腦。 – Jarek

相關問題