Static files

A webapp’s tree holds code, and it can hold files for the browser beside the code: images, stylesheets, scripts, and downloads. Such a file is sent to a client only where a page handler sends it. A file that no handler serves is never sent, so one that lands in the tree by mistake, such as a database or an export, is not public.

Serving files

Cylinder comes with the page handler that sends files. A handler file that uses it is one line:

from cylinder import static_file as main

Where that file goes says which files it serves, as it does for any page handler:

my_webapps
    |-- webapp1.page.get.py
    |-- /webapp1
        |-- assets.tree.get.py         serves every file under /assets
        |-- /assets
            |-- site.css
            |-- /img
                |-- logo.png
        |-- robots.txt.page.get.py     serves /robots.txt
        |-- robots.txt
        |-- notes.txt                  not served: no handler is named for it
  • A .tree. handler serves every file beneath its path. GET /assets/site.css returns the stylesheet and GET /assets/img/logo.png the image.

  • A .page. handler serves the one file it is named for. GET /robots.txt returns the text file.

  • The same line in webapp1.tree.get.py, beside the webapp’s directory, serves every file in the site. That is the model PHP made familiar. It makes every file you add public, apart from the handler files themselves, so prefer a directory that holds nothing but files for the browser.

The Content-Type comes from the file extension, in the table of Python’s standard mimetypes module. What the machine adds to that table is left out, so a file is sent with the same type on every machine that runs the same Python: the Windows registry can name a type that a browser refuses, as when a program has made .mjs text/plain. An extension that the table does not have is sent as application/octet-stream. Before Python 3.14 that goes for fonts, .woff2, .woff, .ttf, and .otf, which a browser loads as fonts all the same. To send another type, see Changing what is sent. A HEAD request returns the same headers without reading the file. Where the URL is not the path of a file, the response is a 404.

static_file is an ordinary page handler, so the rules for matching apply to it as they do to one you write. A page handler closer to the URL answers in its place, hooks run around it, and a POST to a file gets a 405, because the handler is named .get.

A linter that looks for unused imports reports the one line, because nothing in the file uses the name main. Ruff does, as F401, and ruff check --fix then deletes the import. What is left is a handler file with no main(), and every request that it served gets a 500. Say on the line that the import is meant:

from cylinder import static_file as main  # noqa: F401

Changing what is sent

A handler of your own can call static_file and change the response it returns. This one tells browsers to keep the files under /assets for a year, which suits files that have a version or a hash in their name:

# assets.tree.get.py
from cylinder import static_file

def main(request, response, abort):
    response = static_file(request, response, abort)
    response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
    return response

static_file aborts where it has no file to send, so the line after it runs only when a file is the answer. The 404 for an asset that is not deployed yet is not kept for a year.

A type that Python’s table does not have is set in the same way, with response.mimetype.

Caching and partial downloads

Cylinder sends an ETag and a Last-Modified header with every static file, and answers the requests that browsers and download tools build from them:

The client sends

Cylinder answers

If-None-Match or If-Modified-Since

304 Not Modified with no body, if the file is unchanged

Range: bytes=...

206 Partial Content with just that part of the file

A range that cannot be served

416 Range Not Satisfiable

If-Match without the file’s ETag

412 Precondition Failed, and no part of the file

If-Unmodified-Since

The same 412, if the file has changed since that date

A range cannot be served if it starts past the end of the file, if it is a last part that is longer than the file, if the request asks for more than one range, or if Werkzeug cannot read the header.

So a browser that already has a file downloads it again only when it has changed, a video can be seeked, and an interrupted download can resume.

If-Match is looked at before the other headers. So a tool that downloads a file in parts, each with the ETag of the first, gets a 412 for the next part once the file has changed, and not a part of another file. The 412 is an error like any other, with an error handler file if you write one. If-Match: * holds for any file that is there.

If-Unmodified-Since does the same with the date of the file, for a client that kept the Last-Modified and not the ETag. It counts only in a request with no If-Match, and only if it is a date.

Static files are sent with Cache-Control: no-cache. Despite the name, that allows caching: it tells the browser to check with the server before reusing its copy. The check costs one small 304 response, and it means an edited file is never shown stale. For files that never change at a given URL, the handler under Changing what is sent tells browsers to stop checking.

Cylinder tells whether a file has changed by its modification time and its size, as most web servers do. A file that is replaced by one with the same size and the same modification time looks unchanged, and browsers keep the copy they have. That can happen when a build gives every file a fixed time, as some container image builds do. If yours does, put a version or a hash of the content in the file’s name, so that a changed file has a new URL.

What a late hook sees for a static file

A late hook runs on every response under its directory, on errors and redirects as well as on files. Cylinder chooses the answer to a static file request when it serves the file, before the late hook runs. When a file is served, the hook sees one of five statuses:

Status

When

200

The whole file is sent

206

Part of the file is sent, for a Range request

304

The client’s copy is current, and no body is sent

416

The Range asked for cannot be served

412

An If-Match or If-Unmodified-Since failed

A hook that should apply whenever the file is the answer needs to accept 200, 206, and 304. One that checks for 200 alone stops applying once browsers have the file and start receiving 304.

Because the choice is already made, a late hook can change the headers of a 304, but changing the ETag or Last-Modified there does not change which of the five was chosen.

Pre-compressed assets

A file with a compression suffix is described as what is inside it, with the compression as its Content-Encoding:

File

Content-Type

Content-Encoding

script.js.br

text/javascript

br

site.css.gz

text/css

gzip

backup.tar.gz

application/x-tar

gzip

Before Python 3.12, script.js.br is application/javascript, which a browser runs all the same.

A browser decompresses such a response before using it. That lets you compress an asset once, ahead of time, and link to the compressed copy directly:

<script src="/assets/script.js.br"></script>

Every current browser accepts gzip, and accepts Brotli over HTTPS. Cylinder sends the file whether or not the client says it accepts the encoding, so link to a compressed copy only where you know it will be understood.

Compressed downloads

The same rule applies to a compressed file that is meant to be downloaded, where it is not what you want. A browser that downloads /backup.tar.gz removes the gzip layer in transit and saves a plain tar archive under a name that still ends in .tar.gz.

To serve compressed files as they are stored, keep them in their own directory, and serve it with a handler that describes them as plain gzip files:

        |-- downloads.tree.get.py
        |-- /downloads
            |-- backup.tar.gz

downloads.tree.get.py:

from cylinder import static_file

def main(request, response, abort):
    response = static_file(request, response, abort)
    if request.path.endswith(".gz"):
        response.content_type = "application/gzip"
        del response.headers["Content-Encoding"]
    return response

The file is still sent by static_file, so conditional requests and resumable downloads keep working. The handler is named .get, which also covers HEAD.

What is never served

Beneath a handler that serves files, three kinds of file are still not content, and Cylinder never sends them:

  • Handler files. A file with the name of a page handler, a hook, or an error handler, such as users.page.get.py, admin.hook.early.py, or webapp1.404.py. It is code that runs in the site, and its source is never sent. The name counts in any letter case, and so does any name that has the part which says what the file is, with .py anywhere after it. So a leftover copy such as admin.hook.early.py~, users.page.get.py.bak, or admin.hook.early - Copy.py is covered too.

  • Hidden files. Any path with a segment that starts with a dot, such as /.env or /.git/config.

  • Links. A symbolic link, or a junction on Windows, and everything reached through one. A link is passed over as code too: a handler or a hook that is a link does not run.

A request for one of them gets a 404, as a request for a file that is not there does.

Every other file beneath a handler that serves files is content, and anyone can ask for it. That goes for a Python file too: a page that runs Python in the browser, as one does with Brython, asks for main.py and the modules that it imports as it asks for a script. So a module that your handlers import is sent as well, where a handler serves the directory it is in.

Keep a file that is not content for visitors, such as a module of your own, a template, a database, or a configuration file, out of the directories that are served. Beside the webapp directory is the usual place for it. Composing an application shows the layouts, and Security lists what to check before deploying.