在 Bottle 中设置 HTTP 状态码?
Posted
技术标签:
【中文标题】在 Bottle 中设置 HTTP 状态码?【英文标题】:Setting HTTP status code in Bottle? 【发布时间】:2013-05-14 08:06:45 【问题描述】:如何在 Bottle 中设置响应的 HTTP 状态码?
from bottle import app, run, route, Response
@route('/')
def f():
Response.status = 300 # also tried `Response.status_code = 300`
return dict(hello='world')
'''StripPathMiddleware defined:
http://bottlepy.org/docs/dev/recipes.html#ignore-trailing-slashes
'''
run(host='localhost', app=StripPathMiddleware(app()))
如你所见,输出没有返回我设置的 HTTP 状态码:
$ curl localhost:8080 -i
HTTP/1.0 200 OK
Date: Sun, 19 May 2013 18:28:12 GMT
Server: WSGIServer/0.1 Python/2.7.4
Content-Length: 18
Content-Type: application/json
"hello": "world"
【问题讨论】:
from bottle import response; response.status = 300
有效吗? bottlepy.org/docs/dev/api.html#bottle.response
是的,成功了。谢谢:)
【参考方案1】:
我相信你应该使用response
from bottle import response; response.status = 300
【讨论】:
【参考方案2】:Bottle 的内置响应类型可以优雅地处理状态代码。考虑类似的事情:
return bottle.HTTPResponse(status=300, body=theBody)
如:
import json
from bottle import HTTPResponse
@route('/')
def f():
theBody = json.dumps('hello': 'world') # you seem to want a JSON response
return bottle.HTTPResponse(status=300, body=theBody)
【讨论】:
dm03514 的答案正是我想要的。提供我所追求的一切,无需对我的代码进行任何更改(除了从Response
重命名为 response
。【参考方案3】:
raise 可用于通过 HTTPResponse 获得更多功能以显示状态代码 (200,302,401):
就像你可以简单地这样做:
import json
from bottle import HTTPResponse
response=
headers = 'Content-type': 'application/json'
response['status'] ="Success"
response['message']="Hello World."
result = json.dumps(response,headers)
raise HTTPResponse(result,status=200,headers=headers)
【讨论】:
以上是关于在 Bottle 中设置 HTTP 状态码?的主要内容,如果未能解决你的问题,请参考以下文章