Operations

This page covers running a Cylinder app: what needs a restart, logging, streaming, and sharing state between requests. Deployment covers putting one into production.

Reloading and restarts

Cylinder has no development mode. Page handlers, hooks, and error handlers are loaded when a request arrives, so a change to one of those files takes effect on the next request, in development and in production alike. Cylinder sees a change as a different modification time or size, so a tool that replaces a file and keeps both will not be noticed.

The same goes for a file that is added, removed, or renamed, whether it is a handler, a hook, an error handler, or a static file. Cylinder finds every file in the listing of its directory. It reads a directory once, and reads it again when the modification time of the directory changes, which any of those does. A tool that puts that time back afterwards hides its changes until the next one, or until a restart.

For two seconds after a handler file or a directory changes, Cylinder reads it again on every request. Some filesystems keep times in whole seconds, and there a second change made in the same second leaves the time as it was, so a time that recent is not relied on.

Anything else is ordinary long-lived Python and needs a restart:

You changed

Restart needed

A page handler, hook, or error handler file

No

A static file

No

cylinder_main.py

Yes

A module imported by cylinder_main.py or by a handler file

Yes

An object created once and passed through app_map()

Yes

Loading at request time has a consequence for what you put at the top of a handler file, which Handlers explains.

Restarting automatically during development

You do not have to do those restarts by hand. Werkzeug, which is installed with Cylinder, has a development server that watches the project’s Python files and restarts the process when one changes. Use it while you work, and keep a production server for everything else:

# cylinder_main.py
import sys

import cylinder
import waitress
from werkzeug.serving import run_simple

def main():
    app = cylinder.get_app(app_map)
    if "--dev" in sys.argv:
        run_simple("127.0.0.1", 8080, app, use_reloader=True, exclude_patterns=["*/my_webapps/*"])
    else:
        waitress.serve(app, host="127.0.0.1", port=8080)

def app_map(request):
    return "my_webapps", "webapp1"

if __name__ == "__main__":
    main()

Start it with python cylinder_main.py --dev. Edit a module that a handler imports, and about a second later requests are answered by the new code.

A few things to know:

  • exclude_patterns leaves the handler files to Cylinder. The reloader watches every .py file in the project, not only imported modules. Without the pattern, saving a handler file restarts the process too, which is slower than Cylinder loading it on the next request and discards anything held in memory.

  • Only Python files are watched. To restart when another file changes, such as a configuration file read at startup, list it in extra_files.

  • cylinder_main.py runs twice at startup. The reloader runs it once to watch and once more, in a child process, to serve. Anything it does at startup, including Cylinder’s first log line, happens in both.

  • A module that fails to import stops the server. If an edit leaves a syntax error in a module that cylinder_main.py imports, the restart fails, the traceback is printed, and the process exits. Fix the error and start it again.

The Werkzeug server is for development only. Deployment covers production.

Logging

Every handler can ask for logger, a standard Python logger:

def main(response, logger):
    logger.info("building the report")
    return "done"

Cylinder also logs each request itself: a line when it arrives and a line with the status and duration when it completes. It logs the traceback of every uncaught exception at the ERROR level, whether or not an error handler answers for it, so a log kept at INFO or WARNING still has every traceback.

Request IDs

Every log record carries a request ID, so all the records for one request can be found together. By default Cylinder generates the ID. If your proxy or CDN already assigns one, tell Cylinder which header carries it:

app = cylinder.get_app(app_map, request_id_header="X-Request-ID")

Cloudflare, for example, uses Cf-Ray. If the header is missing from a request, Cylinder generates an ID for it.

Cylinder uses the value of the header as it arrives, so name a header only if your proxy sets it on every request and replaces one that a client sent. A header that reaches the app as the client wrote it lets the client choose the ID that its requests are logged under: the ID of someone else’s request, or any text it likes. Not every proxy replaces the header unless it is told to. In nginx, proxy_set_header X-Request-ID $request_id; does. With no proxy in front of the app, leave request_id_header out.

app_map() and every handler can ask for the ID as request_id. A 500 handler can give it to the visitor, so that the log lines of a report can be found:

# webapp1.500.py
def main(request_id):
    return f"Something went wrong. To report it, quote {request_id}."

With a request_id_header, the ID is the value of that header, so escape it as you would any other text that you put in HTML.

Where logs go

Two options on get_app() control output:

  • log_level sets the level. It defaults to logging.DEBUG, which writes how each request was routed: each hook and handler it was passed to, and how long each took. That is what you want while you build a site. logging.INFO writes one line for each request, and is a common choice in production.

  • log_handler sets the destination. It defaults to a StreamHandler writing to standard error. Pass any logging.Handler: a file handler, an SMTP handler, or logging.NullHandler() to silence logging.

To change the format, give the handler a formatter of its own before you pass it. A handler that has one keeps it, and one that has none is given Cylinder’s. This handler has the format that Cylinder gives:

import cylinder
import logging
import sys

log_handler = logging.StreamHandler(sys.stderr)
log_handler.setFormatter(logging.Formatter(
    "%(levelname)s %(timestamp)s %(filename)s:%(lineno)s %(request_id)s\n    %(message)s\n"
))
app = cylinder.get_app(app_map, log_handler=log_handler)

request_id and timestamp are fields that Cylinder adds to each record, so any formatter can use them. timestamp is the time of the record with its microseconds and its offset from UTC, such as 2026-01-31T14:33:05.983273-05:00.

Logging is set up once for the whole process. Every app logs through the same logger, named cylinder, so if get_app() is called more than once, the log_level and log_handler of the latest call apply to all of the apps. To serve several sites from one process, use one app and choose the site in app_map().

Sending the records to the root logger

get_app() sets up the cylinder logger by itself. It takes off any handler that was on that logger before, and keeps its records from going on to the root logger. So each line is written once, even where the root logger is set up afterwards, as waitress.serve() does when it calls logging.basicConfig().

To have the handlers of the root logger write Cylinder’s records instead, as a library that collects logs may have set up, give Cylinder a handler that writes nothing and let the records go on:

import logging

import cylinder

app = cylinder.get_app(app_map, log_handler=logging.NullHandler())
logging.getLogger("cylinder").propagate = True

The records are then in the format of those handlers. A record that is logged through logger.getChild() does not have the fields request_id and timestamp there.

A slow log handler

Cylinder writes each log record as it is logged, on the thread that serves the request. The lines of a request are written by the time its response is returned. With the default handler, or a file, writing a line takes a few tens of microseconds.

A handler that waits for something holds the response up while it waits. One that sends each record over the network, such as HTTPHandler, is the usual example. Give a handler like that a thread of its own, with the QueueHandler and QueueListener of the standard library:

import atexit
import logging
import logging.handlers
import queue

import cylinder

slow_handler = logging.handlers.HTTPHandler("logs.example.com", "/collect", method="POST", secure=True)
log_queue = queue.SimpleQueue()
listener = logging.handlers.QueueListener(log_queue, slow_handler)
listener.start()
atexit.register(listener.stop)  # sends what is still waiting when the process ends

log_handler = logging.handlers.QueueHandler(log_queue)
app = cylinder.get_app(app_map, log_handler=log_handler)

Cylinder gives the QueueHandler its format, or leaves it the formatter that you gave it. Each line is put together on the thread that logged it, with its request ID, and the slow handler only has to send it.

Streaming

Streaming a response

To send a response in pieces, without building the whole body in memory, assign an iterable such as a generator to response.response:

import time

def main(response):
    response.response = countdown()
    return response

def countdown():
    for number in range(10, 0, -1):
        time.sleep(1)
        yield f"{number}\n"

Each value the generator yields is sent to the client as it is produced.

Hooks still run in the normal way. They run before the body is sent, so a late hook can set headers on a streamed response but does not see its content.

If the generator uses a resource that must be released afterwards, register the cleanup with response.call_on_close(), which runs after the last piece has been sent.

A generator runs after Cylinder has answered. An exception in it is not a 500, because the status has been sent: no error handler runs, Cylinder does not log it, and the WSGI server reports it. The line that Cylinder logs for the request has the time until the body starts, and not the time to send it.

Streaming a request

A large upload can be read in pieces through request.stream, without loading it into memory:

def main(request, response):
    total_bytes = 0

    while True:
        chunk = request.stream.read(4096)
        if not chunk:
            break
        total_bytes += len(chunk)

    return f"received {total_bytes} bytes"

request.data, request.form, and request.get_json() read and buffer the whole body. To stream, use request.stream and none of those.

Thread safety

Thread safety in Cylinder works the way it does in any WSGI application. Requests may be handled at the same time, on threads or in separate processes, depending on the server. Waitress uses threads, and Many slow requests at once covers how many.

Cylinder itself keeps nothing of one request for the next. What it keeps between requests, the compiled code of handler files and the listings of directories, changes nothing that a request sees. If your application shares something between requests that is not safe to use concurrently, protect it. Pass a lock in through app_map():

import cylinder
import waitress
import threading

lock = threading.Lock()

def main():
    app = cylinder.get_app(app_map)
    waitress.serve(app, host="127.0.0.1", port=8080)

def app_map(request):
    return "my_webapps", "webapp1", {"lock": lock}

if __name__ == "__main__":
    main()

and use it where it is needed:

def main(response, lock):
    with lock:
        # do something that is not thread-safe
        pass
    return response

A lock created this way is shared by the threads of one process. A server that runs several worker processes gives each process its own copy, so state that every worker must see belongs in a database or cache.