Lauren logoLauren
← Home
Export this page

Guides

Step-by-step recipes for the things you'll do most often as you build a real Lauren application.

💉 Declaring an Injectable


The full lifecycle of an injectable — @injectable, scopes, function-based providers, lifecycle hooks, Protocols, multi-bindings.

⚙ Custom Providers


use_value, use_class, use_factory, use_existing, Token, and Inject — when @injectable isn't enough.

• Implicit Parameter Extraction


Path params, query params, and JSON bodies auto-detected from type annotations — no Path[…]/Query[…]/Json[…] boilerplate unless you need it.

• Validation


Native validation of dataclasses, TypedDict and NamedTuple (no pydantic needed), Annotated constraints, the structured issues 422 payload, ValidationPolicy and TypeCompiler.

• Pagination


OffsetPagination / PageNumberPagination / CursorPagination[C] parameters, Page[T] / CursorPage[T] responses, one envelope per app, RFC 8288 Link headers and signed, rotatable cursors.

• Custom Extractors


Build domain extractors like CurrentUser, TenantId, or RequestSpan and use them as parameter annotations.

• Pipes


Post-extraction transforms: validate, coerce, enrich, or replace extracted values before they reach your handler. Function-based, class-based, chainable, and DI-aware.

• File Uploads


UploadFile for single and multi-file multipart uploads, mixed forms with Form[T], optional files, Unicode filenames.

• File Responses & XML


await Response.file(...) for streamed downloads, browser-inline previews, and XML responses with Response.xml(...).

• Custom Responses


Subclass Response, preserve the concrete type through dispatch, and expose domain-specific response builders or streaming bodies.

• Response Contracts


status_code=, typed results (Created[T], NoContent), response_validation="filter" so internal fields never leave, @raises and json_fallback.

• Custom Guards


Authentication and authorization classes, route metadata, composition with class-level guards.

• Custom Middleware


The onion model, request-id propagation, response post-processing, error handling.

• Interceptors


AOP-style wrappers that run after routing and guards. Full ExecutionContext access: transform results, add headers, implement caching, catch errors, and read route metadata.

• Custom Exception Handlers


Catch domain errors at the right scope. Class-form (DI-injected) vs function-form. Global vs per-controller vs per-route.

• Debug Error Pages


debug=True in development: traceback, route chain and a redacted request summary for unhandled errors — loopback-only, refused in production.

• WebSockets


First-class WebSocket gateways: @ws_controller, @on_message, typed Pydantic frames, BroadcastGroup rooms, in-process testing.

• Server-Sent Events


One-way streaming with EventStream and ServerSentEvent: keep-alive heartbeats, Last-Event-ID resumability, AI text-streaming patterns.

• Typed Streaming


StreamingResponse[T] for outbound content-negotiated streams and Stream[T] for inbound typed iterators. SSE / NDJSON / JSON Lines, discriminated unions, bidirectional pipelines.

• Signals & Lifecycle Events


SignalBus for typed pub/sub: RequestComplete, StartupComplete, background-task signals. MRO dispatch, error isolation, metrics/tracing patterns.

• Health & Readiness Probes


HealthModule.for_root() with /health/live, /ready, /startup and a full report: @health_check methods with timeouts, single-flight and caching, the public lifecycle state, begin_draining() and Kubernetes manifests.

• Application Events


Typed domain events between modules: @on_event handlers discovered and validated at startup, EventBus / request-scoped EventPublisher, inline / concurrent / background delivery, priorities, error policies, after-commit emission, testing aids.

• Socket.IO


Engine.IO v4 / Socket.IO v5 adapter — @socketio_controller, @on_socketio_event, SocketIOConnection, automatic ACKs, DI injection.

• Circular Module Imports


Break circular import cycles between feature modules using ForwardRef("ClassName") in @module(imports=[...]) — resolved lazily at startup.

• OpenAPI Security from Guards


Annotate guard classes with @openapi_security({"SchemeName": []}) and Lauren populates the security field on every protected operation automatically — OR / AND semantics, OAuth2 scopes, explicit overrides.

• Proxy & Static Files


Run behind a reverse proxy with root_path, and serve static assets with StaticFilesModule.for_root("/static", directory="./public") — ETag caching, path traversal protection, multiple mounts.

⚡ Background Tasks


Fire-and-forget work after the response is sent. BackgroundTasks extractor, TaskHandle, sync/async callables, BackgroundTaskFailed signals, graceful-shutdown drain participation.

⏱ Scheduling & Hosted Services


@hosted_service loops started after @post_construct and stopped before @pre_destruct, with restarts and backoff; @interval / @cron / @run_once jobs with overlap, jitter, timeouts, misfire handling and a DI scope per run; SchedulerRegistry; ManualClock for tests.

• Commands & Scripts


The app's DI graph and lifecycle without HTTP: LaurenFactory.create_context, operation scopes, @command methods run with python -m lauren exec, the console, testing with ctx.run_command, workers and Kubernetes CronJobs.

• Sessions


Signed-cookie sessions: sessions=SessionConfig(...), session: Session injection, pluggable SessionStore (in-memory, stateless cookie, Redis), secure-by-default cookies, regenerate_id() / invalidate(), and startup-validated config.

• Stores & Caching


One async key-value Store (bounded MemoryStore in core) behind sessions, the Cache service (get_or_set with single-flight, tags, stale-while-revalidate), @cache_response with correct-by-default rules, @idempotent idempotency keys and Lock.

• Typed Configuration


Settings classes validated inside LaurenFactory.create: ConfigModule.for_root / for_feature, layered .env / TOML / environment sources, profiles, Secret[T] redaction, and one aggregated ConfigValidationError.

• Sync vs Async Handlers


Every handler may be def or async def. Sync handlers are automatically offloaded to a thread pool — no blocking the event loop.

• Custom Route Handlers


@staticmethod and @classmethod bindings, writing decorators with @functools.wraps, environment-conditional handler selection at class-body time, and the descriptor protocol for advanced use cases.

• DI with Data Model Types


Using @dataclass, Pydantic BaseModel, SQLAlchemy DeclarativeBase, and SQLModel with the DI container.

• Logging in Production


ConsoleLogger for development, JsonLogger for production, InMemoryLogger for tests. Log levels, env-var config, DI injection patterns, and coexistence with Python's logging module.