我找到了我的(愚蠢)问题的解决方案并将其列在下面。
我在 Ubuntu 11.04 上使用 Python 2.7.1+。客户端/服务器位于同一台计算机上。
从 Wing 调试器中,我知道正在调用服务器代码,并且我可以一次一行地浏览代码。在本例中,我知道传输了 22 个字节。
在 Firebug 中,我在 Net Post 选项卡下看到了此数据:
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)
最佳答案
您正在执行 POST
查询,因此 QUERY_STRING
确实为空,因为它表示 GET
请求的查询字符串(它也可能出现在其他请求类型中,但与当前的问题无关)。您应该通过使用 wsgi.input
流来解析 POST
数据。
关于python - 为什么 environ ['QUERY_STRING' ] 返回零长度字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7568381/