Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting HTTP status code in Bottle?

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"} 
like image 417
Foo Stack Avatar asked May 19 '13 18:05

Foo Stack


People also ask

How do you set a status code in HTTP response?

Methods to Set HTTP Status Code Sr.No. This method sets an arbitrary status code. The setStatus method takes an int (the status code) as an argument. If your response includes a special status code and a document, be sure to call setStatus before actually returning any of the content with the PrintWriter.

Can I use custom HTTP status codes?

Yes, as long as you respect the class -- that is, 2xx for success, 4xx for Client error, etc. So you can return custom 4XX error codes (preferably those that are unassigned) for your own application's error conditions.

How can I get status code from HTTP status?

To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response. status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error.

What is HTTP status code in API?

The status codes are divided into five categories. 1xx: Informational – Communicates transfer protocol-level information. 2xx: Success – Indicates that the client's request was accepted successfully. 3xx: Redirection – Indicates that the client must take some additional action in order to complete their request.


2 Answers

I believe you should be using response

from bottle import response; response.status = 300

like image 114
dm03514 Avatar answered Sep 28 '22 04:09

dm03514


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) 
like image 25
ron rothman Avatar answered Sep 28 '22 03:09

ron rothman