30

How do I set the HTTP status code of my response in Bottle?

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()))

As you can see, the output doesn't return the HTTP status code I set:

$ 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"}
ron rothman
  • 17,348
  • 7
  • 41
  • 43
Foo Stack
  • 2,185
  • 7
  • 24
  • 25
  • does `from bottle import response; response.status = 300` work? http://bottlepy.org/docs/dev/api.html#bottle.response – dm03514 May 19 '13 at 18:43

3 Answers3

42

I believe you should be using response

from bottle import response; response.status = 300

ron rothman
  • 17,348
  • 7
  • 41
  • 43
dm03514
  • 54,664
  • 18
  • 108
  • 145
26

Bottle's built-in response type handles status codes gracefully. Consider something like:

return bottle.HTTPResponse(status=300, body=theBody)

As in:

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)
ron rothman
  • 17,348
  • 7
  • 41
  • 43
  • dm03514's answer was what I was looking for. Gives me everything I was after, without requiring any changes to my code (apart from renamed from `Response` to `response`. – Foo Stack May 20 '13 at 05:16
0

raise can be use to get more power with HTTPResponse to show the status code (200,302,401):

Like you can simply do this way:

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)