在Bottle中设置HTTP状态代码?

Foo*_*ack 21 python http http-headers bottle

如何在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()))
Run Code Online (Sandbox Code Playgroud)

如您所见,输出不会返回我设置的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"}
Run Code Online (Sandbox Code Playgroud)

dm0*_*514 35

我相信你应该使用 response

from bottle import response; response.status = 300


ron*_*man 18

Bottle的内置响应类型可以优雅地处理状态代码.考虑类似的事情:

return bottle.HTTPResponse(status=300, body=theBody)
Run Code Online (Sandbox Code Playgroud)

如:

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)
Run Code Online (Sandbox Code Playgroud)