Responses¶
Normal responses¶
Handler functions can return many types that will be interpreted by
make_response() and converted to a Response. Here are some
examples of accepted return values:
return body
return body, status_code
return body, headers
return body, status_code, headers
return Response(body, status_code, headers) # not recommended
In these examples, body can be anything described in the table below,
status_code is an int for the HTTP status code and headers is a
dict or a Headers.
Note
The app.default_headers will be added to
every response headers.
Note
The default status code is 200, except for EmptyResponse which
defaults to 204
Body |
Response class |
|---|---|
|
|
Anything else |
|
Error responses¶
HTTP Exceptions¶
If there are HTTP exceptions raised in your
handler, a Response will be made with make_error_response() and
will be sent like a normal response.
For example:
1 2 3 4 5 6 7 | from baguette.httpexceptions import NotFound
@app.route("/profile/{username}")
async def profile(username):
if username not in users: # lets assume users is a list of usernames
raise NotFound()
...
|
This will send a response with a Not Found body and a 404 status code.
See also
For a full list of available HTTP exceptions, see
httpexceptions.
Server errors¶
If you have a python error somewhere in your handler, Baguette will transform it
in a InternalServerError for you. The error
traceback will be included if app.debug is True.
1 2 3 4 5 | app = Baguette(debug=True)
@app.route("/error")
async def eror():
raise Exception
|
This will send a response with an Internal Server Error body along with the
error traceback and a 500 status code.