2011-09-27 109 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

相关问题