Handlers

A handler is a Python function named main() in a file that routing has matched to the request. There is no base class, no decorator, and no registration step. This page covers what a handler receives, what it returns, and the few rules Cylinder enforces.

The request and response objects

The most important object passed to a handler is response:

def main(response):
    response.data = "Hello World!"
    return response

response is an empty Werkzeug Response that Cylinder creates before calling your handler. You fill it in and return it:

  • response.data for the body

  • response.status_code for the HTTP status

  • response.content_type for the content type

  • response.headers[...] for headers

  • response.set_cookie(...) for cookies

To read the incoming request, ask for request as well:

def main(request, response):
    response.data = f"Hello {request.user_agent}!"
    return response

request is the matching Werkzeug Request, so headers, query parameters, form data, cookies, uploaded files, and JSON bodies are all available exactly as Werkzeug documents them. Cylinder does not wrap or rename anything, so the Werkzeug documentation is your documentation.

Returning a string as a shorthand

When all a handler needs to do is set the response body, it can return the body itself as a str or bytes. Cylinder assigns it to response.data for you. These two handlers are equivalent:

def main(response):
    response.data = "Hello World!"
    return response
def main():
    return "Hello World!"

The shorthand only sets the body. Anything already set on the response is kept, including the status, headers, cookies, and content type, so you can combine the two:

def main(response):
    response.content_type = "text/html; charset=utf-8"
    return "<h1>Hello World!</h1>"

This works in page handlers, hooks, and error handlers. A hook that returns a string replaces the body, which is rarely what a hook is for.

Only str and bytes are accepted. Returning anything else is an error, described under the rules below.

Handler parameters

A handler names the things it needs as parameters, and Cylinder passes them in by name. The order does not matter, and no parameter is required. A parameter after a * is passed in too, and one that takes whatever is left over, such as *args or **kwargs, is passed nothing.

def main(request, response, logger, abort):
    logger.info("Saying hello to %s", request.user_agent)
    response.data = f"Hello {request.user_agent}!"
    return response

The built-in parameters are:

Parameter

What it is

response

The Werkzeug Response to fill in and return

request

The Werkzeug Request for this request

logger

A logger whose records carry the request ID. See logging

abort

Stops the request with an HTTP error or a redirect. See errors

remainder

The URL path segments left over after the handler’s file was matched. See routing

e

The exception being handled, in an error handler or a late hook after one. Otherwise None

request_id

The ID that the log records of the request carry. See request IDs

A placeholder in the path of a file adds a parameter of its own. For /users/123, the handler users/{user_id}.page.get.py can ask for user_id and receives "123". So can every hook and error handler that runs for that request.

No parameter affects routing. Which paths a handler serves is decided by its filename, and what it asks for only decides what it is given. See Dynamic paths.

Your application can add its own parameters, such as a database session factory or a template renderer. Composing an application shows how.

Asking for something that is not there

Asking for a parameter that does not exist is an error. For example, asking for req when the parameter is named request:

def main(req, response):
    ...

raises a TypeError that names the file, the parameter, and the parameters that are available. In a handler or hook that becomes a 500 response, so a typo shows up the first time the page is requested.

If a parameter is only sometimes available, such as an extra parameter that only some of your webapps provide, give it a default value. Cylinder uses the default when it has nothing to pass:

def main(response, render_template=None):
    ...

Decorators

Parameters are matched by name, and a decorator normally hides the names of the function it wraps. If you decorate main(), build the decorator with functools.wraps so that Cylinder can still see them.

Type hints

Type hints are optional, and they make editors much more helpful. Annotate request and response with Werkzeug’s types to get autocomplete and inline documentation:

from werkzeug.wrappers import Request, Response

def main(request: Request, response: Response):
    response.data = request.path
    return response

What belongs at the top of a handler file

A handler file is an ordinary Python module, so it can contain imports, constants, and helper functions alongside main().

There is one thing to know. Cylinder loads handler files at request time, which is what lets you edit a page and see the change without restarting. It also means each handler file is executed again on every request that uses it. Cylinder compiles a file only when it changes, but it runs the file every time. A handler file behaves more like a script that runs per request than like a normal imported module, and that has consequences for code outside main():

  • Module-level state does not persist. A counter, cache, or connection pool defined at the top of a handler file is created again for each request, so it never accumulates anything.

  • Code that must only run once will misbehave. Declaring a SQLAlchemy model in a handler file is a common example: the second request raises an error because the table is already defined.

  • A class is built again for each request. A dataclass, or any other class, can be defined in a handler file, and is a new class every time the file runs. Building one takes time: where it was measured, a dataclass with three fields took about 160 microseconds to build, which is longer than a small page took to serve on Linux. An object that outlives its request, in a cache or a session, is not an instance of the class that the next request builds.

  • Python can find a handler file by name only while its top-level code runs. For that long the file is in sys.modules under its __name__, as a module that is being imported is. That is when dataclasses looks there, to read an annotation that is a string. Code in main() that looks up the module of a class does not find it: pickle cannot store an object of a class from a handler file, and typing.get_type_hints() cannot resolve a name that the file defines.

  • __name__ is the path of the file, and can have a number after it. Each request runs a file as a module of its own, and each module needs a name that no other has. So while another request is running the top-level code of the same file, the name is the path with a number after it, such as users.page.get.py#2. Neither request waits for the other. For the path, use __file__, as Cylinder does in its own log lines and errors.

  • A file runs when its turn comes, from its first line. The top of a page handler does not run until the early hooks have let the request in, so nothing in the file runs for a request that a hook turned away. An error at the top, such as a syntax error or an import that fails, is answered like one in main().

Keep the top of a handler file to imports, constants, and helper functions. Anything that must live longer than one request belongs in a normal module that the handler imports, or in an object created in cylinder_main.py and passed in through app_map(). So does a class that is costly to build, or whose objects are stored.

Modules that a handler imports are loaded once and cached by Python in the usual way. Editing users.page.get.py takes effect on the next request; editing a models.py that it imports requires a restart. Operations has the full list, and shows how to have the restart done for you during development.

The rules Cylinder enforces

Cylinder includes two small safeguards. Both exist to prevent a class of bug that is hard to track down once it is in a large codebase, and the second also keeps a site from working on a request that it has not let in.

Handlers must return the same response object

Cylinder creates one response for the request and passes that same object through hooks, page handlers, and error handlers, until an error takes its place. Your code must modify that object and return it, or return a str or bytes body for Cylinder to put on it. It must not create and return a different response object.

This is correct:

def main(response):
    response.data = "Hello World!"
    return response

This is not:

from werkzeug.wrappers import Response

def main(response):
    return Response("Hello World!")

If a handler returns a different response object, Cylinder raises:

ValueError: must return the response passed in, or a str or bytes to use as its body; got a different Response

The same error is raised for any other return value, and names its type. Forgetting the return statement is the most common cause, which reports got NoneType.

The reason for the rule: a hook that sets a security header or a cookie would be silently undone by a handler that swapped in a fresh response. With one shared object, nothing a hook does can be lost by accident.

Only a page handler reads the request body

A page handler can read the body of a request. Everywhere else the request is in Werkzeug’s shallow mode: in app_map(), in early and late hooks, and in error handlers. Code there cannot read the body through request.data, request.form, request.files, request.get_json(), or request.stream unless it says so first. Reading it raises a RuntimeError, so the request gets a 500, and the traceback in the log names the line that read it. request.get_json() looks at the Content-Type first: for a body that is not JSON it reads nothing, and raises a 415, or returns None with silent=True.

Headers, cookies, query parameters, the method, the host, and the path are available everywhere.

The rule does two things:

  • Nothing is done with a body unless the request was let in. Early hooks are where a site decides who may go on, and everything such a check needs is in the head of the request: a session cookie, a token in a header, the path. The body is the part whose size and shape a stranger chooses, and reading it is work: a form is decoded, JSON is built into objects, an upload is written to a temporary file. A request that an early hook turns away has had none of that done for it, by the hooks on the way in or by the error handler and the late hooks that answer it.

  • Code that reads the body by mistake fails at once. A body can be read from the connection once. A hook that read request.stream, or parsed a form that the page handler wanted as bytes, would leave the handler with an empty body, and nothing in the handler’s file would say why. Under the rule, the first request through such a hook is a 500, and the log says which line to look at. A late hook is held to the rule on every request too, and not only on one that was turned away. It is given what the page handler already read, as below says, so it fails at once only where the page handler reads nothing. Where the page handler reads the form, a late hook that reads it too first fails on a request that no page handler read, such as one that an early hook turned away. Test such a hook with a request that is turned away.

The rule is about what your code does with a body, not about receiving it. A WSGI server may take in the whole body before it calls the app, as Waitress does, so a limit on its size belongs in the server or the proxy. See Request size.

When a hook or an error handler needs the body

Most checks do not need it. A token that a script sends can go in a header such as X-CSRF-Token, and an early hook can read every header.

A check that does need the body, such as a CSRF token in a form field, opts in by setting request.shallow = False. Put that line after the checks that need no body, so that only a visitor who has passed them reaches it:

# account.hook.early.py
import hmac

def main(request, response, abort, session):
    if "user" not in session:
        abort(302, "/login")
    if request.method == "POST":
        request.shallow = False  # this visitor is signed in, so the form may be read
        sent = request.form.get("csrf_token", "")
        if not hmac.compare_digest(sent.encode(), session["csrf_token"].encode()):
            abort(403)
    return response

session is the extra parameter that holds the visitor’s session, and the token is one that the site put there when it built the form. A few details:

  • The opt-in lasts for one file. Cylinder puts the request back into shallow mode before each hook and each error handler runs, so every file that reads the body says so itself. An error handler or a late hook opts in with the same line.

  • What was read is kept. Werkzeug keeps what request.form, request.get_json(), and request.get_data() returned. Code that runs later is given the same values without opting in, because nothing is read again. That covers the page handler after a hook that opted in, and an error handler or a late hook after a page handler that read the body. An error handler that cannot count on that, because the page handler may abort before it reads, opts in itself.

  • Parsing a form uses the body up. Once request.form or request.files has parsed a form, request.get_data() returns nothing, in the hook and in the page handler alike. A page that needs the bytes as they were sent, to check the signature of a webhook for example, cannot sit beneath a hook that parses the form. request.get_json() keeps the bytes.