Server entrypoints¶
Use serve() to run a standalone server, or Server to control one inside an existing event loop. For startup, readiness, and shutdown examples, see Embedding.
serve¶
serve(
app: Application,
config: Config | None = None,
*,
factory: Literal[False] = False,
) -> None
serve(
app: ApplicationFactory,
config: Config | None = None,
*,
factory: Literal[True],
) -> None
serve(
app: Application | ApplicationFactory,
config: Config | None = None,
*,
factory: bool,
) -> None
serve(
app: Application | ApplicationFactory,
config: Config | None = None,
*,
factory: bool = False,
) -> None
Start the server. This is the primary programmatic entrypoint and matches the behavior of the h2corn CLI. For an in-process lifecycle, use Server.
On Unix, the call goes through the multi-worker supervisor, even for workers=1, so signal handling, inherited listeners, and worker lifecycle stay identical to the CLI. On Windows, a single in-process worker is used.
Blocks until the server is asked to shut down via one of:
| Signal | Effect |
|---|---|
SIGINT / SIGTERM | Graceful shutdown |
SIGHUP | Rolling worker reload |
SIGTTIN | Scale workers up by one |
SIGTTOU | Scale workers down by one |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app | Application | ApplicationFactory | An ASGI 3 application callable, or its synchronous zero-argument constructor when | required |
config | Config | None | Server configuration. Defaults to | None |
factory | bool | Treat | False |
Raises:
| Type | Description |
|---|---|
ValueError | If TLS PEM material, native configuration, or the configured user/group is invalid. |
OSError | If reading TLS files, creating the pidfile, or binding a listener socket fails. |
NotImplementedError | If a configured option (such as |
ModuleNotFoundError | If |
RuntimeError | If workers fail to start or exit repeatedly during supervision, or if lifespan startup/shutdown fails in-process. |
Examples:
examples/embedded.py shows the Server alternative: one worker inside an event loop you already own, rather than the supervisor this starts.
Server¶
Server(
app: Application,
config: Config | None = None,
*,
factory: Literal[False] = False,
)
Server(
app: ApplicationFactory,
config: Config | None = None,
*,
factory: Literal[True],
)
Server(
app: Application | ApplicationFactory,
config: Config | None = None,
*,
factory: bool,
)
Server(
app: Application | ApplicationFactory,
config: Config | None = None,
*,
factory: bool = False,
)
In-process, single-worker ASGI server.
Use this when you want to embed h2corn inside an existing event loop — for example, inside a test harness, a custom CLI, or an application that manages its own process model. For ordinary deployments, prefer serve, which goes through the multi-worker supervisor and matches the h2corn CLI.
The configured bind listeners are opened, lifespan startup runs, then the server processes requests until shutdown() is called or the surrounding task is cancelled.
workers must be 1. Supervisor-only options (max_requests, max_requests_jitter, and timeout_worker_healthcheck) are ignored with a warning.
With factory=True, app is a synchronous zero-argument constructor. Each effective request-serving loop calls it while running, once per serve generation, then starts that instance's ASGI lifespan on the same loop. Acquire asynchronous resources in lifespan and use lifespan="on" when startup acknowledgement is required. Factory errors always fail startup. Without the flag the supplied app is shared across request loops, so it must support their concurrent use.
Raises:
| Type | Description |
|---|---|
TypeError | If |
Examples:
examples/embedded.py runs one worker on an ephemeral port, sends a request through it, and shuts it down.
addressesproperty¶
addresses: tuple[str, ...]
Resolved listener addresses, in Config.bind string form.
Empty until serve() has bound the listeners. Unlike Config.bind, these carry the port the kernel actually assigned — bind to port 0 and read the address back from here:
Partial example:
server = Server(app, Config(bind=('127.0.0.1:0',)))
serving = asyncio.create_task(server.serve())
await server.wait_started()
print(server.addresses)
is_drainingproperty¶
is_draining: bool
Whether a previous serve() is still draining and releasing application resources.
A startup failure or an expired graceful budget can settle serve() while cancellation cleanup still owns the application and its loops. The same Server cannot serve() again until this becomes false. Lifespan shutdown follows actual request settlement, and private loop cleanup finishes before the generation releases.
serveasync¶
serve() -> None
Run the server until shutdown.
Binds the configured listeners, runs ASGI lifespan startup, processes requests, then runs lifespan shutdown after the native drain has fully released the application.
One lifecycle at a time, reusable afterwards: once a serve() call has fully finished, the same Server can serve() again with fresh shutdown state, while a second concurrent call raises RuntimeError. Cancelling the serve() task does not abort in-flight work — it triggers the same bounded graceful drain as shutdown() and re-raises the cancellation once that drain finishes or its budget runs out.
Cooperative asynchronous requests cannot hold the caller waiting past the drain budget. An application that catches CancelledError and never finishes may still retain the server after serve() raises RuntimeError; lifespan shutdown runs after those requests release, and the same Server cannot serve() again until then. A synchronous Python call that blocks the event-loop thread cannot be preempted in-process; use supervised workers when a hard kill bound is required.
The original serving or startup error remains the public failure if rollback also fails. A later cleanup failure is reported through the owning event loop's exception handler.
Raises:
| Type | Description |
|---|---|
NotImplementedError | If |
ValueError | If |
OSError | If reading TLS files, creating the pidfile, or binding a listener socket fails. |
RuntimeError | If this |
shutdown¶
shutdown() -> None
Initiate a graceful shutdown of an in-flight serve() call.
Safe to call from any thread or coroutine. Native acceptance stops immediately and cooperative tasks receive up to Config.timeout_graceful_shutdown seconds to finish. Arbitrary synchronous Python code cannot be preempted in-process; use supervised workers when a hard kill bound is required.
wait_startedasync¶
wait_started() -> None
Wait until this server is accepting connections.
Resolves once listeners are bound, lifespan startup has completed, and the server is accepting connections.
If startup fails, raises the startup error. Raises RuntimeError if the server is already shutting down.
A failure is delivered to callers waiting for that startup. A later call waits for the next serve generation rather than repeating a previous generation's error.
Raises:
| Type | Description |
|---|---|
RuntimeError | If the server is already shutting down, or if lifespan startup fails. |
BaseException | Any startup error raised while binding listeners, preparing TLS, or running lifespan startup. |
Partial example:
serving = asyncio.create_task(server.serve())
await server.wait_started()
SendAfterCloseError¶
Bases: builtins.OSError
Raised when an application sends on a stream the server has already closed.