CORS & lifecycle

Cross-origin requests and startup/teardown, in a couple of lines.

app.enable_cors(origins="*")                       class=com># or origins=["https://app.you.com"]
app.enable_cors(origins=["https://a.com"], credentials=True)

This adds the CORS headers to every response and answers preflight OPTIONS requests with a 204. Because middleware runs before routing, preflight works even for routes that only declare GET/POST.

Lifecycle

@app.on_startup
class=kw>def connect():
    app.state_db = open_pool()     class=com># runs once, before the first request

@app.on_shutdown
class=kw>def cleanup():
    app.state_db.close()

Startup runs when app.run() starts or on the first request (so it fires under gunicorn too); shutdown runs when the dev server stops. Use them for connection pools, warm caches or scheduled-job setup.