Skip to main content
 首页 » 编程设计

python之返回响应代码 python HTTP header

2025年05月04日15softidea

我有 python 服务器服务于 cgi 脚本,

我想在我的回复中添加状态代码。我做到了,

try: 
     cgi = CGI()      
     output = cgi.fire() 
     print 'Content-Type text/json' 
     print 'Status:200 success' 
     print 
     print json.dumps(output)      
 except: 
     print 'Content-Type: text/json' 
     print 'Status: 403 Forbidden' 
     print 
     print json.dumps({'msg':'error'}) 

但是当我通过 dojo xhr 请求请求此脚本时,我得到 200 请求状态。为什么会这样?

标题

Request URL:http://192.168.2.72:8080/cgi-bin/cgi.py 
Request Method:POST 
Status Code:200 Script output follows  
Request Headersview source 
Accept:*/* 
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 
Accept-Encoding:gzip,deflate,sdch 
Accept-Language:en-US,en;q=0.8 
Cache-Control:no-cache 
Connection:keep-alive 
Content-Length:125 
Content-Type:application/x-www-form-urlencoded 
Host:192.168.2.72:7999 
Origin:http://192.168.2.72:7999 
Pragma:no-cache 
Referer:http://192.168.2.72:7999/home.html 
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Ubuntu Chromium/25.0.1364.160 Chrome/25.0.1364.160 Safari/537.22 
X-Requested-With:XMLHttpRequest 
Form Dataview sourceview URL encoded     
Response Headersview source 
Content-Type:text/json 
Date:Fri, 08 Aug 2014 05:16:29 GMT 
Server:SimpleHTTP/0.6 Python/2.7.3 
Status:403 Forbidden  

有什么意见吗?

我已经尝试过的:

result.ioArgs.xhr.getAllResponseHeaders() // returns string 
ioargs.xhr.status // returns the request status. 

请您参考如下方法:

如果 json.dumps(output) 引发异常,您将已经打印了包含状态代码的 header (通常拼写为 Status: 200 OK)和结束 HTTP 响应 header 部分的空行。

然后,except block 将打印第二组 header ,但此时它们实际上被视为响应正文的一部分,因为打印一个空行结束了 header 。查看HTTP message规范。

解决方案是等到您知道您的输出将打印任何 header 。

-更多-

如果您向

json.dumps 提供不可序列化的输入,它可能会引发异常。鉴于 cgi.fire() 似乎是某些自定义 CGI 对象的方法(内置 cgi 模块没有该方法)它可能会返回任何东西。

要进行调试,您需要记录引发的异常,最好使用回溯。您拥有的裸except: block 将捕获所有错误,然后对它们不做任何处理,因此您不知道发生了什么,也不知道任何人在看这个问题。您可能还需要记录 output 的值。