---
name: cylinder
description: >-
    Build, modify, and debug web applications that use Cylinder, the Python WSGI framework from Plasma with
    file-based routing on top of Werkzeug. Use whenever a project imports `cylinder`, calls
    `cylinder.get_app()`, has an `app_map()` function, or contains handler files named like
    `name.page.get.py`, `name.tree.get.py`, `name.hook.early.py`, `name.hook.late.py`, or `name.404.py`.
    Read it before starting a Cylinder project, and before adding or changing a page, a URL, a hook, an
    error page, or a static file in one, even when the request does not name Cylinder.
---

# Cylinder

Cylinder is a small WSGI framework built on Werkzeug. A URL is handled by the file whose path matches it.
There is no route table and there are no decorators. To add a page, add a file. To find the code for a URL,
open the file at that path.

This file holds what most tasks need. The [references](#references) at the end are the pages of the
framework's documentation as raw Markdown. Fetch one only when a task needs that detail.

## Project layout

Install with `pip install cylinder waitress`. Cylinder needs Python 3.11 or newer, and runs under any WSGI
server.

```text
my_project
    |-- cylinder_main.py                    creates the app; defines app_map()
    |-- /shop                               an ordinary package: the application's own logic
    |-- /templates                          what is not for visitors stays outside the webapp
    |-- /tests
    |-- /my_webapps
        |-- webapp1.page.get.py             GET /
        |-- webapp1.hook.late.py            late hook for the whole site
        |-- webapp1.404.py                  every 404 on the site
        |-- /webapp1
            |-- contact.page.get.py         GET /contact
            |-- contact.page.post.py        POST /contact
            |-- assets.tree.get.py          serves the files under /assets (rule 8)
            |-- /assets
                |-- site.css                GET /assets/site.css
            |-- admin.hook.early.py         early hook for /admin and everything beneath it
            |-- admin.page.get.py           GET /admin
            |-- /admin
                |-- reports.page.get.py     GET /admin/reports
            |-- /users
                |-- {user_id}.page.get.py   GET /users/123, with user_id="123"
```

`cylinder_main.py`:

```python
import logging
import pathlib

import cylinder
import waitress

WEBAPPS = pathlib.Path(__file__).parent / "my_webapps"
config = {"site_name": "My Site"}

def app_map(request):
    # (directory that holds the webapps, name of the webapp, extra parameters for every handler)
    return WEBAPPS, "webapp1", {"config": config}

app = cylinder.get_app(app_map, log_level=logging.INFO)

if __name__ == "__main__":
    waitress.serve(app, host="127.0.0.1", port=8080)
```

-   `app_map()` runs first, for every request. It can ask for any of `request`, `response`, `logger`,
    `abort`, and `request_id`.
-   The directory is an absolute path, so that the app works whatever directory it is started from.
-   The name of the webapp is one name and never a path. Where it depends on the request, as with a site
    for each hostname, look it up in a dictionary you wrote, and never build it from what a client sent.
-   The third value is optional. Each key of it is a parameter that any handler, hook, or error handler can
    ask for by name. It is how a handler gets what the application creates: configuration, a template
    renderer, a database session factory, a lock. An object made inside `app_map()` is new for each
    request. A key cannot be the name of a parameter in the table under [Handlers](#handlers), such as
    `request` or `logger`.
-   An object that is made once and passed to every request is shared by requests that run at the same time
    on threads, so guard one that is not thread-safe with a lock.
-   `app` is at module level so that a server can import it, as in `gunicorn cylinder_main:app`.
-   Without `log_level`, every step of every request is logged to stderr at `DEBUG`.

## Filenames

| Filename                  | What it is                                                             |
| ------------------------- | ---------------------------------------------------------------------- |
| `<name>.page.<method>.py` | Page handler for one HTTP method, at its own path only                 |
| `<name>.tree.<method>.py` | Page handler for its own path and every path beneath it                |
| `<name>.hook.early.py`    | Hook that runs before the page handler, for its path and those beneath |
| `<name>.hook.late.py`     | Hook that runs after it, for the same paths                            |
| `<name>.<status>.py`      | Error handler for that status, for its path and those beneath          |
| anything else             | A file, which is sent only where a page handler serves files (rule 8)  |

-   `<name>` is the last segment of the URL path. The file for `/foo/bar` is `bar.*` inside the directory
    `foo`. The files for the root of the site have the name of the webapp, and sit beside its directory.
-   There are no `index` files. `/foo` is handled by `foo.page.get.py`, and the pages beneath it are in a
    directory `foo` next to that file.
-   `<method>` is the HTTP method in lowercase, or `default` for every method that has no file of its own.
-   A `<name>` in braces, such as `{user_id}`, is a placeholder. It stands for any one segment, as a file
    or as a directory, and the segment is passed to `main()` as the parameter `user_id`.

## Handlers

A page handler, a hook, and an error handler are each a function named `main()`. It names what it needs as
parameters, in any order, and is passed them by name.

```python
def main(request, response, abort, logger):
    if "id" not in request.args:
        abort(400, "The id parameter is required")
    logger.info("serving %s", request.path)
    response.content_type = "text/html; charset=utf-8"
    response.data = "<h1>Hello</h1>"
    return response
```

| Parameter    | Value                                                                            |
| ------------ | -------------------------------------------------------------------------------- |
| `request`    | Werkzeug `Request`                                                               |
| `response`   | Werkzeug `Response` to change and return                                         |
| `abort`      | `abort(404)`, `abort(400, "description")`, `abort(302, "/login")` for a redirect |
| `logger`     | Logger whose records carry the request ID                                        |
| `remainder`  | Path segments after the page handler's own path; every one where no page serves  |
| placeholder  | The segment a `{name}` on the path stood for, as a `str`: `user_id` is `"123"`   |
| `e`          | Exception in an error handler or in a late hook after one; otherwise `None`      |
| `request_id` | The ID that the request's log records carry, as a `str`                          |
| extras       | Any key of the dictionary that `app_map()` returns as its third value            |

-   `request` and `response` are Werkzeug's own objects, with nothing wrapped. `request.args`,
    `request.form`, `request.get_json()`, `request.cookies`, `response.headers`, `response.status_code`,
    and `response.set_cookie()` work as Werkzeug documents them.
-   A response starts as a `200` with the content type `text/plain`. A handler that sends HTML sets
    `response.content_type = "text/html; charset=utf-8"`, or a browser shows the markup as text.
-   `abort()` stops the request and leaves the body to the error handler for the status. It takes an error
    status, or one of the redirects `301`, `302`, `303`, `307`, and `308`: `abort(204)` is a `500`. An
    error status that Werkzeug has no class for, such as `402` or `507`, needs a class registered with
    `abort_extra`, or it is a `500` too. To send another status with a body of your own, set
    `response.status_code` and return the response. No error handler runs for that.

## The order of a request

1.  `app_map()` chooses the webapp and supplies the extra parameters. The hooks and the error handlers
    belong to the webapp, so none of them runs for a request that `app_map()` itself aborts or fails on, or
    for the `500` of an extra that is refused. A placeholder that is refused is a `500` before any early
    hook runs, and the `500` handler and the late hooks above it answer it.
2.  The early hooks run, from the root of the site down to the URL. An `abort()` in one skips the rest of
    them and the page handler.
3.  The page handler runs. Where no page handler serves the request, Cylinder aborts here: with a `404`
    when the URL has no page for any method, and with a `405` and an `Allow` header when it has one for
    other methods.
4.  For an HTTP error from any of those, the closest `<name>.<status>.py` on the path builds the response.
    An exception that nothing caught is a `500`, and Cylinder logs its traceback. A redirect runs no error
    handler.
5.  The late hooks run, from the URL back up to the root of the site, on errors and redirects too.
6.  The response is sent, and then the functions registered with `response.call_on_close()` run.

Hooks run whether or not a page is found, and for every HTTP method. So a hook that asks for a login
answers before the `404` does, and a header set in a hook is on that `404` too.

## Which file serves a URL

-   A deeper path wins over a shallower one. At the same path, the exact method wins over `default`, and
    then `.page.` wins over `.tree.`.
-   A `.page.` handler serves its own path and nothing beneath it. For a URL with no file of its own, the
    nearest `.tree.` handler above it runs, and is passed the rest of the path in `remainder`.
-   A segment matches whatever in the directory is named for it. Only when nothing is, it matches the
    placeholder there. A hook, an error handler, or a directory named `admin` counts as much as a page
    does: once `users/admin.hook.early.py` exists, `/users/admin` is no longer served by
    `users/{user_id}.page.get.py`, and needs a page of its own.
-   A directory holds one placeholder. Use the name that is already there.
-   `HEAD` runs the `.get` file and the body is dropped, so do not add `.head` files by default.
-   Matching is case-sensitive on every operating system. Nothing is found through a symbolic link.
-   A page is served in one spelling of its URL. Link to `/about`, never `/about/`: a slash at the end, a
    slash too many, a `.` or `..` segment, or a backslash makes a URL one that no page serves.

## Rules to follow

1.  **Every `main()` returns the response it was given, or a `str` or `bytes`.** That goes for a hook and
    an error handler as much as for a page handler: a hook ends with `return response`. A `str` or `bytes`
    becomes the body, and everything else on the response is kept. Never construct and return a new
    `Response`, and never fall off the end of `main()`: both are a `500`. Use one style throughout a
    project: match the handlers already there, and in a new project set fields on `response` and return it.
2.  **Only ask for parameters that exist.** A name that is not available is a `500`. Give a parameter that
    only some requests have a default value.
3.  **Put the dynamic part of a URL in a filename.** For one segment, use a placeholder:
    `users/{user_id}.page.get.py` serves `/users/123` and nothing deeper, so an unknown URL gets a `404`
    without any code. For a path of any depth, use `<name>.tree.<method>.py`, which must `abort(404)` for
    the paths it does not serve, or every URL beneath it answers `200`. No parameter affects routing:
    asking for `remainder` in a `.page.` handler does nothing.
4.  **Keep handler files stateless.** A handler file is run again for every request, so the top of one
    holds imports, constants, and helper functions, and nothing else. A cache, a counter, a connection
    pool, a SQLAlchemy model, or a class whose objects are stored goes in an ordinary module, or is made in
    `cylinder_main.py` and passed through `app_map()`. A handler file cannot be imported, because its name
    has dots in it, so code that two handlers share goes in an ordinary module too. A handler imports such
    a module by its usual name, so the directory of the project has to be on `sys.path`, as it is when
    `cylinder_main.py` is run or imported from there.
5.  **Read the request body in a page handler only.** In `app_map()`, in a hook, and in an error handler,
    reading `request.form`, `request.data`, or `request.files` is a `500`, and so is `request.get_json()`
    for a JSON body. For a body that is not JSON, `get_json()` reads nothing: it raises a `415`, or returns
    `None` with `silent=True`. A request is let in or turned away on its headers, before anything is done
    with its body. A hook that has to read it, as a check of a CSRF token in a form field does, sets
    `request.shallow = False` first, after its checks that need no body. An error handler or a late hook
    can use what the page handler already read, and fails on a request whose body no page handler read,
    such as one that an early hook turned away.
6.  **Every hook on the path runs.** A hook for a section adds to the hooks above it and never replaces
    them, so do not repeat the check of a parent hook in a child, and put an exception for part of a
    section in the hook that covers the section. A hook is not named for a method. It runs for every one,
    the `OPTIONS` that a browser sends before a cross-origin request included, and checks `request.method`
    itself where it treats one differently. A hook that answers a request itself, as for that `OPTIONS`,
    sets the status and the headers on `response` and calls `abort(response)`: no page handler and no error
    handler runs, and the late hooks still do.
7.  **Headers and cookies survive `abort()`.** An error or a redirect replaces the status and the body, and
    keeps the headers and cookies that were set before it. Set a header that only suits success, such as
    `Cache-Control: public`, after the last point where the handler might abort. A late hook runs on errors
    and redirects too, so it checks `response.status_code` first; for static files it accepts `200`, `206`,
    and `304`.
8.  **A file is public only where a handler serves it.** To serve the files in a directory, write
    `<dir>.tree.get.py` beside it with the one line `from cylinder import static_file as main`. To serve
    one file, write `<filename>.page.get.py` beside it with the same line. Ruff calls that import unused,
    and `ruff check --fix` deletes it, so end the line with `# noqa: F401`. A file is sent with the content
    type of its extension, and a URL that is not a file is a `404`. Give the files for the browser a
    directory of their own, such as `assets`, and do not serve the whole site unless asked. Modules,
    templates, databases, and configuration go beside the webapp directory and not in it. Handler files and
    hidden paths are never sent. To set headers on files, call `static_file(request, response, abort)` from
    a `main()` of your own and change the response it returns.
9.  **Check what a client sends.** Cylinder validates and converts nothing. A placeholder's value, a query
    parameter, a form field, and a JSON body come from the client unchecked, and a placeholder's value is
    always a `str`. Check each one in the handler that uses it, and `abort(400)` where it fails. A value in
    a URL is not a permission: `/users/123/settings` says which user is asked about, not who is asking.

## What Cylinder leaves to you

Cylinder routes requests and nothing more. Do not look for these in it:

-   **Templates, a database layer, and sessions.** Use any library, create its objects once in
    `cylinder_main.py`, and pass them through `app_map()`. The composition reference has a Jinja2 setup, a
    SQLAlchemy setup, and a complete server-side session.
-   **Protection against cross-site request forgery.** A site that signs users in with a cookie and accepts
    form posts needs its own check, in an early hook.
-   **A function that builds URLs.** A URL is the path of its file, so write the link out.
-   **Async handlers and WebSockets.** A handler is an ordinary function, never `async def`.

## Common tasks

**Add a page.** Create `<dir>/<name>.page.get.py` with a `main()`. A handler, hook, or error handler file
takes effect on the next request, with no restart. A change to `cylinder_main.py` or to a module that is
imported needs one.

**Add a URL with a dynamic part.** For `/users/123`, create `users/{user_id}.page.get.py` and ask for
`user_id` in `main()`. For `/users/123/posts`, create `users/{user_id}/posts.page.get.py`. The name in the
braces must be a Python identifier, and must not be the name of another parameter such as `request`.

**Handle a form.** `contact.page.get.py` shows it and `contact.page.post.py` receives it, reading
`request.form`. Any other method gets a `405` with no code, so do not write a `.default` file to send one.

**Render a template.** In `cylinder_main.py`, make a `jinja2.Environment` once, with a `FileSystemLoader`
on the absolute path of the `templates` directory and `autoescape=jinja2.select_autoescape()`, and pass a
function `render_template(template_name, **context)` through `app_map()`. A handler asks for
`render_template`, sets the content type, and puts what it renders in the body.

**Protect a section.** Add `<section>.hook.early.py` beside the directory of the section, and abort in it.
It covers `/<section>` and everything beneath it, including pages added later, so no page checks for
itself. To pass what the hook found to those pages, add `"g": types.SimpleNamespace()` to the dictionary
that `app_map()` returns, so that each request gets a new one:

```python
# admin.hook.early.py
def main(request, response, abort, g, sessions):
    g.user = sessions.get(request.cookies.get("session_id"))
    if g.user is None:
        abort(302, "/login")
    return response
```

A page beneath `/admin` then asks for `g` and reads `g.user`.

**Redirect.** `abort(302, "/path")`. The location is a `str` that is not empty, that Werkzeug can read as a
URL, and that has no line break, or the redirect is a `500`. Never pass a value from the request as the
location unchecked: a location that starts with `//` or `/\` leaves the site. Encode `request.path` with
`urllib.parse.quote()` before putting it in a location.

**Build a JSON API.** Set `response.content_type = "application/json"` once, in `<api>.hook.late.py`, and
put `json.dumps(...)` in the body in each handler. Read a body with `request.get_json(silent=True)`, which
is `None` where the body is not JSON. To make errors JSON too, add an error handler for each status that
the API sends, such as `<api>.400.py`, `<api>.404.py`, `<api>.405.py`, and `<api>.500.py`. There is one
file for each status. Put the function that builds the body in an ordinary module, and give each file a
`main(response, e)` that calls it.

**Customize an error page.** Add `<name>.<status>.py`. Its `response` already has the status, and
Werkzeug's HTML page for it as the body, with the content type `text/html`. Ask for `e` and use `e.code`,
`e.name`, and `e.description`. For a `500`, `e.description` is a generic sentence that is safe to send, the
exception that was raised is `e.original_exception`, and Cylinder has already logged its traceback. Never
send a visitor the traceback.

**Release a resource after the request.** Call `response.call_on_close(function)`, in `app_map()`, a hook,
or a handler. The function runs however the request ends.

**Test.** Give the test an `app_map()` of its own, which can pass other extras than production does:

```python
import cylinder
from cylinder_main import WEBAPPS

def test_user_page():
    def app_map(request):
        return WEBAPPS, "webapp1", {"users": {"1": {"name": "Ada"}}}

    client = cylinder.get_app(app_map).test_client()
    response = client.get("/users/1")
    assert response.status_code == 200
    assert "Ada" in response.text
```

The client is Werkzeug's: `client.post("/contact", data={...})`, `client.post("/api/users", json={...})`,
`client.get("/admin", headers={...})`. The response has `status_code`, `headers`, `data`, `text`, and
`json`, and the client keeps cookies between requests. For pytest to find `cylinder_main`, set
`pythonpath = .` in `pytest.ini`.

## Working in an existing project

-   **Find the handler of a URL by building its path, and not by searching.** Then check with a directory
    listing: `/account/orders/12` is `account/orders/12.page.get.py`, or the placeholder in that directory,
    or the nearest `.tree.` file upward.
-   **Find what else runs for a URL by listing the directories above it.** Every `.hook.` file that is
    named for a part of the URL applies, and of the files named for a status, the closest one does.
-   **Read only the handler and what its signature names.** Every dependency is a parameter, and the extras
    come from `app_map()` in `cylinder_main.py`. Put logic in ordinary packages, and keep handlers thin.

## Debugging

| Symptom                                         | Likely cause                                                |
| ----------------------------------------------- | ----------------------------------------------------------- |
| `404` for one value, such as `/users/admin`     | Something there is named `admin`, and takes it from `{..}`  |
| `404` beneath a handler                         | It asks for `remainder` but is not named `.tree.`           |
| `404` for an image, stylesheet, or script       | No handler serves files there; see rule 8                   |
| `405` for one method                            | No file for that method; `Allow` lists the ones with a file |
| `500` with "site_dir that is not a directory"   | A wrong `site_dir`, or a relative one; use an absolute path |
| `500` with "site_name that names nothing"       | A misspelled webapp name, or a path in it                   |
| `500` with "latin-1" or "hop-by-hop"            | Non-Latin-1 text in a header, or a header like `Connection` |
| `500` with "more than one placeholder"          | Two different `{names}` in one directory                    |
| `500` with "has the name of another parameter"  | A placeholder or an `app_map()` extra with a name in use    |
| `500` with "must return the response passed in" | Missing `return`, or a new `Response` was returned          |
| `500` with "app_map() must return"              | Not `(directory, name)` or `(directory, name, extras)`      |
| `500` with "asks for the parameter"             | Misspelled parameter, or an extra not provided by `app_map` |
| `500` with "shallow=True"                       | The body was read outside a page handler; see rule 5        |
| `500` with "no exception for"                   | A status with no class in Werkzeug or in `abort_extra`      |
| An error page is cached or has a stray header   | The header was set before `abort()`, and headers are kept   |

Every `500` is logged with its traceback, so read the log before guessing.

## References

Each reference is one page of the documentation as raw Markdown. Fetch only the one the task needs.

-   A first app, built step by step: <https://plasmacan.github.io/cylinder/_sources/quickstart.md.txt>
-   Matching rules, placeholders, `.tree.` handlers, several sites from one process:
    <https://plasmacan.github.io/cylinder/_sources/routing.md.txt>
-   Serving files, caching, pre-compressed files, what is never sent:
    <https://plasmacan.github.io/cylinder/_sources/static-files.md.txt>
-   Parameters, return values, a hook that reads the body:
    <https://plasmacan.github.io/cylinder/_sources/handlers.md.txt>
-   Early and late hooks, an authentication example, a preflight answered in a hook:
    <https://plasmacan.github.io/cylinder/_sources/hooks.md.txt>
-   `abort()`, error handlers, redirects, status codes of your own:
    <https://plasmacan.github.io/cylinder/_sources/errors.md.txt>
-   Templates, databases, sessions, cleanup, data for one request:
    <https://plasmacan.github.io/cylinder/_sources/composition.md.txt>
-   A complete JSON API: <https://plasmacan.github.io/cylinder/_sources/json-apis.md.txt>
-   Laying out a large project: <https://plasmacan.github.io/cylinder/_sources/large-applications.md.txt>
-   The test client and pytest: <https://plasmacan.github.io/cylinder/_sources/testing.md.txt>
-   Restarting during development, logging, request IDs, streaming, thread safety:
    <https://plasmacan.github.io/cylinder/_sources/operations.md.txt>
-   Deployment, reverse proxies, worker threads and processes, running under ASGI:
    <https://plasmacan.github.io/cylinder/_sources/deployment.md.txt>
-   Every filename, parameter, and option in tables:
    <https://plasmacan.github.io/cylinder/_sources/reference.md.txt>
-   A checklist to go through before an app faces the internet:
    <https://plasmacan.github.io/cylinder/_sources/security.md.txt>
-   What Cylinder does not do: <https://plasmacan.github.io/cylinder/_sources/limits.md.txt>

Links inside those pages such as `routing.md#placeholders` refer to the other pages in this list.
