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

23

ボトルの組み込みの応答タイプは、ステータス コードを適切に処理します。次のようなものを検討してください。

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 に答える