python - 返回响应代码 python HTTP header

标签 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'})

但是当我通过 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 的值。

关于python - 返回响应代码 python HTTP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25196721/

相关文章:

python - 使用正则表达式修改字符串

python - 正则表达式查找后面不跟某些字符的数字

Python 你为什么要使用 [ :] over =

python - 如何检索名称遵循模式的列的最大时间增量

python - 如何在discord.py中获取调用命令的人的姓名

python - 从 3 个列表中创建字典列表,其中每个列表数据都是字典中的关键

python - 将 pandas.DataFrame 索引保存到 txt 文件 (Python)

python - Docker-compose flask 应用程序不打印 'print' 的输出

python - 在格式化文本文件中查找一段文本

python - 如何使用 Class 装饰器包装器?