返回响应代码python HTTP标头

Dip*_*ole 1 python

我有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'})
Run Code Online (Sandbox Code Playgroud)

但是当我通过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 
Run Code Online (Sandbox Code Playgroud)

有什么投入?

我已经尝试过的:

result.ioArgs.xhr.getAllResponseHeaders() // returns string
ioargs.xhr.status // returns the request status.
Run Code Online (Sandbox Code Playgroud)

Jas*_*n S 6

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

然后,该except块将打印第二组标题,但那些实际上被认为是该点响应主体的一部分,因为打印空行结束了标题.请参阅HTTP消息规范.

解决方案是等到你知道打印任何标题的输出是什么.

-更多-

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

要进行调试,您需要记录引发的异常,最好使用回溯.except:你拥有的裸露块会捕获所有错误,然后对它们不做任何事情,所以你不知道发生了什么,也没有人看到这个问题.您可能还需要记录值output.