29

如何在 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"}
4

3 回答 3

43

我相信你应该使用response

from bottle import response; response.status = 300

于 2013-05-19T18:53:44.670 回答
23

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)
于 2013-05-20T01:59:50.690 回答
0

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)
于 2017-02-23T06:39:58.333 回答