Composing an application
Cylinder does not include a template engine, a database layer, or sessions. It gives you one mechanism for handing your own objects to your handlers, and that mechanism is enough to plug in whichever libraries you prefer.
The pattern is always the same: create the object once in cylinder_main.py, return it from app_map(),
and ask for it by name in any handler. Nothing is global, and nothing is hidden.
Extra parameters on main()
app_map() can return a third value: a dictionary of extra parameters. Every handler, hook, and error
handler in the webapp can then ask for any of them by name.
For example, to give every handler access to your application’s settings:
import cylinder
import waitress
config = {
"site_name": "My Site",
"support_email": "help@example.com",
}
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", {"config": config}
if __name__ == "__main__":
main()
Any page in webapp1 can now ask for config:
def main(response, config):
response.data = f"Welcome to {config['site_name']}"
return response
The handler does not import anything or reach for a global. What it depends on is visible in its signature,
and a test can call it with a different config.
Use this for objects your application creates: database session factories, template renderers, locks, clients for other services. Standard-library and third-party modules are better imported at the top of the handler file in the normal way.
An extra cannot have the name of a parameter that Cylinder passes itself: request, response, abort,
logger, remainder, e, or request_id. A request that app_map() returns one for gets a
plain 500, and the log names the extra.
app_map() itself can ask for request, response, logger, abort, and request_id, in any order. It
cannot ask for remainder, e, or the value of a placeholder, because it runs before any file has been
matched.
Configuration and environments
Cylinder treats configuration as ordinary Python. There is no settings file format to learn.
To load values from a .env file, read them once and pass them in:
import cylinder
import waitress
from dotenv import dotenv_values
config = dotenv_values(".env")
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", {"config": config}
if __name__ == "__main__":
main()
Because app_map() runs for every request, it can also make decisions per request, such as
serving a different webapp for each hostname.
The options on get_app() itself are few, and are listed in the reference.
HTML templates and Jinja2
Template rendering is added like any other dependency. Here is a minimal Jinja2 setup:
import cylinder
import waitress
import jinja2
jinja_env = jinja2.Environment(
loader=jinja2.FileSystemLoader("templates"),
autoescape=jinja2.select_autoescape(),
)
def render_template(template_name, **context):
return jinja_env.get_template(template_name).render(**context)
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", {"render_template": render_template}
if __name__ == "__main__":
main()
Templates are neither handlers nor content for visitors, so they go beside the webapp directory:
my_project
|-- cylinder_main.py
|-- /templates
|-- hello.html
|-- /my_webapps
|-- webapp1.page.get.py
webapp1.page.get.py:
def main(response, render_template):
response.content_type = "text/html; charset=utf-8"
return render_template("hello.html", name="Developer")
hello.html:
<!doctype html>
<html>
<body>
Hello, {{ name }}
</body>
</html>
Any other template engine fits the same way.
Databases and SQLAlchemy
Database setup is usually long enough to deserve its own module. With SQLAlchemy, define the engine and
session factory in db.py:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine("sqlite:///app.db")
SessionLocal = sessionmaker(engine)
Import it in cylinder_main.py and pass the session factory through app_map():
import cylinder
import waitress
import db
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", {"SessionLocal": db.SessionLocal}
if __name__ == "__main__":
main()
A handler asks for it and uses it:
from sqlalchemy import select
from models import User
def main(response, SessionLocal):
with SessionLocal() as session:
users = session.execute(select(User)).scalars().all()
return f"{len(users)} users found"
Define your models in a normal module such as models.py, and import them from handlers. Do not declare
them inside a handler file: handler files run on every request, as
Handlers explains.
Cleaning up after a request
Some resources need to be released when a request is over: a file, a database connection, a lock. Use
Werkzeug’s
response.call_on_close()
to register a function that runs once the response has been sent.
app_map(), hooks, and page handlers all receive response, so any of them can register cleanup:
def app_map(request, response):
connection = open_connection()
response.call_on_close(connection.close)
return "my_webapps", "webapp1", {"connection": connection}
The function runs after the response body has been sent, so a streaming response can keep using the resource while it generates output.
It runs however the request ends: a normal response,
abort(), a redirect, or an uncaught exception.You can register more than one function. They run in the order they were registered.
That includes a failure in
app_map()itself: a function it registered before raising still runs.
Sessions
Cylinder does not implement sessions, because no single design fits every application. Some frameworks store the whole session in a signed cookie, which scales easily and invites people to put sensitive data in the browser. Others keep the data on the server and send only an ID, which needs shared storage once there is more than one server.
Here is a complete server-side implementation. Session data lives in SQLite and the browser holds only an ID:
import cylinder
import waitress
import json
import secrets
import sqlite3
from collections import UserDict
def main():
app = cylinder.get_app(app_map)
waitress.serve(app, host="127.0.0.1", port=8080)
def app_map(request, response):
session = SessionDict(request.cookies.get("session_id"))
response.call_on_close(session.conn.close)
# should also set `secure=True` in production
response.set_cookie("session_id", session.uid, httponly=True)
return "my_webapps", "webapp1", {"session": session}
class SessionDict(UserDict):
def __init__(self, uid):
self.conn = sqlite3.connect("sessions.sqlite")
self.conn.execute(
"CREATE TABLE IF NOT EXISTS store (uid TEXT PRIMARY KEY, data TEXT)"
)
row = self.conn.execute(
"SELECT data FROM store WHERE uid=?", (uid,)
).fetchone()
# only keep an ID that this server stored; never adopt one the client made up
self.uid = uid if row else secrets.token_urlsafe(32)
super().__init__(json.loads(row[0]) if row else {})
def _save(self):
self.conn.execute(
"INSERT OR REPLACE INTO store VALUES (?, ?)",
(self.uid, json.dumps(self.data)),
)
self.conn.commit()
def __setitem__(self, key, value):
super().__setitem__(key, value)
self._save()
def __delitem__(self, key):
super().__delitem__(key)
self._save()
if __name__ == "__main__":
main()
A handler uses it like a dictionary:
def main(response, session):
visits = session.get("visits", 0)
session["visits"] = visits + 1
return f"visits: {visits}"
A few details:
The database connection is closed with
response.call_on_close().A
session_idcookie is only honored if that ID is already in the store. Anything else is replaced with a freshly generated ID, so a client cannot choose its own session ID. This prevents session fixation, where an attacker plants a known ID in a victim’s browser.The cookie is sent however the request ends. Cookies set before an
abort()or a redirect are kept on the response, so a visitor who is redirected to a login page on their first request still receives a session.The session is saved when you assign or delete a top-level key. Changing a nested value in place, such as
session["cart"].append(item), is not saved; assign the key again afterwards.
To scale beyond one server, keep the same shape and swap SQLite for shared storage such as PostgreSQL or Redis.
The g object
Users coming from Flask may know the
Flask g object, a place to keep
data for the duration of one request. Cylinder does not need a special object for this. Create a fresh
namespace for each request in app_map():
from types import SimpleNamespace
def app_map(request):
return "my_webapps", "webapp1", {"g": SimpleNamespace()}
An early hook can then leave something for the page handler:
# admin.hook.early.py
def main(request, response, g):
g.user = look_up_user(request)
return response
# admin/profile.page.get.py
def main(g):
return f"Signed in as {g.user}"
Because app_map() builds a new namespace for every request, nothing leaks from one request to the next.