How sanic-org/sanic works
Sanic is a Python 3.10+ async web framework and HTTP server. The repo is organized around a runtime core, a protocol/server layer, and a set of application-facing abstractions for routing, request handling, and lifecycle management.
1. Core application object
The central boundary is sanic.app.Sanic, backed by mixins under sanic/mixins/. This is where an app accumulates configuration, routes, middleware, signals, listeners, static handlers, and extension state. Most user-facing APIs ultimately register into this app object.
2. Request-to-response flow
Incoming traffic is converted into sanic.request objects, routed by sanic.router, passed through middleware and handlers, and returned as sanic.response objects. This is the main application execution path and the key diagram flow for request processing.
3. Routing and view dispatch
Routing is split between route registration and route matching. sanic.blueprints, sanic.blueprint_group, and sanic.views add structure for grouping handlers, class-based views, and versioned/mounted route sets. The router and these abstractions define how URL paths map to callables.
4. Middleware, signals, listeners, and startup hooks
Cross-cutting behavior is implemented in separate subsystems: sanic.middleware, sanic.signals, sanic/mixins/listeners.py, and sanic/mixins/startup.py. These provide ordered request/response interception, event-style hooks, and application lifecycle callbacks.
5. Server and protocol layer
The lower layer lives in sanic/server/ and sanic/http/. It handles socket setup, event loop integration, HTTP/1 processing, websockets, and TLS. The server layer is where application code is decoupled from transport concerns.
6. ASGI and deployment compatibility
sanic.asgi exposes ASGI compatibility so the framework can run under alternative ASGI servers. This makes the transport boundary explicit: the app can be served by Sanic’s own server stack or integrated into the broader ASGI ecosystem.
7. WebSocket and streaming support
WebSocket handling is first-class via sanic/server/protocols/websocket_protocol.py and sanic/server/websockets/. Streaming is also represented in sanic/http/stream.py and documented examples. These paths are separate from normal request/response handling and should be shown as specialized protocol flows.
8. CLI, worker lifecycle, and reload/daemon tooling
Operational control lives in sanic/cli/ and sanic/worker/. This includes app loading, daemonization, inspector mode, process management, reloading, restarts, and multi-worker serving. The CLI is the entry point that bridges user configuration to runtime server startup.
9. Configuration, logging, and runtime behavior
sanic.config, sanic/log.py, and sanic/logging/ centralize application settings and logging behavior. These modules influence server startup, debug/development mode, error reporting, and operational observability rather than request routing itself.
10. Error handling and HTTP utilities
Error translation is handled by sanic.exceptions, sanic/errorpages.py, and sanic/handlers/error.py. HTTP-specific helpers live in sanic/http/constants.py, sanic/headers.py, sanic/cookies/, and sanic/handlers/content_range.py / directory.py. These are support layers around the core request pipeline.
11. Static content and page rendering
Static file serving is built into the framework through sanic/mixins/static.py, sanic/pages/, and related handlers. This is a distinct boundary from dynamic routing because it resolves files/pages rather than executing app-defined handlers.
12. Type/model boundary and internal contracts
The sanic/models/ and sanic/types/ packages define typed interfaces for ASGI, protocol handlers, futures, server state, and shared context. These are internal contracts used to keep the server, app, and worker subsystems loosely coupled.
13. Documentation and developer portal
The repository includes a substantial docs system (docs/ and guide/) plus a separate Sanic-powered guide web app under guide/webapp/. This is not part of the runtime framework, but it is a meaningful secondary application with its own display, endpoint, and worker layers.
14. Tests and examples as architecture validation
tests/ exercises the framework across HTTP, ASGI, websockets, TLS, workers, static files, CLI, and reloader behavior. examples/ demonstrates the supported integration patterns and is useful for understanding the intended subsystem boundaries and data flows.
Overall, the architecture is a layered async framework: CLI and workers boot the server; the server/protocol layer turns sockets into HTTP/WebSocket events; the app/router/middleware stack converts those events into handler execution; and response/error/static utilities shape the output back to the client.
Main entry points: app.py Sanic app · server Server · router.py Router · tests Tests
Components 22
Core framework
Application, routing, request/response, and lifecycle abstractions.
- Sanic app · Central application object that collects routes, middleware, listeners, signals, and extensions.
sanic/app.py - App mixins · Reusable behaviors for routes, middleware, listeners, startup, static content, commands, and exceptions.
sanic/mixins - Router · Maps incoming paths and methods to handlers and named routes.
sanic/router.py - Request · HTTP request parsing and request-scoped data structures.
sanic/request - Response · Response construction and convenience APIs for outbound HTTP results.
sanic/response - Blueprints · Grouped and reusable route registration for modular applications.
sanic/blueprints.py - Views · Class-based handler dispatch and view composition.
sanic/views.py - Signals · Application events and signal dispatch for cross-cutting coordination.
sanic/signals.py - Middleware · Ordered request and response interception hooks.
sanic/middleware.py - Startup · Application initialization and startup error handling.
sanic/startup
Runtime stack
Server, protocol, worker, and transport handling.
- Server · Async server orchestration, event loop integration, runners, and socket setup.
sanic/server - Protocols · HTTP and websocket protocol adapters for the server layer.
sanic/server/protocols - HTTP stack · HTTP/1, HTTP/3, streaming, TLS, and related transport utilities.
sanic/http - WebSockets · WebSocket connection, framing, and implementation support.
sanic/server/websockets - Workers · Multi-worker serving, reload, restarts, daemon mode, and process management.
sanic/worker - ASGI bridge · ASGI compatibility boundary for alternative deployment environments.
sanic/asgi.py
Operations
CLI, configuration, logging, and startup behavior.
- CLI · Command-line app loading and runtime control entrypoints.
sanic/cli - Config & logging · Configuration, logging setup, log formatting, and operational defaults.
sanic/config.py
Documentation app
Repository docs plus the Sanic-powered guide site.
Connections 26
- Sanic app → App mixins: composes · The app is built from mixin-based capabilities.
- Sanic app → Router: registers to · Routes and named paths are accumulated into the router.
- Sanic app → Middleware: attaches · Middleware is registered on the app and applied during requests.
- Sanic app → Signals: emits · The app exposes signal/event hooks for extensions and lifecycle coordination.
- Sanic app → Startup: boots with · Startup routines initialize the application and validate readiness.
- Router → Views: dispatches to · Matched routes may resolve to class-based view handlers.
- Router → Request: routes · Routing operates on parsed request information.
- Request → Response: yields · Handlers transform requests into response objects.
- Middleware → Request: wraps · Request middleware can inspect and mutate inbound requests.
- Middleware → Response: wraps · Response middleware can adjust outbound responses.
- Server → Protocols: drives · The async server hosts HTTP and websocket protocol adapters.
- Protocols → HTTP stack: uses · HTTP protocol handling relies on HTTP parsing and streaming utilities.
- Protocols → WebSockets: upgrades to · WebSocket protocol handling delegates to websocket runtime support.
- Server → Workers: managed by · Serving can be coordinated through worker, reload, and process-management subsystems.
- CLI → Server: starts · The CLI is the primary entrypoint for launching the server stack.
- CLI → Workers: orchestrates · CLI commands delegate to worker lifecycle and process management.
- Config & logging → CLI: configures · Configuration and logging affect command behavior and runtime startup.
- Config & logging → Server: configures · Runtime settings influence server behavior and observability.
- ASGI bridge → Sanic app: adapts · ASGI compatibility exposes the app to alternative servers.
- Guide app → Sanic app: uses framework · The guide web application is itself built on Sanic.
- Docs site → Guide app: references · The docs and guide materials explain and support the guide application.
- Tests → Sanic app: verifies · Tests cover app behavior, routing, middleware, and lifecycle boundaries.
- Tests → Server: verifies · Tests exercise server, protocol, TLS, and worker behaviors.
- Tests → ASGI bridge: verifies · Tests cover ASGI compatibility paths.
- Examples → Router: demonstrates · Examples show route registration and dispatch patterns.
- Examples → WebSockets: demonstrates · Examples include WebSocket usage and streaming patterns.