Examples¶
Version 0.11 adds python -m examples.flask_migration: language-prefix
URL preprocessing/defaults, Blueprint app-wide hooks, namespaced config and JSON
cache control, without extra dependencies. See migration boundaries.
0.10+ adds python -m examples.async_ecosystem (disposable async SQLite, health, request IDs),
python -m examples.redis_sessions (dedicated Redis, shared sessions, CSRF), and
python -m examples.signals (app-scoped lifecycle events). Read setup and boundaries.
The 0.9+ project example
combines factories, nested components, SQLAlchemy, login/CSRF/roles, an admin UI,
and app commands. See setup and boundaries.
examples/server_modes.py exposes POST /upload; see performance for comparisons.
The 0.6.0 examples include csr_app.py (dependency-free browser CSR,
History API, fetch; open /app/) and vite_ssr.py (Python HTML with Vite CSS and
module preloads). Run higuma run examples.csr_app:create_app for the former.
For the latter, generate your own .vite/manifest.json with build.manifest: true,
set Vite's base to /build/, and point HIGUMA_FRONTEND_DIST to that build.
See frontend integration for development/production instructions.
See Flask compatibility for examples/flask_mount.py
(install higuma[compat]) and examples/flask_compat.py (g, sessions, flash,
URL generation, and CSRF; requires HIGUMA_SECRET_KEY).
security_tokens_roles.py additionally requires HIGUMA_DEMO_PASSWORD_HASH,
generated by PasswordHasher().hash(...). First GET /csrf-token, retain its
cookie and token, then POST with X-CSRF-Token and JSON containing
user_id="usr_example123" and your password. User IDs alone cannot log in.
examples/ is split by topic so each concept stays small and runnable.
| File | Covers | Runtime note |
|---|---|---|
app.py |
Routing, JSON, SSR templates | None |
blueprint_hooks.py |
Blueprints, config, request/lifecycle hooks | None |
routing_async.py |
Converters, multiple methods, async handlers | None |
modern_typed_api.py |
Annotated inputs, DI, response models, OpenAPI | None |
class_based_views.py |
View and MethodView | None |
streaming_sse.py |
Sync streaming, async SSE, background tasks | SSE ends after three events |
lifespan_background.py |
Async lifespan, app.state, background tasks | None |
responses_cookies_files.py |
Response types, cookies, file downloads | Serves a repository template |
websocket_chat.py |
JSON WebSocket echo | Needs a WebSocket client |
multipart_upload.py |
Safe file upload and persistence | Creates uploads/ on request |
mounted_apps.py |
WSGI and ASGI mounts | HTTP scopes only |
server_modes.py |
One application on native/ASGI/WSGI, async WS and SSE | ASGI extra is optional; WSGI is HTTP-only |
flask_mount.py |
Real Flask application through WSGI | Requires higuma[compat] |
flask_compat.py |
Contexts, sessions, flash, URLs, CSRF | Requires HIGUMA_SECRET_KEY |
flask_lifecycle.py |
Scoped Blueprint hooks, teardown, session writes from after callbacks | 0.7.0+, requires HIGUMA_SECRET_KEY |
openapi_api.py |
Legacy dataclass and OpenAPI metadata | Metadata-only form |
orm_blog.py |
SQLite ORM CRUD | Creates blog.sqlite3 at startup |
orm_fields.py |
Every ORM field, queries, and save | In-memory SQLite only |
authentication.py |
Login, CSRF, passwords, sessions | Requires a secret environment variable |
security_tokens_roles.py |
Signed tokens, roles, permissions | Requires a secret environment variable |
oauth_login.py |
Google OAuth with PKCE/state | Needs credentials and network access |
security_hardened.py |
CORS, hosts, headers, proxy, rate limit | Match proxy trust to your environment |
testing_client.py |
JSON, cookie jar, multipart tests | Runs assertions without a server |
supervised_app.py |
Multi-process Supervisor | Workers see the peer as loopback |
Basic execution¶
See Server interfaces. Try
uvicorn examples.server_modes:asgi_app --lifespan on --ws websockets-sansio,
python -m examples.server_modes --mode wsgi, or python -m examples.server_modes
for the same HTTP endpoints. The reference WSGI server is development-only.
Install from the repository root, then run an example:
python -m pip install -e .
python examples/routing_async.py
python examples/modern_typed_api.py
python examples/streaming_sse.py
python examples/testing_client.py
Factory-style examples also work through the CLI:
higuma run examples.orm_blog:create_app --port 8000
higuma run examples.blueprint_hooks:create_app --port 8000
higuma run examples.supervised_app:app --processes 4
Examples that use secrets¶
Set a random development value of at least 32 bytes. Do not save a real secret in shell history or the repository.
For the CSRF-protected login, first call GET /csrf to create a token in the
same client session. Send that value to POST /login in the X-CSRF-Token
header or _csrf_token form field.
The OAuth example additionally requires GOOGLE_CLIENT_ID and
GOOGLE_CLIENT_SECRET. Register its exact redirect URI with the provider. The
example makes real requests to Google.
Try request lifecycle hooks¶
Set a development secret as above, then start from the repository root:
GET /counter/ with a cookie-preserving client. The response contains count,
csrf_token, and a Server-Timing header. Send that token as X-CSRF-Token
when POSTing JSON {"increment": 2} to /counter/increment. Check
X-Counter-Saved: yes, then GET again to confirm persistence. Missing CSRF
tokens return 403; invalid increments return 400.
The same flow without starting a server:
from examples.flask_lifecycle import create_app
with create_app().test_client() as client:
token = client.get("/counter/").get_json()["csrf_token"]
response = client.post(
"/counter/increment", json={"increment": 2}, headers={"X-CSRF-Token": token}
)
assert response.get_json()["count"] == 2
assert response.headers["X-Counter-Saved"] == "yes"
assert client.get("/counter/").get_json()["count"] == 2
This is demo state in a signed cookie, not a durable or concurrency-safe database
counter. Production needs HTTPS, secure=True, appropriate host/proxy settings,
and external state management. See Flask compatibility and
Testing for ordering, early responses, and context boundaries.
Examples that create files¶
multipart_upload.py stores files in examples/uploads/ by default. Set
HIGUMA_UPLOAD_DIR to use a dedicated directory. The example normalizes names
and checks a 2 MiB limit and an extension allowlist; production systems should
also add content inspection, malware scanning, authorization, quotas, and
object storage.
orm_blog.py creates examples/blog.sqlite3. Run orm_fields.py for an ORM
exercise that uses only in-memory SQLite.
See Deployment for the production Supervisor topology. A directly exposed Supervisor cannot support client-IP rate limits or audit logs.