Errors and redirects
A handler can stop a request at any point with an HTTP status, and Cylinder turns that into a response. What the response says is decided by files in the tree, in the same way pages are: an error handler for the whole site, with more specific ones for the sections that need them.
abort()
Ask for the abort parameter and call it with a status code:
def main(request, response, abort):
if "id" not in request.args:
abort(400)
response.data = "ok"
return response
abort() is the one that Cylinder passes in: Werkzeug’s
Aborter, with the
redirects and any custom status codes added. It raises an HTTP
exception, so nothing after it in the handler runs. It works the same way in hooks. Code outside a handler
that needs it is passed it: werkzeug.exceptions.abort() knows neither the redirects nor the codes that
you add, and raises a LookupError for them.
Without an error handler file, the client receives Werkzeug’s default page for that status:
<!doctype html>
<html lang=en>
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>
A second argument replaces the description, for any error status:
abort(400, "The id parameter is required")
Anything else that Werkzeug’s class for the status takes is passed by name, such as the methods that the
Allow header of a 405 lists: abort(405, "Only POST here", valid_methods=["POST"]).
What survives an abort
When a request is aborted, the error response takes the place of the one the handler was building. The status and body come from the error. The headers and cookies that hooks and handlers had already set are kept:
Set before |
On the error response |
|---|---|
Headers such as |
Kept |
Cookies |
Kept |
The body, and the status code |
Replaced by the error’s |
|
Replaced by the error’s |
A header the error sets itself, such as |
The error’s value is used |
Any other header that says something about the body |
Dropped |
The same applies to redirects and to uncaught exceptions. So a security header set in an early hook is
still present on a 404, and a session cookie set before a redirect to a login page still reaches the
browser.
These are the headers that are not kept. Each says something about the body that was thrown away, or what to do with it:
Content-Type,Content-Length,Content-Encoding,Content-Language,Content-Location,Content-Range,Content-MD5,Allow,Expires, andLast-ModifiedETagandAccept-Ranges, so that a browser does not store the error page as a copy of a fileLocation, which belongs to the redirect or the201 Createdthat it was set forContent-Disposition, so that a browser does not save the error page as a download, under the name of the fileContent-Digest,Repr-Digest, andDigest, which a client checks the body againstX-Accel-RedirectandX-Sendfile, which tell a proxy to send a file in place of the body. On an error, that would be the file that was just refused.
Every other header is kept. A header that is set in an error handler file is set on the error itself, so all of these can be set there.
One consequence to keep in mind: a header that only makes sense for a successful response, such as
Cache-Control: public, is kept too if it was set before the abort. Set headers like that after the last
point where the handler might abort.
Ending a request with the response itself
abort() can be given the response in place of a status. It stops the request as any abort does, and the
response is sent as it is. Nothing takes its place, so its status, its headers, and its body are what was
set on it:
def main(response, abort):
response.status_code = 409
response.data = "That name is taken"
abort(response)
Use it where code has to answer a request and cannot do so by returning. An early hook returns to let the
request go on, so a hook that answers a request itself
ends it this way. It is also the way to stop with a status that is not an error. abort(204) cannot do
that: Werkzeug has no exception for a status that is not an error, so that call is a 500.
Everything else is as it is for any abort, but for one thing. The early hooks below and the page handler do
not run, and the late hooks do. No error handler file runs, whatever the status of
the response: an error handler builds the response for an error, and this one is built already. The
exception that a late hook is given as e has no status of its own, so e.code is None: read the status
from response.status_code.
Error handler files
To control the response for a status code, create a file named after it:
my_webapps
|-- webapp1.400.py
|-- webapp1.404.py
|-- webapp1.page.get.py
|-- /webapp1
|-- /foo
|-- bar.page.get.py
webapp1.404.py now builds every 404 response on the site, and webapp1.400.py every 400. That
includes the 404 Cylinder raises itself for a URL that
no page handler serves. An error handler is a main() function like any
other:
from markupsafe import escape
def main(request, response):
response.data = f"Nothing lives at {escape(request.path)}"
return response
The response of an error is HTML, and the path is text that the client chose, so the handler escapes it.
markupsafe is installed with Werkzeug.
The response it receives already has the right status code and Werkzeug’s default body. The handler
changes what it wants and returns it.
An error handler can ask for e, the exception that was raised. e.code, e.name, and e.description
are useful for building a response:
import json
def main(response, e):
response.content_type = "application/json"
return json.dumps({"error": e.name, "detail": e.description, "status": e.code})
An error handler can ask for request too, but it is
not given the body: it answers for requests that
a hook turned away as well as for ones that failed in a page. It can use what the page handler had already
read, and one that needs more sets request.shallow = False first.
Error handlers are also a natural place for work that should happen whenever an error occurs: logging
repeated 404 responses by address to spot a scanner, raising an alert on a class of failure, or giving
every API error the same shape.
Different error pages for different sections
Error handlers are scoped by path, just like page handlers. A file deeper in the tree overrides one higher up for its section:
my_webapps
|-- webapp1.404.py
|-- webapp1.page.get.py
|-- /webapp1
|-- API.404.py
|-- /API
|-- users.page.get.py
webapp1.404.pyhandles404for the site in generalAPI.404.pyhandles404for everything under/API
So the site can return HTML error pages while the API returns JSON, and neither knows about the other. Cylinder uses the most specific error handler for the URL that was requested.
There is one file per status code. A site that wants custom pages for 404 and 500 has two files.
Uncaught exceptions
An exception that your code does not catch becomes a 500 Internal Server Error. Cylinder logs its
traceback, and then runs the 500 error handler if there is one. If there is not, it returns Werkzeug’s
plain 500 page.
An HTTP error that Werkzeug raises itself keeps its own status, and is handled as an abort() is, with no
traceback. request.form["name"] raises a 400 when the form has no such field, and request.get_json()
a 400 or a 415 for a body that is not JSON.
A 500 handler chooses what the visitor is told, and has no logging to do. The traceback is in the log
before the handler runs, whatever the handler then does:
def main(response):
response.data = "Something went wrong on our side."
return response
In a 500 handler, e is a
Werkzeug InternalServerError
and e.original_exception is the exception that was actually raised, for a handler that does more with it,
such as sending an alert.
Returning the traceback to the browser can be handy while developing. Do not do it in production, where it tells a stranger how your code is laid out.
Because uncaught exceptions already mean 500, you generally should not call abort(500) yourself. For a
failure you expect, use the most specific status that fits, such as 503.
Cylinder always answers
Whatever goes wrong while handling a request, Cylinder returns a response and logs the traceback of the
cause. An exception never reaches your WSGI server while Cylinder has the request, except one that Python
raises to stop a program, such as the SystemExit of sys.exit(). These are the cases beyond a failing
page handler:
What fails |
What the client gets |
|---|---|
An error handler raises an exception |
A |
The |
A plain |
A late hook raises |
A |
|
A plain |
|
A plain |
|
A plain |
An extra is refused |
A plain |
A placeholder is refused |
A |
The response cannot be sent |
A plain |
A 500 handler that calls abort(500) counts as one that raises. A file that fails outside main()
counts as one whose main() raises: a file with a syntax error, with an import that fails, or with no
main(). A file is run when its turn comes, so the files before it have run by then.
A plain 500 is Werkzeug’s page for the status. It takes the place of the response as any error does, so
what survives an abort survives it too: the headers and cookies that were set
are kept, and whatever was registered with
response.call_on_close() still runs. The late hooks run on
it where the files of the request are known. The one plain 500 that keeps nothing but the cleanup is the
one for a response that cannot be sent, which is found after the late hooks have run.
app_map() runs before Cylinder knows which webapp the request belongs to, so no error handler file or
hook can run for a failure there. The same goes for what app_map() returns
when it is refused: the files of the request are not known yet.
A placeholder that is refused is found while Cylinder walks down the URL, before
it runs any hook. The directories above the placeholder are known by then. So the 500 handler and the
late hooks for the path of the directory that it is in, and for every path above that, run as for any
error. With two placeholders in users, those are the files named users and the ones above them.
A response that cannot be sent is found last of all. Werkzeug reads a Location as a URL when it writes
the headers, and refuses one such as //[. A redirect is made where abort() is called, and
its URL is read there in the same way, so a redirect that cannot be sent fails there, and is answered as
any other error. A Location that a handler sets itself is read only when the headers are written. That is
also when two more things are found that no server can send: a character that Latin-1 does not have, which
no header can hold, and a header that only a server may send, such as Connection, which a server such as
Waitress refuses. The late hooks have run by then, so the plain 500 for any of these has nothing of the
response but its cleanup. To send a filename with such a character in Content-Disposition, percent-encode
it after filename*=UTF-8'', as urllib.parse.quote() does.
What goes wrong after Cylinder has handed the response to the server is the server’s to report: a generator
that streams a body and raises, or a function registered with
call_on_close() that does.
Aborting from an error handler or from app_map()
abort() works everywhere a handler runs.
In an error handler. A
401handler can send the visitor to a login page withabort(302, "/login"), and any handler can turn one status into another. Whatever an error handler aborts with is final: Cylinder sends Werkzeug’s response for it and does not run another error handler. That keeps two error handlers from passing a request back and forth. The one exception isabort(500), which counts as the handler raising: the500handler answers it.In
app_map(). It can refuse or redirect a request before any webapp is chosen, for exampleabort(503)during maintenance.
Redirects
abort() also performs redirects. Pass a redirect status and the destination:
def main(request, response, abort):
if not request.cookies.get("session_id"):
abort(302, "/login")
response.data = "Welcome back"
return response
The supported redirect codes are 301, 302, 303, 307, and 308.
A redirect needs somewhere to go. abort(302), or a location that is None, empty, or not a str, is a
500, and the log says that the redirect has no URL. A browser keeps a 301 as the new address of the
page, so a redirect that sent the client to a guess could not be taken back.
abort() makes the redirect when it is called, and reads the URL as Werkzeug does when it sends the
response. So a URL that cannot be sent is an error where abort() is called: one that Werkzeug cannot
read, such as //[, and one with a line break in it, which no header can hold. Whoever writes a link can
put either in the next of a login form. The 500 handler answers it, and the late hooks run on it.
Redirects do not use error handler files. Cylinder builds the redirect response itself. Late hooks still run on it, so they can add headers. A late hook that raises the redirect itself is not run again.
Custom status codes
Werkzeug has a class for most HTTP errors, and not for every one: 402, 407, 425, 426, 506, 507,
508, 510, and 511 have none, and neither does a status that no standard defines. To use such a
status, write an exception class for it and register it with abort_extra when you create the app.
abort() passes it the description by name, as it does for Werkzeug’s own classes:
import cylinder
import waitress
import werkzeug.exceptions
class InsufficientStorage(werkzeug.exceptions.HTTPException):
code = 507
name = "Insufficient Storage"
description = "The server has insufficient storage to complete the request"
def main():
app = cylinder.get_app(app_map, abort_extra={507: InsufficientStorage})
waitress.serve(app, host="127.0.0.1", port=8080)
def app_map(request):
return "my_webapps", "webapp1"
if __name__ == "__main__":
main()
After that, abort(507) works in any handler, and a file named webapp1.507.py handles it like any other
error. Without such a file, the response is built from the class’s name and description. Where no abort()
is at hand, as in a module that a handler calls, the class can be raised itself:
raise InsufficientStorage() is answered as abort(507) is.
The order things happen in
For a request that ends in an error, Cylinder runs:
the early hooks, from the site root down
the page handler, up to the point where it calls
abort()or raisesthe most specific error handler for that status code, if there is one
the late hooks, from the URL back up
When no page handler serves the request, there is nothing to run at step 2, and the error is the 404,
405, or 501 that Cylinder raises in its place. The early hooks have already run by then. When an early
hook is what raises the error, the early hooks below it are skipped along with the page handler. A
redirect, and a response that is passed to abort(), skip step 3.
Given this layout:
my_webapps
|-- webapp1.400.py
|-- webapp1.page.get.py
|-- /webapp1
|-- foo.hook.early.py
|-- foo.hook.late.py
|-- /foo
|-- bar.400.py
|-- bar.page.get.py
a GET /foo/bar whose handler calls abort(400) runs foo.hook.early.py, then bar.page.get.py, then
bar.400.py, then foo.hook.late.py. Without bar.400.py, the error would be handled by
webapp1.400.py.
Anything registered with response.call_on_close() runs
however the request ends, including after an error or a redirect.