# Routing In Cylinder the directory tree is the routing table. This page explains how a request is matched to a file. Once you know the rule, you can predict where any request will go by looking at a directory listing, and you can find the code for any URL without searching. ## The shape of a webapp A webapp is a directory, plus the files that sit beside it and share its name: ```text my_webapps |-- webapp1.page.get.py handles GET / |-- /webapp1 |-- about.page.get.py handles GET /about |-- /foo |-- bar.page.get.py handles GET /foo/bar ``` A page handler is named in three parts: | Part | Example | Meaning | | ------ | ------- | ----------------------------------------------------------------- | | name | `bar` | The last segment of the URL path this file handles | | kind | `.page` | A page handler. `.hook` is a [hook](hooks.md) | | method | `.get` | The HTTP method, in lowercase, or `.default` for any other method | A page handler can also be of the kind `.tree`, which serves the [paths beneath it](#dynamic-paths) as well, and a name can be a [placeholder](#placeholders) such as `{user_id}`, which stands for any value. A hook has `.early` or `.late` where a page handler has its method, as in `admin.hook.early.py`: it is not named for a method, and runs for every one. An [error handler](errors.md#error-handler-files) has its status in place of the last two parts, as in `webapp1.404.py`. The file that handles `/foo/bar` is named `bar` and lives in the `foo` directory. The file that handles the root of the site is named after the webapp and lives beside the webapp's directory. Matching is case-sensitive on every operating system. A directory named `API` matches `/API/...` and does not match `/api/...`. That holds on Windows and macOS too, where the filesystem itself would open the directory under either spelling, so a site answers the same URLs on a developer's machine as on a Linux server. ## Why there are no index files Many frameworks and file-based routers revolve around names like `index.html`, `index.php`, or `page.tsx`. Cylinder intentionally does not. In a large project, index-style names produce "index soup": you open several tabs in your editor and they all have the same name, even though they are different pages. Cylinder names each handler after the last segment of the path it serves, so the tabs read `payments.page.get.py` and `company.page.get.py`. For example, the handlers on the way to `/API/v2/reports/company/payments` look like this: ```text my_webapps |-- webapp1.page.get.py |-- /webapp1 |-- /API |-- /v2 |-- reports.page.get.py |-- /reports |-- company.page.get.py |-- /company |-- payments.page.get.py ``` A path segment can be both a file and a directory. `/API/v2/reports/company` is handled by `company.page.get.py`, and the pages beneath it live in the `company` directory next to that file. ## HTTP method routing The method is part of the filename, so one URL can have a separate file for each method: ```text |-- /foo |-- bar.page.get.py handles GET /foo/bar |-- bar.page.post.py handles POST /foo/bar |-- bar.page.default.py handles PUT, DELETE, and anything else ``` - `.get`, `.post`, `.put`, `.delete` and so on handle that one method. - `.default` handles any method that has no file of its own at that path. - Custom methods work too. `bar.page.move.py` handles `MOVE /foo/bar`. Method names must be alphabetic, and `DEFAULT` is reserved. No file can be named for any other method, such as `M-SEARCH`, so a request that uses one [gets a `501`](#when-nothing-matches). ### HEAD requests You do not need to write anything to support `HEAD`. A `HEAD` request is answered by the same files as a `GET` to that URL: the `.get` page handler, between the hooks that run for every method. Werkzeug then sends the status and headers and drops the body, so the response carries the same `Content-Length` and other headers the `GET` would have. If you want `HEAD` to behave differently, for example to skip expensive work that only matters for the body, add a `.head` file. `bar.page.head.py` takes over `HEAD /foo/bar` from `bar.page.get.py`. Your handler still sees the real method, so `request.method` is `"HEAD"` even when a `.get` file is running. ## How requests are matched Cylinder chooses the most specific file on disk: 1. A deeper path wins over a shallower one. 2. At the same path, an exact method match wins over `.default`. 3. For a `HEAD` request at the same path, `.head` wins over `.get`, which wins over `.default`. 4. A file is sent only where a page handler [serves files](static-files.md), and a handler file is never sent. 5. A `.page.` handler serves its own path only. A [`.tree.`](#handlers-for-a-whole-tree) page handler also serves the paths beneath it. At the same path and for the same method, `.page.` wins over `.tree.` 6. A name wins over a [placeholder](#placeholders): a segment is taken as a value only when nothing in the directory is named for it. 7. A URL is served in [one spelling](#one-spelling-for-each-url) only. Given this layout: ```text my_webapps |-- webapp1.page.get.py |-- /webapp1 |-- foo.tree.default.py |-- /foo |-- bar.page.get.py |-- bar.page.post.py ``` requests are matched like this: | Request | Handled by | | -------------------- | ---------------------------------------- | | `GET /` | `webapp1.page.get.py` | | `GET /foo/bar` | `bar.page.get.py` | | `POST /foo/bar` | `bar.page.post.py` | | `HEAD /foo/bar` | `bar.page.get.py`, with the body dropped | | `PUT /foo/bar` | `foo.tree.default.py` | | `GET /foo/bar/extra` | `foo.tree.default.py` | | `GET /anything-else` | no handler, so the response is `404` | `PUT /foo/bar` has no file of its own, so Cylinder walks up the tree to the nearest `.tree.` file that accepts the method, which is `foo.tree.default.py`. `GET /foo/bar/extra` walks up in the same way. `bar.page.get.py` is a `.page.` file, so for a path beneath its own it is passed over as if it were not there. `GET /anything-else` walks all the way up: the only handler above it is `webapp1.page.get.py`, which serves `/` and nothing else. Rule 1 takes priority over rule 2. A deeper `.default` file is chosen over a shallower file with the exact method. ### When nothing matches If no page handler serves the request, the response says what is at the URL: | The URL | Response | | ---------------------------------------------- | ------------------------------------------------ | | has no page handler, for any method | `404 Not Found` | | has one, but not for the method of the request | `405 Method Not Allowed`, with an `Allow` header | The `Allow` header lists the methods that have a file: those of the page handlers at the URL and of the `.tree.` handlers above it, with `HEAD` wherever `GET` is. With `users.page.get.py` and `users.page.post.py`, a `DELETE /users` gets `Allow: GET, HEAD, POST`. A `GET` is answered the same way: where a URL has only a `.post` file, it gets a `405`. A method that no file can be named for gets `501 Not Implemented` at every URL. That is a method that is not alphabetic, such as `M-SEARCH`, or the reserved `DEFAULT`. No page handler serves it, not even a `.default` one. The hooks run for it as they do for any request. A site therefore needs no code to turn down a URL that nobody wrote a page for, or a method that a URL has no file for. The response is built like any other error: the [early hooks](hooks.md) run first, then the [error handler file](errors.md#error-handler-files) for the status, then the late hooks. ### One spelling for each URL A page is served at one URL, and not at the others that resemble it. Each of these is answered as a URL that no page serves: | Request | Why it is not `/foo/bar` | | ------------ | ------------------------ | | `/foo/bar/` | A slash at the end | | `/foo//bar` | A slash too many | | `/foo/./bar` | A `.` or a `..` segment | | `/foo\bar` | A backslash | So a page has one address for links, caches, and search engines, and a rule in a proxy that names `/admin` sees the same path that Cylinder serves. The hooks on the way to the page still run for such a request, so a hook that asks for a login answers before the `404` does. To send a visitor who adds a slash on to the page instead, add [a hook that redirects](hooks.md#example-redirecting-a-stray-slash). ## Dynamic paths Not every URL has a file of its own. In a REST API you might expect: - `GET /API/v1/users` to list users - `GET /API/v1/users/123` to return one user - `GET /API/v1/users/123/posts` to list that user's posts Cylinder has no route patterns in code. The dynamic part of a route goes in a filename, like every other part of it, in one of two ways: - A [placeholder](#placeholders) such as `{user_id}` is a name that stands for any one segment. - A [`.tree.` handler](#handlers-for-a-whole-tree) serves its own path and every path beneath it. Reach for a placeholder first: it fits whenever you know the shape of the URL. A `.tree.` handler is for a path of any depth, or for a whole section that gets one answer. ### Placeholders A file or directory named with a parameter name in braces matches any one segment of a URL: ```text |-- /API |-- /v1 |-- users.page.get.py handles GET /API/v1/users |-- /users |-- {user_id}.page.get.py handles GET /API/v1/users/123 |-- /{user_id} |-- posts.page.get.py handles GET /API/v1/users/123/posts ``` The segment is passed in as the parameter that the placeholder names: ```python # {user_id}.page.get.py def main(response, user_id): response.data = f"get user {user_id}" return response ``` The path on disk is the URL with names where the values go. It is also how an OpenAPI document writes the same route: `/API/v1/users/{user_id}/posts`. A placeholder stands for exactly one segment. Nothing in this layout serves `/API/v1/users/123/extra`, so it is a [`404`](#when-nothing-matches) without any code. The value is a string: one segment of the path, as the server decoded it. The server decodes the whole path before Cylinder splits it, so an encoded slash, `%2F`, ends a segment as `/` does, and a value never holds a slash. Cylinder does not convert or check the value, so `user_id` can be `123`, `abc`, or a thousand characters long. The handler decides what is valid. Everything else about a file works as it does under an ordinary name. `{user_id}.page.put.py` handles another method, `{user_id}.404.py` is an error handler, and `{user_id}.hook.early.py` is a hook for `/API/v1/users/123` and everything beneath it. Hooks, error handlers, and the handlers beneath a placeholder can all ask for its value. A placeholder can be a directory, as `{user_id}` is above, so one resource can sit beneath another. [Nested resources](json-apis.md#nested-resources) builds an example, and says when a flat URL is the better choice. Five rules keep a placeholder predictable: - **A name of its own wins.** If anything in the directory is named for the segment, the segment is that name and not a value. With `me.page.get.py` beside `{user_id}.page.get.py`, `/users/me` goes to `me.page.get.py`. A hook, an error handler, a directory, or a static file under its full name counts as much as a page handler does. - **Cylinder does not go back.** Once a segment has matched a name of its own, the placeholder plays no part in the request. If `me` is also a directory, `/users/me/posts` is looked for in that directory only. - **One placeholder to a directory.** `{user_id}.page.get.py` and the directory `{user_id}` belong together. With a second placeholder of another name beside them, a request that needs one gets a `500`, and the log names both. - **A placeholder cannot take the name of another parameter.** That covers the built-in parameters, the ones from `app_map()`, and a placeholder higher up the same path. A request that reaches one gets a `500`. That `500`, and the one for a second placeholder, is found on the way down the URL, before any early hook has run. It is answered [as any error is](errors.md#cylinder-always-answers), by the `500` handler and the late hooks for the path of the directory and for the paths above it. - **The name is a Python identifier.** Braces around anything else, such as `{user-id}`, make an ordinary name that matches only itself. ### Handlers for a whole tree A page handler of the kind `.tree` serves its own path and every path beneath it that has no closer match. It is named like any other page handler, with `.tree` where `.page` would be: ```text |-- files.tree.get.py handles GET /files, /files/2024, /files/2024/q3.pdf, ... |-- old-shop.tree.get.py handles GET /old-shop and everything beneath it ``` Such a handler can answer for a whole section without looking at the path: ```python # old-shop.tree.get.py def main(abort): abort(301, "/store") ``` ### Accessing the remaining path `remainder` is a list of the URL path segments that come after the part of the path the handler's file matched. A `.tree.` handler uses it to see which of its paths was asked for: | Request | `remainder` in `files.tree.get.py` | | ------------------------ | ---------------------------------- | | `GET /files` | `[]` | | `GET /files/2024` | `["2024"]` | | `GET /files/2024/q3.pdf` | `["2024", "q3.pdf"]` | The handler decides which of those shapes are valid: ```python def main(response, remainder, abort): if len(remainder) > 2: abort(404) response.data = "files in /" + "/".join(remainder) return response ``` `remainder` is relative to the handler's own file, so this code keeps working unchanged if you move `files.tree.get.py` to another directory. A few more details: - Any handler, hook, or error handler can ask for `remainder`. Asking has no effect on routing. - For a `.page.` handler it is `[]`. - Hooks and error handlers receive the same `remainder` as the page handler for the request, not one relative to their own file. - If no page handler serves the request, `remainder` holds every segment of the path. - The full path is still available as `request.path`, and the query string as `request.args`. ### Paths a handler does not serve A `.page.` handler serves its own path and nothing beneath it. As `bar.page.get.py`, a handler answers `GET /foo/bar`. For `GET /foo/bar/extra` Cylinder passes it over and looks further up the tree for a `.tree.` handler. If there is none, the response is a [`404`](#when-nothing-matches). What a handler serves is decided by its filename alone. The parameters it asks for never change it. A `.tree.` handler has taken on every path beneath it that has no closer match. It should turn down the ones it does not serve, as the example above does with `abort(404)`. Otherwise it answers `200` for URLs that do not exist. ## Static files A file is sent to a client only where a page handler sends it, and a handler file is never sent. Cylinder comes with that page handler, so serving the files in a directory takes a handler file of one line: ```python # assets.tree.get.py from cylinder import static_file as main ``` [Static files](static-files.md) has the rest: serving a single file, caching, compressed files, and what is never sent. ## Several sites from one process `app_map()` runs for every request and chooses the webapp, so one process can serve several sites: ```python SITES = { "foo.com": "foo", "bar.com": "bar", } def app_map(request): return "my_webapps", SITES.get(request.host, "bar") ``` `request.host` has the port in it when the port is not the usual one for the scheme. A site that is reached on port 8080 is `foo.com:8080` there, and has to be in the table under that name. This plays a role similar to Apache virtual hosts or nginx server blocks, expressed in Python. Look the hostname up in a fixed table as shown, and do not pass a value from the request straight through as the webapp name. The webapp name is one name, and not a path: one such as `"customers/foo"` names nothing in the directory, and is a `500`. Webapps that are kept in different directories differ in the first value: ```python SITES = { "foo.com": ("my_webapps/customers", "foo"), "bar.com": ("my_webapps/internal", "bar"), } def app_map(request): return SITES.get(request.host, SITES["bar.com"]) ```