如何在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"}
答案 0 :(得分:32)
我相信你应该使用response
from bottle import response; response.status = 300
答案 1 :(得分:13)
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)
答案 2 :(得分:0)
就像你可以这样做:
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)