Skip to content

HTTP Server API Reference

Auto-generated API documentation for the HTTP Server module.

httpserver

Zero-dependency async HTTP server with decorator-based routing.

Part of zerodep: https://github.com/Oaklight/zerodep Copyright (c) 2026 Peng Ding. MIT License.

Async HTTP/1.1 server built on asyncio.start_server(). Supports decorator-based routing, JSON request/response, static file serving, streaming responses (SSE), and graceful shutdown.

Usage::

from httpserver import App, JSONResponse

app = App()

@app.route("/status")
async def status(request):
    return JSONResponse({"state": "idle"})

@app.route("/echo", methods=["POST"])
def echo(request):
    return JSONResponse(request.json())

app.run(host="127.0.0.1", port=8000)

HTTPException

Bases: Exception

HTTP error that maps to a specific status code.

Raise directly or via :func:abort to short-circuit request handling.

Parameters:

Name Type Description Default
status_code int

HTTP status code (e.g. 404, 500).

required
message str | None

Optional human-readable error message.

None
Source code in httpserver/httpserver.py
class HTTPException(Exception):
    """HTTP error that maps to a specific status code.

    Raise directly or via :func:`abort` to short-circuit request handling.

    Args:
        status_code: HTTP status code (e.g. 404, 500).
        message: Optional human-readable error message.
    """

    __slots__ = ("status_code", "message")

    def __init__(self, status_code: int, message: str | None = None):
        self.status_code = status_code
        self.message = message or _STATUS_REASONS.get(status_code, "Error")
        super().__init__(self.message)

State

Mutable namespace for storing arbitrary per-request data.

Middleware and handlers can attach attributes freely::

@app.before_request
async def start_timer(req):
    req.state.start_time = time.monotonic()

Uses __dict__-based attribute access (no __slots__), following the same pattern as Starlette's State.

Source code in httpserver/httpserver.py
class State:
    """Mutable namespace for storing arbitrary per-request data.

    Middleware and handlers can attach attributes freely::

        @app.before_request
        async def start_timer(req):
            req.state.start_time = time.monotonic()

    Uses ``__dict__``-based attribute access (no ``__slots__``), following
    the same pattern as Starlette's ``State``.
    """

    def __init__(self, **kwargs: Any) -> None:
        self.__dict__.update(kwargs)

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, State):
            return NotImplemented
        return self.__dict__ == other.__dict__

    def __repr__(self) -> str:
        items = ", ".join(f"{k}={v!r}" for k, v in self.__dict__.items())
        return f"State({items})"

Request

Parsed HTTP request.

Attributes:

Name Type Description
method

Uppercase HTTP method (GET, POST, ...).

path

URL path, percent-decoded.

query_string

Raw query string (without leading ?).

query_params dict[str, list[str]]

Parsed query string as {key: [values]}.

headers

Case-insensitive header dict (keys stored lowercase).

body

Raw request body bytes.

path_params dict[str, Any]

Parameters extracted from the route pattern.

client_addr

Client (host, port) tuple.

app

Reference to the :class:App instance handling this request.

state

Per-request :class:State namespace for arbitrary data.

Source code in httpserver/httpserver.py
class Request:
    """Parsed HTTP request.

    Attributes:
        method: Uppercase HTTP method (GET, POST, ...).
        path: URL path, percent-decoded.
        query_string: Raw query string (without leading ``?``).
        query_params: Parsed query string as ``{key: [values]}``.
        headers: Case-insensitive header dict (keys stored lowercase).
        body: Raw request body bytes.
        path_params: Parameters extracted from the route pattern.
        client_addr: Client ``(host, port)`` tuple.
        app: Reference to the :class:`App` instance handling this request.
        state: Per-request :class:`State` namespace for arbitrary data.
    """

    __slots__ = (
        "method",
        "path",
        "query_string",
        "query_params",
        "headers",
        "body",
        "path_params",
        "client_addr",
        "app",
        "state",
        "_json",
        "_cookies",
    )

    def __init__(
        self,
        method: str,
        path: str,
        query_string: str,
        headers: dict[str, str],
        body: bytes,
        client_addr: tuple[str, int],
        app: App | None = None,
    ):
        self.method = method
        self.path = path
        self.query_string = query_string
        self.query_params: dict[str, list[str]] = parse_qs(query_string)
        self.headers = headers
        self.body = body
        self.path_params: dict[str, Any] = {}
        self.client_addr = client_addr
        self.app = app
        self.state = State()
        self._json: Any = _SENTINEL
        self._cookies: Any = _SENTINEL

    @property
    def cookies(self) -> dict[str, str]:
        """Parse the Cookie request header into a ``{name: value}`` dict."""
        if self._cookies is _SENTINEL:
            raw = self.headers.get("cookie", "")
            if raw:
                sc = SimpleCookie()
                try:
                    sc.load(raw)
                except CookieError:
                    self._cookies = {}
                else:
                    self._cookies = {k: m.value for k, m in sc.items()}
            else:
                self._cookies = {}
        return self._cookies

    def json(self) -> Any:
        """Parse body as JSON (cached)."""
        if self._json is _SENTINEL:
            self._json = _json.loads(self.body)
        return self._json

    def text(self) -> str:
        """Decode body as UTF-8."""
        return self.body.decode("utf-8")

    def form(self) -> dict[str, list[str]]:
        """Parse URL-encoded form body."""
        return parse_qs(self.body.decode("utf-8"))

cookies property

Parse the Cookie request header into a {name: value} dict.

json()

Parse body as JSON (cached).

Source code in httpserver/httpserver.py
def json(self) -> Any:
    """Parse body as JSON (cached)."""
    if self._json is _SENTINEL:
        self._json = _json.loads(self.body)
    return self._json

text()

Decode body as UTF-8.

Source code in httpserver/httpserver.py
def text(self) -> str:
    """Decode body as UTF-8."""
    return self.body.decode("utf-8")

form()

Parse URL-encoded form body.

Source code in httpserver/httpserver.py
def form(self) -> dict[str, list[str]]:
    """Parse URL-encoded form body."""
    return parse_qs(self.body.decode("utf-8"))

Response

HTTP response with a fixed body.

Parameters:

Name Type Description Default
body bytes | str

Response body (bytes or str).

b''
status_code int

HTTP status code.

200
headers dict[str, str] | None

Extra response headers.

None
content_type str | None

Shorthand for Content-Type header.

None
Source code in httpserver/httpserver.py
class Response:
    """HTTP response with a fixed body.

    Args:
        body: Response body (bytes or str).
        status_code: HTTP status code.
        headers: Extra response headers.
        content_type: Shorthand for ``Content-Type`` header.
    """

    __slots__ = ("status_code", "headers", "body", "_cookie_headers")

    def __init__(
        self,
        body: bytes | str = b"",
        status_code: int = 200,
        headers: dict[str, str] | None = None,
        content_type: str | None = None,
    ):
        self.status_code = status_code
        self.headers: dict[str, str] = headers.copy() if headers else {}
        if isinstance(body, str):
            self.body = body.encode("utf-8")
        else:
            self.body = body
        if content_type is not None:
            self.headers["Content-Type"] = content_type
        self._cookie_headers: list[str] = []

    def set_cookie(
        self,
        name: str,
        value: str = "",
        *,
        max_age: int | None = None,
        expires: str | None = None,
        path: str | None = None,
        domain: str | None = None,
        secure: bool = False,
        httponly: bool = False,
        samesite: str | None = None,
    ) -> None:
        """Append a Set-Cookie header to the response.

        Args:
            name: Cookie name.
            value: Cookie value.
            max_age: Max age in seconds.
            expires: Expiry date string (HTTP date format).
            path: Cookie path scope.
            domain: Cookie domain scope.
            secure: Restrict to HTTPS.
            httponly: Restrict to HTTP (no JavaScript access).
            samesite: SameSite attribute (``"Strict"``, ``"Lax"``, or ``"None"``).
        """
        _append_set_cookie(
            self._cookie_headers,
            name,
            value,
            max_age=max_age,
            expires=expires,
            path=path,
            domain=domain,
            secure=secure,
            httponly=httponly,
            samesite=samesite,
        )

    def delete_cookie(
        self,
        name: str,
        *,
        path: str | None = None,
        domain: str | None = None,
    ) -> None:
        """Append a Set-Cookie header that expires the named cookie.

        Args:
            name: Cookie name to delete.
            path: Must match the path used when the cookie was set.
            domain: Must match the domain used when the cookie was set.
        """
        _append_delete_cookie(
            self._cookie_headers,
            name,
            path=path,
            domain=domain,
        )

    async def _write(self, writer: asyncio.StreamWriter) -> None:
        """Serialize and write the full HTTP response."""
        reason = _STATUS_REASONS.get(self.status_code, "Unknown")
        self.headers.setdefault("Content-Length", str(len(self.body)))
        self.headers.setdefault("Content-Type", "text/plain; charset=utf-8")
        self.headers.setdefault("Date", _http_date())
        self.headers.setdefault("Connection", "close")

        buf = bytearray()
        buf.extend(f"HTTP/1.1 {self.status_code} {reason}\r\n".encode("latin-1"))
        for k, v in self.headers.items():
            buf.extend(f"{k}: {v}\r\n".encode("latin-1"))
        for cookie_line in self._cookie_headers:
            buf.extend(f"Set-Cookie: {cookie_line}\r\n".encode("latin-1"))
        buf.extend(b"\r\n")
        buf.extend(self.body)
        writer.write(bytes(buf))
        await writer.drain()

Append a Set-Cookie header to the response.

Parameters:

Name Type Description Default
name str

Cookie name.

required
value str

Cookie value.

''
max_age int | None

Max age in seconds.

None
expires str | None

Expiry date string (HTTP date format).

None
path str | None

Cookie path scope.

None
domain str | None

Cookie domain scope.

None
secure bool

Restrict to HTTPS.

False
httponly bool

Restrict to HTTP (no JavaScript access).

False
samesite str | None

SameSite attribute ("Strict", "Lax", or "None").

None
Source code in httpserver/httpserver.py
def set_cookie(
    self,
    name: str,
    value: str = "",
    *,
    max_age: int | None = None,
    expires: str | None = None,
    path: str | None = None,
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: str | None = None,
) -> None:
    """Append a Set-Cookie header to the response.

    Args:
        name: Cookie name.
        value: Cookie value.
        max_age: Max age in seconds.
        expires: Expiry date string (HTTP date format).
        path: Cookie path scope.
        domain: Cookie domain scope.
        secure: Restrict to HTTPS.
        httponly: Restrict to HTTP (no JavaScript access).
        samesite: SameSite attribute (``"Strict"``, ``"Lax"``, or ``"None"``).
    """
    _append_set_cookie(
        self._cookie_headers,
        name,
        value,
        max_age=max_age,
        expires=expires,
        path=path,
        domain=domain,
        secure=secure,
        httponly=httponly,
        samesite=samesite,
    )

Append a Set-Cookie header that expires the named cookie.

Parameters:

Name Type Description Default
name str

Cookie name to delete.

required
path str | None

Must match the path used when the cookie was set.

None
domain str | None

Must match the domain used when the cookie was set.

None
Source code in httpserver/httpserver.py
def delete_cookie(
    self,
    name: str,
    *,
    path: str | None = None,
    domain: str | None = None,
) -> None:
    """Append a Set-Cookie header that expires the named cookie.

    Args:
        name: Cookie name to delete.
        path: Must match the path used when the cookie was set.
        domain: Must match the domain used when the cookie was set.
    """
    _append_delete_cookie(
        self._cookie_headers,
        name,
        path=path,
        domain=domain,
    )

JSONResponse

Bases: Response

Response serialized as JSON.

Parameters:

Name Type Description Default
data Any

Python object to serialize.

required
status_code int

HTTP status code.

200
headers dict[str, str] | None

Extra response headers.

None
Source code in httpserver/httpserver.py
class JSONResponse(Response):
    """Response serialized as JSON.

    Args:
        data: Python object to serialize.
        status_code: HTTP status code.
        headers: Extra response headers.
    """

    def __init__(
        self,
        data: Any,
        status_code: int = 200,
        headers: dict[str, str] | None = None,
    ):
        body = _json.dumps(data, ensure_ascii=False).encode("utf-8")
        super().__init__(
            body=body,
            status_code=status_code,
            headers=headers,
            content_type="application/json; charset=utf-8",
        )

StreamingResponse

HTTP response streamed from an async generator.

All streaming responses use Transfer-Encoding: chunked for maximum compatibility with reverse proxies and intermediaries. SSE (text/event-stream) responses additionally set Cache-Control: no-cache.

Parameters:

Name Type Description Default
generator AsyncIterator[bytes | str]

Async iterator yielding bytes or str chunks.

required
status_code int

HTTP status code.

200
headers dict[str, str] | None

Extra response headers.

None
content_type str

MIME type (default application/octet-stream).

'application/octet-stream'
background Callable[[], Any] | None

Optional callable invoked after the stream completes (including client disconnect). Accepts both sync and async callables. Exceptions are logged and suppressed.

None
disconnect_check_interval float | None

Seconds between client-disconnect checks while the generator is blocked. Defaults to 30.

None
Source code in httpserver/httpserver.py
class StreamingResponse:
    """HTTP response streamed from an async generator.

    All streaming responses use ``Transfer-Encoding: chunked`` for
    maximum compatibility with reverse proxies and intermediaries.
    SSE (``text/event-stream``) responses additionally set
    ``Cache-Control: no-cache``.

    Args:
        generator: Async iterator yielding ``bytes`` or ``str`` chunks.
        status_code: HTTP status code.
        headers: Extra response headers.
        content_type: MIME type (default ``application/octet-stream``).
        background: Optional callable invoked after the stream completes
            (including client disconnect).  Accepts both sync and async
            callables.  Exceptions are logged and suppressed.
        disconnect_check_interval: Seconds between client-disconnect
            checks while the generator is blocked.  Defaults to 30.
    """

    __slots__ = (
        "_generator",
        "status_code",
        "headers",
        "content_type",
        "background",
        "_cookie_headers",
        "_disconnect_check_interval",
    )

    def __init__(
        self,
        generator: AsyncIterator[bytes | str],
        status_code: int = 200,
        headers: dict[str, str] | None = None,
        content_type: str = "application/octet-stream",
        background: Callable[[], Any] | None = None,
        disconnect_check_interval: float | None = None,
    ):
        self._generator = generator
        self.status_code = status_code
        self.headers: dict[str, str] = headers.copy() if headers else {}
        self.content_type = content_type
        self.background = background
        self._cookie_headers: list[str] = []
        self._disconnect_check_interval = (
            disconnect_check_interval
            if disconnect_check_interval is not None
            else _STREAMING_DISCONNECT_CHECK_INTERVAL
        )

    def set_cookie(
        self,
        name: str,
        value: str = "",
        *,
        max_age: int | None = None,
        expires: str | None = None,
        path: str | None = None,
        domain: str | None = None,
        secure: bool = False,
        httponly: bool = False,
        samesite: str | None = None,
    ) -> None:
        """Append a Set-Cookie header to the response."""
        _append_set_cookie(
            self._cookie_headers,
            name,
            value,
            max_age=max_age,
            expires=expires,
            path=path,
            domain=domain,
            secure=secure,
            httponly=httponly,
            samesite=samesite,
        )

    def delete_cookie(
        self,
        name: str,
        *,
        path: str | None = None,
        domain: str | None = None,
    ) -> None:
        """Append a Set-Cookie header that expires the named cookie."""
        _append_delete_cookie(
            self._cookie_headers,
            name,
            path=path,
            domain=domain,
        )

    async def _write(self, writer: asyncio.StreamWriter) -> None:
        """Write status line, headers, then stream the body.

        Raises ``BrokenPipeError``, ``ConnectionResetError``, or
        ``ConnectionAbortedError`` on client disconnect.  The caller
        (``_handle_connection``) is responsible for handling these.
        Generator cleanup and the background callback still run via
        the ``finally`` block before the exception propagates.
        """
        reason = _STATUS_REASONS.get(self.status_code, "Unknown")
        is_sse = self.content_type.startswith("text/event-stream")

        self.headers["Content-Type"] = self.content_type
        self.headers.setdefault("Transfer-Encoding", "chunked")
        if is_sse:
            self.headers.setdefault("Cache-Control", "no-cache")
        self.headers.setdefault("Date", _http_date())
        self.headers.setdefault("Connection", "close")

        buf = bytearray()
        buf.extend(f"HTTP/1.1 {self.status_code} {reason}\r\n".encode("latin-1"))
        for k, v in self.headers.items():
            buf.extend(f"{k}: {v}\r\n".encode("latin-1"))
        for cookie_line in self._cookie_headers:
            buf.extend(f"Set-Cookie: {cookie_line}\r\n".encode("latin-1"))
        buf.extend(b"\r\n")
        writer.write(bytes(buf))
        await writer.drain()

        try:
            aiter = self._generator.__aiter__()
            is_closing = getattr(writer, "is_closing", None)
            while True:
                # Detect client disconnect between generator yields.
                # When the generator blocks on slow upstream I/O (e.g.
                # an LLM API producing the next SSE chunk), plain
                # ``async for`` never checks the writer state.  We
                # race the next-chunk coroutine against a periodic
                # disconnect check so CLOSE_WAIT connections don't
                # accumulate.
                if is_closing is not None and is_closing():
                    raise BrokenPipeError("client disconnected (detected)")

                next_coro = aiter.__anext__()
                if is_closing is None:
                    # Writer has no is_closing (e.g. mock) — fall back
                    # to plain await without disconnect detection.
                    try:
                        chunk = await next_coro
                    except StopAsyncIteration:
                        break
                else:
                    next_task = asyncio.ensure_future(next_coro)
                    try:
                        chunk = await _anext_or_disconnect(
                            next_task,
                            is_closing,
                            self._disconnect_check_interval,
                        )
                    except StopAsyncIteration:
                        break
                    except (
                        BrokenPipeError,
                        ConnectionResetError,
                        ConnectionAbortedError,
                    ):
                        next_task.cancel()
                        try:
                            await next_task
                        except (asyncio.CancelledError, Exception):
                            pass
                        raise

                if isinstance(chunk, str):
                    chunk = chunk.encode("utf-8")
                writer.write(f"{len(chunk):x}\r\n".encode("latin-1"))
                writer.write(chunk)
                writer.write(b"\r\n")
                await writer.drain()
            writer.write(b"0\r\n\r\n")
            await writer.drain()
        except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
            raise
        finally:
            aclose = getattr(self._generator, "aclose", None)
            if aclose is not None:
                try:
                    await aclose()
                except Exception:
                    logger.debug("Generator aclose failed", exc_info=True)
            if self.background is not None:
                try:
                    result = self.background()
                    if inspect.isawaitable(result):
                        await result
                except Exception:
                    logger.warning("Background callback failed", exc_info=True)

Append a Set-Cookie header to the response.

Source code in httpserver/httpserver.py
def set_cookie(
    self,
    name: str,
    value: str = "",
    *,
    max_age: int | None = None,
    expires: str | None = None,
    path: str | None = None,
    domain: str | None = None,
    secure: bool = False,
    httponly: bool = False,
    samesite: str | None = None,
) -> None:
    """Append a Set-Cookie header to the response."""
    _append_set_cookie(
        self._cookie_headers,
        name,
        value,
        max_age=max_age,
        expires=expires,
        path=path,
        domain=domain,
        secure=secure,
        httponly=httponly,
        samesite=samesite,
    )

Append a Set-Cookie header that expires the named cookie.

Source code in httpserver/httpserver.py
def delete_cookie(
    self,
    name: str,
    *,
    path: str | None = None,
    domain: str | None = None,
) -> None:
    """Append a Set-Cookie header that expires the named cookie."""
    _append_delete_cookie(
        self._cookie_headers,
        name,
        path=path,
        domain=domain,
    )

FileResponse

Bases: Response

Response serving a file from disk.

Parameters:

Name Type Description Default
path str | Path

Path to the file.

required
content_type str | None

MIME type (auto-detected from extension if None).

None
status_code int

HTTP status code.

200
Source code in httpserver/httpserver.py
class FileResponse(Response):
    """Response serving a file from disk.

    Args:
        path: Path to the file.
        content_type: MIME type (auto-detected from extension if ``None``).
        status_code: HTTP status code.
    """

    def __init__(
        self,
        path: str | Path,
        content_type: str | None = None,
        status_code: int = 200,
    ):
        file_path = Path(path)
        body = file_path.read_bytes()
        if content_type is None:
            guessed, _ = mimetypes.guess_type(str(file_path))
            content_type = guessed or "application/octet-stream"
        headers = {
            "Last-Modified": _http_date(os.path.getmtime(file_path)),
        }
        super().__init__(
            body=body,
            status_code=status_code,
            headers=headers,
            content_type=content_type,
        )

App

Async HTTP server application.

Request lifecycle::

before_request → route handler → after_request
  → on_response_started → write → on_response_completed
                            ↘ on_client_disconnect

Parameters:

Name Type Description Default
max_body_size int

Maximum request body size in bytes.

DEFAULT_MAX_BODY_SIZE
read_timeout float

Timeout for reading a single request (seconds).

DEFAULT_READ_TIMEOUT
keep_alive bool

Serve more than one request per connection. HTTP/1.1 connections stay open unless the client or the response asks to close; HTTP/1.0 stays open only when the client asks. Streaming responses always close. Defaults to True.

True
keep_alive_timeout float

Seconds an idle kept-alive connection may wait for the next request before the server closes it quietly. 0 or a negative value disables reuse, so the response never advertises a connection the server will not keep. Defaults to :data:DEFAULT_KEEP_ALIVE_TIMEOUT.

DEFAULT_KEEP_ALIVE_TIMEOUT
max_requests_per_connection int

Close a connection after this many requests even if the client would reuse it. Defaults to :data:DEFAULT_MAX_REQUESTS_PER_CONNECTION.

DEFAULT_MAX_REQUESTS_PER_CONNECTION
shutdown_grace_timeout float

Seconds a shutdown waits for requests that are already being handled before cancelling them. On Python 3.12+ Server.wait_closed() provides the same guarantee, but it returns immediately on 3.10/3.11, where the wait is needed. Defaults to :data:DEFAULT_SHUTDOWN_GRACE_TIMEOUT.

DEFAULT_SHUTDOWN_GRACE_TIMEOUT

Example::

app = App()

@app.get("/hello")
async def hello(request):
    return {"message": "Hello, world!"}

app.run()
Source code in httpserver/httpserver.py
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
class App:
    """Async HTTP server application.

    Request lifecycle::

        before_request → route handler → after_request
          → on_response_started → write → on_response_completed
                                    ↘ on_client_disconnect

    Args:
        max_body_size: Maximum request body size in bytes.
        read_timeout: Timeout for reading a single request (seconds).
        keep_alive: Serve more than one request per connection.  HTTP/1.1
            connections stay open unless the client or the response asks to
            close; HTTP/1.0 stays open only when the client asks.  Streaming
            responses always close.  Defaults to ``True``.
        keep_alive_timeout: Seconds an idle kept-alive connection may wait for
            the next request before the server closes it quietly.  ``0`` or a
            negative value disables reuse, so the response never advertises a
            connection the server will not keep.  Defaults to
            :data:`DEFAULT_KEEP_ALIVE_TIMEOUT`.
        max_requests_per_connection: Close a connection after this many
            requests even if the client would reuse it.  Defaults to
            :data:`DEFAULT_MAX_REQUESTS_PER_CONNECTION`.
        shutdown_grace_timeout: Seconds a shutdown waits for requests that
            are already being handled before cancelling them.  On Python
            3.12+ ``Server.wait_closed()`` provides the same guarantee, but
            it returns immediately on 3.10/3.11, where the wait is needed.
            Defaults to :data:`DEFAULT_SHUTDOWN_GRACE_TIMEOUT`.

    Example::

        app = App()

        @app.get("/hello")
        async def hello(request):
            return {"message": "Hello, world!"}

        app.run()
    """

    def __init__(
        self,
        *,
        max_body_size: int = DEFAULT_MAX_BODY_SIZE,
        read_timeout: float = DEFAULT_READ_TIMEOUT,
        keep_alive: bool = True,
        keep_alive_timeout: float = DEFAULT_KEEP_ALIVE_TIMEOUT,
        max_requests_per_connection: int = DEFAULT_MAX_REQUESTS_PER_CONNECTION,
        shutdown_grace_timeout: float = DEFAULT_SHUTDOWN_GRACE_TIMEOUT,
    ):
        self._routes: list[_Route] = []
        self._static_routes: list[tuple[str, str]] = []
        self._before_request_handlers: list[Callable[..., Any]] = []
        self._after_request_handlers: list[Callable[..., Any]] = []
        self._startup_handlers: list[Callable[[], Any]] = []
        self._shutdown_handlers: list[Callable[[], Any]] = []
        self._on_response_started_handlers: list[Callable[..., Any]] = []
        self._on_response_completed_handlers: list[Callable[..., Any]] = []
        self._on_client_disconnect_handlers: list[Callable[..., Any]] = []
        self._error_handlers: dict[int | type, Callable[..., Any]] = {}
        self._server: asyncio.Server | None = None
        self._shutdown_event: asyncio.Event | None = None
        self._loop: asyncio.AbstractEventLoop | None = None
        #: Connections currently waiting for their next request line.  A
        #: graceful shutdown closes these so ``Server.wait_closed()`` does
        #: not have to wait out ``keep_alive_timeout`` for every idle client
        #: (Python 3.12+ waits for all connections).
        self._idle_connections: set[asyncio.StreamWriter] = set()
        self.max_body_size = max_body_size
        self.read_timeout = read_timeout
        self.keep_alive = keep_alive
        self.keep_alive_timeout = keep_alive_timeout
        self.max_requests_per_connection = max_requests_per_connection
        self.shutdown_grace_timeout = shutdown_grace_timeout
        #: Connection handlers still running, so a shutdown can wait for a
        #: request that is already being handled (see
        #: :meth:`_drain_connection_tasks`).
        self._tasks: set[asyncio.Task[Any]] = set()
        self.port: int | None = None
        self.host: str | None = None

    # ── Route Registration ───────────────────────────────────────────────

    def route(
        self, url_pattern: str, methods: list[str] | None = None
    ) -> Callable[..., Any]:
        """Register a route handler.

        Args:
            url_pattern: URL pattern with optional parameters.
            methods: HTTP methods to handle (e.g. ``["GET", "POST"]``).
                Defaults to ``["GET"]``.

        Example::

            @app.route("/users/<int:id>", methods=["GET", "POST"])
            async def user(request, id):
                return {"id": id}
        """
        if methods is None:
            methods = ["GET"]

        def decorator(handler: Callable[..., Any]) -> Callable[..., Any]:
            pattern, param_names, converters = _compile_route(url_pattern)
            is_async = inspect.iscoroutinefunction(handler)
            self._routes.append(
                _Route(
                    methods=[m.upper() for m in methods],
                    pattern=pattern,
                    handler=handler,
                    is_async=is_async,
                    param_names=param_names,
                    param_converters=converters,
                )
            )
            return handler

        return decorator

    def get(self, path: str) -> Callable[..., Any]:
        """Shorthand for ``@app.route(path, methods=["GET"])``."""
        return self.route(path, methods=["GET"])

    def post(self, path: str) -> Callable[..., Any]:
        """Shorthand for ``@app.route(path, methods=["POST"])``."""
        return self.route(path, methods=["POST"])

    def put(self, path: str) -> Callable[..., Any]:
        """Shorthand for ``@app.route(path, methods=["PUT"])``."""
        return self.route(path, methods=["PUT"])

    def delete(self, path: str) -> Callable[..., Any]:
        """Shorthand for ``@app.route(path, methods=["DELETE"])``."""
        return self.route(path, methods=["DELETE"])

    def patch(self, path: str) -> Callable[..., Any]:
        """Shorthand for ``@app.route(path, methods=["PATCH"])``."""
        return self.route(path, methods=["PATCH"])

    def static(self, url_prefix: str, directory: str) -> None:
        """Register a directory for static file serving.

        Args:
            url_prefix: URL prefix (e.g. ``"/static"``).
            directory: Filesystem path to the directory.

        Example::

            app.static("/assets", "./public")
        """
        url_prefix = url_prefix.rstrip("/")
        abs_dir = os.path.abspath(directory)
        self._static_routes.append((url_prefix, abs_dir))

    # ── Middleware ────────────────────────────────────────────────────────

    def before_request(self, handler: Callable[..., Any]) -> Callable[..., Any]:
        """Register a before-request hook.

        The hook receives ``(request)`` and may return a ``Response`` to
        short-circuit the route handler.
        """
        self._before_request_handlers.append(handler)
        return handler

    def after_request(self, handler: Callable[..., Any]) -> Callable[..., Any]:
        """Register an after-request hook.

        The hook receives ``(request, response)`` and may return a new
        or modified ``Response``.
        """
        self._after_request_handlers.append(handler)
        return handler

    def errorhandler(self, code_or_exc: int | type) -> Callable[..., Any]:
        """Register an error handler.

        Args:
            code_or_exc: HTTP status code (int) or exception class.

        The handler receives ``(request, exception)`` and must return a
        ``Response``.
        """

        def decorator(handler: Callable[..., Any]) -> Callable[..., Any]:
            self._error_handlers[code_or_exc] = handler
            return handler

        return decorator

    # ── Lifespan Hooks ───────────────────────────────────────────────────

    def on_startup(self, handler: Callable[[], Any]) -> Callable[[], Any]:
        """Register a startup hook.

        The hook is called (with no arguments) before the server starts
        accepting connections.  Both sync and async callables are supported.
        Hooks run in registration order.

        If a startup hook raises, the error is logged and re-raised so the
        server does not start with failed initialization.

        Example::

            @app.on_startup
            async def init_pool():
                app.pool = await create_pool()
        """
        self._startup_handlers.append(handler)
        return handler

    def on_shutdown(self, handler: Callable[[], Any]) -> Callable[[], Any]:
        """Register a shutdown hook.

        The hook is called (with no arguments) after the server stops
        accepting connections.  Both sync and async callables are supported.
        Hooks run in **reverse** registration order (LIFO).

        If a shutdown hook raises, the error is logged and the remaining
        hooks still execute (best-effort cleanup).

        Example::

            @app.on_shutdown
            async def close_pool():
                await app.pool.close()
        """
        self._shutdown_handlers.append(handler)
        return handler

    # ── Request Lifecycle Signals ────────────────────────────────────────

    def on_response_started(self, handler: Callable[..., Any]) -> Callable[..., Any]:
        """Register a response-started signal.

        Fired just before the response is written to the client.  Useful
        for TTFB (time-to-first-byte) metrics.

        The handler receives ``(request, response)`` and its return value
        is ignored.  Both sync and async callables are supported.
        Exceptions are logged and suppressed.  Handlers run sequentially;
        keep them fast to avoid delaying the response write.

        Example::

            @app.on_response_started
            async def ttfb(request, response):
                request.state.response_start = time.monotonic()
        """
        self._on_response_started_handlers.append(handler)
        return handler

    def on_response_completed(self, handler: Callable[..., Any]) -> Callable[..., Any]:
        """Register a response-completed signal.

        Fired after the entire response body has been successfully sent
        to the client.  Useful for total transfer time and post-response
        logging.

        The handler receives ``(request, response)`` and its return value
        is ignored.  Both sync and async callables are supported.
        Exceptions are logged and suppressed.  Handlers run sequentially.

        Not fired when the client disconnects mid-response (see
        :meth:`on_client_disconnect` for that case).

        Example::

            @app.on_response_completed
            async def log_transfer(request, response):
                elapsed = time.monotonic() - request.state.response_start
                logger.info("Sent %d in %.3fs", response.status_code, elapsed)
        """
        self._on_response_completed_handlers.append(handler)
        return handler

    def on_client_disconnect(self, handler: Callable[..., Any]) -> Callable[..., Any]:
        """Register a client-disconnect signal.

        Fired when the client closes the connection during response
        delivery (broken pipe, connection reset).  Does not fire for
        disconnects during request dispatch (e.g. slow handler).
        Useful for cleanup, metrics, and cancelling expensive work.

        The handler receives ``(request)`` and its return value is ignored.
        Both sync and async callables are supported.  Exceptions are logged
        and suppressed.

        Example::

            @app.on_client_disconnect
            async def on_disconnect(request):
                logger.info("Client %s disconnected", request.client_addr)
        """
        self._on_client_disconnect_handlers.append(handler)
        return handler

    async def _fire_signal(
        self, name: str, handlers: list[Callable[..., Any]], *args: Any
    ) -> None:
        for hook in handlers:
            try:
                await _invoke(hook, *args)
            except Exception:
                logger.warning("%s hook failed", name, exc_info=True)

    # ── Request Dispatch ─────────────────────────────────────────────────

    def _match_route(
        self, request: Request
    ) -> tuple[_Route | None, re.Match[str] | None, bool]:
        """Find the first route matching the request path and method.

        Returns:
            (matched_route, regex_match, path_existed).  *path_existed* is
            True when a route matched the path but not the HTTP method.
        """
        # RFC 9110 §9.3.2: a server that supports GET must support HEAD.
        method = "GET" if request.method == "HEAD" else request.method
        path_existed = False
        for route in self._routes:
            m = route.pattern.match(request.path)
            if m is None:
                continue
            path_existed = True
            if "*" not in route.methods and method not in route.methods:
                continue
            return route, m, True
        return None, None, path_existed

    async def _invoke_route(
        self, route: _Route, match: re.Match[str], request: Request
    ) -> Response | StreamingResponse:
        """Extract path params, call the handler, return a response."""
        for name, converter, value in zip(
            route.param_names, route.param_converters, match.groups()
        ):
            request.path_params[name] = converter(value)

        try:
            result = await _invoke(route.handler, request, **request.path_params)
            return _coerce_response(result)
        except HTTPException as exc:
            return await self._handle_error(request, exc)
        except Exception as exc:
            logger.exception(
                "Unhandled exception in handler %s",
                getattr(route.handler, "__name__", repr(route.handler)),
            )
            return await self._handle_error(request, exc)

    async def _run_after_hooks(
        self, request: Request, response: Response | StreamingResponse
    ) -> Response | StreamingResponse:
        """Run after-request hooks, allowing them to replace the response."""
        for hook in self._after_request_handlers:
            hook_result = await _invoke(hook, request, response)
            if hook_result is not None:
                response = _coerce_response(hook_result)
        return response

    async def _dispatch(self, request: Request) -> Response | StreamingResponse:
        """Match a request to a route and invoke the handler."""
        # -- before_request hooks --
        for hook in self._before_request_handlers:
            result = await _invoke(hook, request)
            if result is not None:
                return _coerce_response(result)

        # -- Static file check --
        for prefix, directory in self._static_routes:
            file_resp = _resolve_static_file(request.path, prefix, directory)
            if file_resp is not None:
                return file_resp

        # -- Route matching --
        route, match, path_existed = self._match_route(request)

        if route is not None and match is not None:
            response = await self._invoke_route(route, match, request)
            return await self._run_after_hooks(request, response)

        # -- No route matched --
        if path_existed:
            allowed = sorted(
                {
                    m
                    for r in self._routes
                    if r.pattern.match(request.path)
                    for m in r.methods
                    if m != "*"
                }
            )
            exc = HTTPException(405, "Method Not Allowed")
            response = await self._handle_error(request, exc)
            if isinstance(response, Response):
                response.headers["Allow"] = ", ".join(allowed)
            return response

        exc = HTTPException(404, "Not Found")
        return await self._handle_error(request, exc)

    async def _handle_error(
        self, request: Request, exc: Exception
    ) -> Response | StreamingResponse:
        """Resolve an error into a response, consulting registered handlers."""
        if isinstance(exc, HTTPException):
            handler = self._error_handlers.get(exc.status_code)
            if handler is not None:
                result = await _invoke(handler, request, exc)
                return _coerce_response(result)

        for exc_cls, handler in self._error_handlers.items():
            if isinstance(exc_cls, type) and isinstance(exc, exc_cls):
                result = await _invoke(handler, request, exc)
                return _coerce_response(result)

        if isinstance(exc, HTTPException):
            return JSONResponse(
                {"error": exc.message},
                status_code=exc.status_code,
            )
        return JSONResponse(
            {"error": "Internal Server Error"},
            status_code=500,
        )

    # ── Connection Handling ───────────────────────────────────────────────

    @staticmethod
    async def _send_error_and_close(
        writer: asyncio.StreamWriter,
        response: Response | JSONResponse,
    ) -> None:
        """Write an error response to the client and close the connection.

        Swallows broken-pipe / reset errors that occur when the client has
        already disconnected.
        """
        try:
            await response._write(writer)
        except (BrokenPipeError, ConnectionResetError):
            pass
        writer.close()

    async def _handle_connection(
        self,
        reader: asyncio.StreamReader,
        writer: asyncio.StreamWriter,
    ) -> None:
        """Serve requests on one connection until it closes.

        A kept-alive connection is read, dispatched and written in a loop;
        the loop ends on ``Connection: close``, an HTTP/1.0 request that did
        not ask to stay, a streaming response, the request limit, an idle
        timeout, or a client disconnect.
        """
        peer = writer.get_extra_info("peername")
        client_addr = (peer[0], peer[1]) if peer else ("unknown", 0)
        served = 0
        task = asyncio.current_task()
        if task is not None:
            self._tasks.add(task)

        try:
            while True:
                idle_timeout = (
                    self.keep_alive_timeout
                    if served and self.keep_alive and self.keep_alive_timeout > 0
                    else None
                )
                # A connection is idle until a request line arrives: a probe
                # that says nothing, a half-sent line, and a socket still
                # sitting in the accept queue must not hold a shutdown for
                # the whole grace period (#220).  Once the request line is
                # in it leaves the set (``on_request_start``), so a body
                # that is still uploading is drained, not cut off.
                self._idle_connections.add(writer)
                try:
                    request_parts = await _read_request(
                        reader,
                        self.read_timeout,
                        self.max_body_size,
                        idle_timeout=idle_timeout,
                        on_request_start=lambda: self._idle_connections.discard(writer),
                    )
                except _ClientDisconnected:
                    break
                except Exception as exc:
                    await self._reject_read(exc, writer, client_addr)
                    break
                finally:
                    self._idle_connections.discard(writer)

                method, path, qs, headers, body, version = request_parts
                keep_alive = self._keep_alive_requested(version, headers, served + 1)
                served += 1
                try:
                    if not await self._serve_one(
                        method,
                        path,
                        qs,
                        headers,
                        body,
                        client_addr,
                        writer,
                        keep_alive,
                    ):
                        break
                except Exception:
                    logger.exception("Error writing response to %s", client_addr)
                    break
        finally:
            if task is not None:
                self._tasks.discard(task)
            try:
                writer.close()
                await writer.wait_closed()
            except Exception:
                pass

    async def _reject_read(
        self,
        exc: Exception,
        writer: asyncio.StreamWriter,
        client_addr: tuple,
    ) -> None:
        """Answer a failed request read, or close quietly on an idle timeout.

        A timeout before the request line is an idle kept-alive connection:
        the client simply stopped talking, so the connection closes without a
        response. A timeout after the request line means the client started a
        request and did not finish it, which gets a ``408``.

        Args:
            exc: The exception raised while reading the request.
            writer: The client connection.
            client_addr: Client address for logging.
        """
        if isinstance(exc, _IdleTimeout):
            logger.debug("Keep-alive idle timeout from %s", client_addr)
            return
        if isinstance(exc, asyncio.TimeoutError):
            logger.debug("Request read timed out from %s", client_addr)
        elif isinstance(exc, _BadRequest):
            logger.debug("Bad request from %s: %s", client_addr, exc)
        elif not isinstance(exc, (HTTPException, asyncio.IncompleteReadError)):
            logger.debug("Failed to read request from %s", client_addr, exc_info=True)
        elif isinstance(exc, asyncio.IncompleteReadError):
            logger.debug("Incomplete request body from %s", client_addr)
        await self._send_error_and_close(writer, _read_error_response(exc))

    @staticmethod
    def _connection_tokens(headers: dict[str, str]) -> set[str]:
        """Connection header tokens, looked up case-insensitively.

        Args:
            headers: Response or request headers.

        Returns:
            Lower-cased token set; empty when there is no ``Connection``
            header under any spelling.
        """
        tokens: set[str] = set()
        for key, value in headers.items():
            if key.lower() == "connection":
                tokens.update(
                    token.strip().lower() for token in value.split(",") if token.strip()
                )
        return tokens

    @staticmethod
    def _set_connection_header(headers: dict[str, str], value: str) -> None:
        """Set ``Connection`` under its canonical spelling, dropping variants.

        A caller that wrote ``headers={"connection": "close"}`` should get
        one header that says ``close``, not two that disagree.
        """
        for key in [key for key in headers if key.lower() == "connection"]:
            del headers[key]
        headers["Connection"] = value

    async def _serve_one(
        self,
        method: str,
        path: str,
        qs: str,
        headers: dict[str, str],
        body: bytes,
        client_addr: tuple,
        writer: asyncio.StreamWriter,
        keep_alive: bool,
    ) -> bool:
        """Dispatch and write one request.

        Args:
            method: Request method.
            path: Decoded request path.
            qs: Query string.
            headers: Lower-cased request headers.
            body: Request body.
            client_addr: Client address for logging.
            writer: The client connection.
            keep_alive: Whether the connection may be reused afterwards.

        Returns:
            ``True`` when the connection stays open for another request.
        """
        request = Request(
            method=method,
            path=path,
            query_string=qs,
            headers=headers,
            body=body,
            client_addr=client_addr,
            app=self,
        )
        logger.debug("%s %s from %s", method, path, client_addr)

        try:
            response = await self._dispatch(request)
        except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
            logger.debug("Connection reset by %s during dispatch", client_addr)
            return False

        # A HEAD response has no body (RFC 9110 §9.3.2), and 204/304 carry
        # none either.  Writing one would leave stray bytes in the stream and
        # poison the next request on a kept-alive connection (#210 review).
        if isinstance(response, Response) and (
            method == "HEAD" or response.status_code in (204, 304)
        ):
            if method == "HEAD":
                # Same header fields as the GET would have sent, including
                # Content-Length, but no body (RFC 9110 §9.3.2).
                response.headers.setdefault("Content-Length", str(len(response.body)))
            response.body = b""

        # A request that is already being handled still gets its response, but
        # the connection must not be reused after shutdown has begun.
        if (
            keep_alive
            and self._shutdown_event is not None
            and self._shutdown_event.is_set()
        ):
            keep_alive = False

        keep_alive = keep_alive and not isinstance(response, StreamingResponse)
        if keep_alive and "close" not in self._connection_tokens(response.headers):
            self._set_connection_header(response.headers, "keep-alive")
        else:
            keep_alive = False
            self._set_connection_header(response.headers, "close")

        await self._fire_signal(
            "on_response_started",
            self._on_response_started_handlers,
            request,
            response,
        )

        try:
            await response._write(writer)
        except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
            await self._fire_signal(
                "on_client_disconnect",
                self._on_client_disconnect_handlers,
                request,
            )
            logger.debug("Connection reset by %s during response", client_addr)
            return False

        await self._fire_signal(
            "on_response_completed",
            self._on_response_completed_handlers,
            request,
            response,
        )
        is_closing = getattr(writer, "is_closing", None)
        if is_closing is not None and is_closing():
            return False
        return keep_alive

    def _keep_alive_requested(
        self,
        version: str,
        headers: dict[str, str],
        served: int,
    ) -> bool:
        """Whether this request may be followed by another on the connection.

        Args:
            version: HTTP version from the request line.
            headers: Lower-cased request headers.
            served: Number of requests served including this one.

        Returns:
            ``True`` when the connection should stay open.
        """
        if (
            not self.keep_alive
            or self.keep_alive_timeout <= 0
            or served >= self.max_requests_per_connection
        ):
            return False
        tokens = {
            token.strip().lower()
            for token in headers.get("connection", "").split(",")
            if token.strip()
        }
        if "close" in tokens:
            return False
        if version == "HTTP/1.0":
            return "keep-alive" in tokens
        if not version.startswith("HTTP/1."):
            # Unknown or malformed protocol version: do not assume the
            # client can frame a second response.
            return False
        return True

    # ── Server Lifecycle ─────────────────────────────────────────────────

    async def _run_startup_hooks(self) -> None:
        """Run all registered startup hooks in registration order.

        If any hook raises, the exception is logged and re-raised so the
        server does not start with failed initialization.
        """
        for hook in self._startup_handlers:
            try:
                result = hook()
                if inspect.isawaitable(result):
                    await result
            except Exception:
                logger.error(
                    "Startup hook %r failed",
                    getattr(hook, "__name__", repr(hook)),
                    exc_info=True,
                )
                raise

    async def _run_shutdown_hooks(self) -> None:
        """Run all registered shutdown hooks in reverse registration order.

        Errors are logged and suppressed so that remaining hooks still
        execute (best-effort cleanup).
        """
        for hook in reversed(self._shutdown_handlers):
            try:
                result = hook()
                if inspect.isawaitable(result):
                    await result
            except Exception:
                logger.warning(
                    "Shutdown hook %r failed",
                    getattr(hook, "__name__", repr(hook)),
                    exc_info=True,
                )

    def run(
        self,
        host: str = DEFAULT_HOST,
        port: int = DEFAULT_PORT,
        *,
        socket: str | None = None,
        ssl_context: ssl.SSLContext | None = None,
        backlog: int | None = None,
        reuse_address: bool | None = None,
        reuse_port: bool | None = None,
    ) -> None:
        """Start the server (blocking).

        Args:
            host: Bind address (ignored when *socket* is set).
            port: Bind port. Use ``0`` for OS-assigned port (ignored when
                *socket* is set).
            socket: Unix domain socket path. When set, the server listens
                on a Unix socket instead of TCP. The socket file permissions
                are restricted to owner-only (``0o600``) after creation.
                Only available on Unix-like systems.
            ssl_context: An :class:`ssl.SSLContext` for TLS termination.
                When provided, the server accepts HTTPS connections.
                The caller is responsible for configuring the context
                (loading certs, setting verify mode, etc.).
            backlog: Maximum number of queued connections passed to
                :func:`asyncio.start_server`. ``None`` leaves the OS
                default (typically 128).
            reuse_address: Sets ``SO_REUSEADDR``. ``None`` lets asyncio
                decide (``True`` on non-Windows).
            reuse_port: Sets ``SO_REUSEPORT`` for multi-process load
                balancing. ``None`` lets asyncio decide (``False``).
        """
        try:
            asyncio.run(
                self._serve(
                    host,
                    port,
                    socket=socket,
                    ssl_context=ssl_context,
                    backlog=backlog,
                    reuse_address=reuse_address,
                    reuse_port=reuse_port,
                )
            )
        except KeyboardInterrupt:
            pass

    async def _serve(
        self,
        host: str,
        port: int,
        *,
        socket: str | None = None,
        ssl_context: ssl.SSLContext | None = None,
        backlog: int | None = None,
        reuse_address: bool | None = None,
        reuse_port: bool | None = None,
    ) -> None:
        """Internal async server loop."""
        self._shutdown_event = asyncio.Event()
        self._loop = asyncio.get_running_loop()
        self._socket_path: str | None = None

        try:
            # Run startup hooks before accepting connections
            await self._run_startup_hooks()

            if socket:
                server = await self._start_unix_socket(
                    socket, ssl_context=ssl_context, backlog=backlog
                )
            else:
                kwargs: dict[str, Any] = {}
                if backlog is not None:
                    kwargs["backlog"] = backlog
                if reuse_address is not None:
                    kwargs["reuse_address"] = reuse_address
                if reuse_port is not None:
                    kwargs["reuse_port"] = reuse_port
                server = await asyncio.start_server(
                    self._handle_connection,
                    host,
                    port,
                    ssl=ssl_context,
                    **kwargs,
                )
                addrs = (
                    server.sockets[0].getsockname() if server.sockets else (host, port)
                )
                self.host = addrs[0]
                self.port = addrs[1]
                scheme = "https" if ssl_context else "http"
                logger.info("Serving on %s://%s:%d", scheme, self.host, self.port)

            self._server = server

            loop = asyncio.get_running_loop()
            if sys.platform != "win32":
                for sig in (signal.SIGINT, signal.SIGTERM):
                    loop.add_signal_handler(sig, self._shutdown_event.set)

            async with server:
                await self._shutdown_event.wait()
                logger.info("Shutting down server")
                # Stop accepting first, then let in-flight requests finish.
                # On 3.12+ ``wait_closed()`` waits for connections; on
                # 3.10/3.11 it returns immediately, so the drain is what
                # keeps the handler tasks from being cancelled by
                # ``asyncio.run``.
                server.close()
                self._close_idle_connections()
                if self._socket_path:
                    self._cleanup_socket()
                await self._drain_connection_tasks()
        finally:
            # Run shutdown hooks after server stops accepting connections
            await self._run_shutdown_hooks()

    async def _start_unix_socket(
        self,
        socket_path: str,
        *,
        ssl_context: ssl.SSLContext | None = None,
        backlog: int | None = None,
    ) -> asyncio.Server:
        """Start listening on a Unix domain socket.

        Handles stale socket cleanup, permission hardening (``0o600``),
        and registers the path for shutdown cleanup.

        Args:
            socket_path: Path for the Unix domain socket file.
            ssl_context: Optional :class:`ssl.SSLContext` for TLS over
                the Unix socket.
            backlog: Maximum number of queued connections. ``None``
                leaves the OS default.

        Returns:
            The ``asyncio.Server`` instance.

        Raises:
            SystemExit: If the path exists but is not a socket, or the
                parent directory does not exist.
        """
        import stat as stat_mod

        path = os.path.realpath(socket_path)

        # Remove stale socket if present
        if os.path.exists(path):
            try:
                st = os.stat(path)
                if stat_mod.S_ISSOCK(st.st_mode):
                    os.unlink(path)
                    logger.info("Removed stale socket: %s", path)
                else:
                    logger.error("Socket path exists and is not a socket: %s", path)
                    sys.exit(1)
            except OSError as exc:
                logger.error("Cannot remove stale socket %s: %s", path, exc)
                sys.exit(1)

        # Ensure parent directory exists
        parent = os.path.dirname(path)
        if not os.path.isdir(parent):
            logger.error("Socket parent directory does not exist: %s", parent)
            sys.exit(1)

        kwargs: dict[str, Any] = {}
        if backlog is not None:
            kwargs["backlog"] = backlog
        server = await asyncio.start_unix_server(
            self._handle_connection,
            path=path,
            ssl=ssl_context,
            **kwargs,
        )

        # Restrict permissions to owner-only
        if os.path.exists(path):
            os.chmod(path, 0o600)

        self._socket_path = path
        scheme = "https+unix" if ssl_context else "unix"
        logger.info("Serving on %s:%s (mode 0600)", scheme, path)
        return server

    def _cleanup_socket(self) -> None:
        """Remove the Unix socket file on shutdown."""
        if self._socket_path and os.path.exists(self._socket_path):
            try:
                os.unlink(self._socket_path)
                logger.info("Removed socket: %s", self._socket_path)
            except OSError:
                pass

    async def _drain_connection_tasks(self) -> None:
        """Wait for connection handlers that are still serving a request.

        Idle kept-alive connections have already been closed, and a request
        that completes after shutdown started is answered with
        ``Connection: close``, so every remaining task is finishing an
        in-flight request (or about to observe the closed socket).  The wait
        is bounded by ``shutdown_grace_timeout``; anything still running is
        cancelled, because an unresponsive client must not block exit.
        """
        current = asyncio.current_task()
        tasks = [
            task for task in self._tasks if task is not current and not task.done()
        ]
        if not tasks:
            return
        _done, pending = await asyncio.wait(tasks, timeout=self.shutdown_grace_timeout)
        for task in pending:
            logger.warning(
                "Cancelling a connection handler that outlived the shutdown "
                "grace period (%.1fs)",
                self.shutdown_grace_timeout,
            )
            task.cancel()

    def _close_idle_connections(self) -> None:
        """Close connections that are waiting for another request.

        A connection is idle while it waits for a request line: a
        kept-alive one until ``keep_alive_timeout`` expires, and a
        brand-new one until ``read_timeout`` does.  Since Python 3.12,
        ``Server.wait_closed()`` waits for every open connection, so leaving
        either open would hold a graceful shutdown for the idle window — or
        for ``shutdown_grace_timeout`` in the drain.  Requests that have
        been read are not idle: their handler finishes and closes its own
        writer.
        """
        writers = list(self._idle_connections)
        self._idle_connections.clear()
        for writer in writers:
            try:
                writer.close()
            except Exception:  # pragma: no cover - already closed
                pass

    def shutdown(self) -> None:
        """Request a graceful server shutdown.

        Safe to call from any thread or from a request handler.
        """
        if self._shutdown_event is None or self._loop is None:
            return
        if self._loop.is_closed():
            # Already stopped; a repeated shutdown is a no-op rather than an
            # ``Event loop is closed`` error from ``call_soon_threadsafe``.
            return
        try:
            self._loop.call_soon_threadsafe(self._shutdown_event.set)
            # Wake idle kept-alive connections so a host that waits for them
            # (``Server.wait_closed()`` on 3.12+) is not held up by the idle
            # window.  ``_serve`` does the same for signal-driven shutdowns.
            self._loop.call_soon_threadsafe(self._close_idle_connections)
        except RuntimeError:  # pragma: no cover - loop closed mid-call
            # The loop can finish between the ``is_closed()`` check and the
            # call when shutdown races the server thread's exit.
            pass

route(url_pattern, methods=None)

Register a route handler.

Parameters:

Name Type Description Default
url_pattern str

URL pattern with optional parameters.

required
methods list[str] | None

HTTP methods to handle (e.g. ["GET", "POST"]). Defaults to ["GET"].

None

Example::

@app.route("/users/<int:id>", methods=["GET", "POST"])
async def user(request, id):
    return {"id": id}
Source code in httpserver/httpserver.py
def route(
    self, url_pattern: str, methods: list[str] | None = None
) -> Callable[..., Any]:
    """Register a route handler.

    Args:
        url_pattern: URL pattern with optional parameters.
        methods: HTTP methods to handle (e.g. ``["GET", "POST"]``).
            Defaults to ``["GET"]``.

    Example::

        @app.route("/users/<int:id>", methods=["GET", "POST"])
        async def user(request, id):
            return {"id": id}
    """
    if methods is None:
        methods = ["GET"]

    def decorator(handler: Callable[..., Any]) -> Callable[..., Any]:
        pattern, param_names, converters = _compile_route(url_pattern)
        is_async = inspect.iscoroutinefunction(handler)
        self._routes.append(
            _Route(
                methods=[m.upper() for m in methods],
                pattern=pattern,
                handler=handler,
                is_async=is_async,
                param_names=param_names,
                param_converters=converters,
            )
        )
        return handler

    return decorator

get(path)

Shorthand for @app.route(path, methods=["GET"]).

Source code in httpserver/httpserver.py
def get(self, path: str) -> Callable[..., Any]:
    """Shorthand for ``@app.route(path, methods=["GET"])``."""
    return self.route(path, methods=["GET"])

post(path)

Shorthand for @app.route(path, methods=["POST"]).

Source code in httpserver/httpserver.py
def post(self, path: str) -> Callable[..., Any]:
    """Shorthand for ``@app.route(path, methods=["POST"])``."""
    return self.route(path, methods=["POST"])

put(path)

Shorthand for @app.route(path, methods=["PUT"]).

Source code in httpserver/httpserver.py
def put(self, path: str) -> Callable[..., Any]:
    """Shorthand for ``@app.route(path, methods=["PUT"])``."""
    return self.route(path, methods=["PUT"])

delete(path)

Shorthand for @app.route(path, methods=["DELETE"]).

Source code in httpserver/httpserver.py
def delete(self, path: str) -> Callable[..., Any]:
    """Shorthand for ``@app.route(path, methods=["DELETE"])``."""
    return self.route(path, methods=["DELETE"])

patch(path)

Shorthand for @app.route(path, methods=["PATCH"]).

Source code in httpserver/httpserver.py
def patch(self, path: str) -> Callable[..., Any]:
    """Shorthand for ``@app.route(path, methods=["PATCH"])``."""
    return self.route(path, methods=["PATCH"])

static(url_prefix, directory)

Register a directory for static file serving.

Parameters:

Name Type Description Default
url_prefix str

URL prefix (e.g. "/static").

required
directory str

Filesystem path to the directory.

required

Example::

app.static("/assets", "./public")
Source code in httpserver/httpserver.py
def static(self, url_prefix: str, directory: str) -> None:
    """Register a directory for static file serving.

    Args:
        url_prefix: URL prefix (e.g. ``"/static"``).
        directory: Filesystem path to the directory.

    Example::

        app.static("/assets", "./public")
    """
    url_prefix = url_prefix.rstrip("/")
    abs_dir = os.path.abspath(directory)
    self._static_routes.append((url_prefix, abs_dir))

before_request(handler)

Register a before-request hook.

The hook receives (request) and may return a Response to short-circuit the route handler.

Source code in httpserver/httpserver.py
def before_request(self, handler: Callable[..., Any]) -> Callable[..., Any]:
    """Register a before-request hook.

    The hook receives ``(request)`` and may return a ``Response`` to
    short-circuit the route handler.
    """
    self._before_request_handlers.append(handler)
    return handler

after_request(handler)

Register an after-request hook.

The hook receives (request, response) and may return a new or modified Response.

Source code in httpserver/httpserver.py
def after_request(self, handler: Callable[..., Any]) -> Callable[..., Any]:
    """Register an after-request hook.

    The hook receives ``(request, response)`` and may return a new
    or modified ``Response``.
    """
    self._after_request_handlers.append(handler)
    return handler

errorhandler(code_or_exc)

Register an error handler.

Parameters:

Name Type Description Default
code_or_exc int | type

HTTP status code (int) or exception class.

required

The handler receives (request, exception) and must return a Response.

Source code in httpserver/httpserver.py
def errorhandler(self, code_or_exc: int | type) -> Callable[..., Any]:
    """Register an error handler.

    Args:
        code_or_exc: HTTP status code (int) or exception class.

    The handler receives ``(request, exception)`` and must return a
    ``Response``.
    """

    def decorator(handler: Callable[..., Any]) -> Callable[..., Any]:
        self._error_handlers[code_or_exc] = handler
        return handler

    return decorator

on_startup(handler)

Register a startup hook.

The hook is called (with no arguments) before the server starts accepting connections. Both sync and async callables are supported. Hooks run in registration order.

If a startup hook raises, the error is logged and re-raised so the server does not start with failed initialization.

Example::

@app.on_startup
async def init_pool():
    app.pool = await create_pool()
Source code in httpserver/httpserver.py
def on_startup(self, handler: Callable[[], Any]) -> Callable[[], Any]:
    """Register a startup hook.

    The hook is called (with no arguments) before the server starts
    accepting connections.  Both sync and async callables are supported.
    Hooks run in registration order.

    If a startup hook raises, the error is logged and re-raised so the
    server does not start with failed initialization.

    Example::

        @app.on_startup
        async def init_pool():
            app.pool = await create_pool()
    """
    self._startup_handlers.append(handler)
    return handler

on_shutdown(handler)

Register a shutdown hook.

The hook is called (with no arguments) after the server stops accepting connections. Both sync and async callables are supported. Hooks run in reverse registration order (LIFO).

If a shutdown hook raises, the error is logged and the remaining hooks still execute (best-effort cleanup).

Example::

@app.on_shutdown
async def close_pool():
    await app.pool.close()
Source code in httpserver/httpserver.py
def on_shutdown(self, handler: Callable[[], Any]) -> Callable[[], Any]:
    """Register a shutdown hook.

    The hook is called (with no arguments) after the server stops
    accepting connections.  Both sync and async callables are supported.
    Hooks run in **reverse** registration order (LIFO).

    If a shutdown hook raises, the error is logged and the remaining
    hooks still execute (best-effort cleanup).

    Example::

        @app.on_shutdown
        async def close_pool():
            await app.pool.close()
    """
    self._shutdown_handlers.append(handler)
    return handler

on_response_started(handler)

Register a response-started signal.

Fired just before the response is written to the client. Useful for TTFB (time-to-first-byte) metrics.

The handler receives (request, response) and its return value is ignored. Both sync and async callables are supported. Exceptions are logged and suppressed. Handlers run sequentially; keep them fast to avoid delaying the response write.

Example::

@app.on_response_started
async def ttfb(request, response):
    request.state.response_start = time.monotonic()
Source code in httpserver/httpserver.py
def on_response_started(self, handler: Callable[..., Any]) -> Callable[..., Any]:
    """Register a response-started signal.

    Fired just before the response is written to the client.  Useful
    for TTFB (time-to-first-byte) metrics.

    The handler receives ``(request, response)`` and its return value
    is ignored.  Both sync and async callables are supported.
    Exceptions are logged and suppressed.  Handlers run sequentially;
    keep them fast to avoid delaying the response write.

    Example::

        @app.on_response_started
        async def ttfb(request, response):
            request.state.response_start = time.monotonic()
    """
    self._on_response_started_handlers.append(handler)
    return handler

on_response_completed(handler)

Register a response-completed signal.

Fired after the entire response body has been successfully sent to the client. Useful for total transfer time and post-response logging.

The handler receives (request, response) and its return value is ignored. Both sync and async callables are supported. Exceptions are logged and suppressed. Handlers run sequentially.

Not fired when the client disconnects mid-response (see :meth:on_client_disconnect for that case).

Example::

@app.on_response_completed
async def log_transfer(request, response):
    elapsed = time.monotonic() - request.state.response_start
    logger.info("Sent %d in %.3fs", response.status_code, elapsed)
Source code in httpserver/httpserver.py
def on_response_completed(self, handler: Callable[..., Any]) -> Callable[..., Any]:
    """Register a response-completed signal.

    Fired after the entire response body has been successfully sent
    to the client.  Useful for total transfer time and post-response
    logging.

    The handler receives ``(request, response)`` and its return value
    is ignored.  Both sync and async callables are supported.
    Exceptions are logged and suppressed.  Handlers run sequentially.

    Not fired when the client disconnects mid-response (see
    :meth:`on_client_disconnect` for that case).

    Example::

        @app.on_response_completed
        async def log_transfer(request, response):
            elapsed = time.monotonic() - request.state.response_start
            logger.info("Sent %d in %.3fs", response.status_code, elapsed)
    """
    self._on_response_completed_handlers.append(handler)
    return handler

on_client_disconnect(handler)

Register a client-disconnect signal.

Fired when the client closes the connection during response delivery (broken pipe, connection reset). Does not fire for disconnects during request dispatch (e.g. slow handler). Useful for cleanup, metrics, and cancelling expensive work.

The handler receives (request) and its return value is ignored. Both sync and async callables are supported. Exceptions are logged and suppressed.

Example::

@app.on_client_disconnect
async def on_disconnect(request):
    logger.info("Client %s disconnected", request.client_addr)
Source code in httpserver/httpserver.py
def on_client_disconnect(self, handler: Callable[..., Any]) -> Callable[..., Any]:
    """Register a client-disconnect signal.

    Fired when the client closes the connection during response
    delivery (broken pipe, connection reset).  Does not fire for
    disconnects during request dispatch (e.g. slow handler).
    Useful for cleanup, metrics, and cancelling expensive work.

    The handler receives ``(request)`` and its return value is ignored.
    Both sync and async callables are supported.  Exceptions are logged
    and suppressed.

    Example::

        @app.on_client_disconnect
        async def on_disconnect(request):
            logger.info("Client %s disconnected", request.client_addr)
    """
    self._on_client_disconnect_handlers.append(handler)
    return handler

run(host=DEFAULT_HOST, port=DEFAULT_PORT, *, socket=None, ssl_context=None, backlog=None, reuse_address=None, reuse_port=None)

Start the server (blocking).

Parameters:

Name Type Description Default
host str

Bind address (ignored when socket is set).

DEFAULT_HOST
port int

Bind port. Use 0 for OS-assigned port (ignored when socket is set).

DEFAULT_PORT
socket str | None

Unix domain socket path. When set, the server listens on a Unix socket instead of TCP. The socket file permissions are restricted to owner-only (0o600) after creation. Only available on Unix-like systems.

None
ssl_context SSLContext | None

An :class:ssl.SSLContext for TLS termination. When provided, the server accepts HTTPS connections. The caller is responsible for configuring the context (loading certs, setting verify mode, etc.).

None
backlog int | None

Maximum number of queued connections passed to :func:asyncio.start_server. None leaves the OS default (typically 128).

None
reuse_address bool | None

Sets SO_REUSEADDR. None lets asyncio decide (True on non-Windows).

None
reuse_port bool | None

Sets SO_REUSEPORT for multi-process load balancing. None lets asyncio decide (False).

None
Source code in httpserver/httpserver.py
def run(
    self,
    host: str = DEFAULT_HOST,
    port: int = DEFAULT_PORT,
    *,
    socket: str | None = None,
    ssl_context: ssl.SSLContext | None = None,
    backlog: int | None = None,
    reuse_address: bool | None = None,
    reuse_port: bool | None = None,
) -> None:
    """Start the server (blocking).

    Args:
        host: Bind address (ignored when *socket* is set).
        port: Bind port. Use ``0`` for OS-assigned port (ignored when
            *socket* is set).
        socket: Unix domain socket path. When set, the server listens
            on a Unix socket instead of TCP. The socket file permissions
            are restricted to owner-only (``0o600``) after creation.
            Only available on Unix-like systems.
        ssl_context: An :class:`ssl.SSLContext` for TLS termination.
            When provided, the server accepts HTTPS connections.
            The caller is responsible for configuring the context
            (loading certs, setting verify mode, etc.).
        backlog: Maximum number of queued connections passed to
            :func:`asyncio.start_server`. ``None`` leaves the OS
            default (typically 128).
        reuse_address: Sets ``SO_REUSEADDR``. ``None`` lets asyncio
            decide (``True`` on non-Windows).
        reuse_port: Sets ``SO_REUSEPORT`` for multi-process load
            balancing. ``None`` lets asyncio decide (``False``).
    """
    try:
        asyncio.run(
            self._serve(
                host,
                port,
                socket=socket,
                ssl_context=ssl_context,
                backlog=backlog,
                reuse_address=reuse_address,
                reuse_port=reuse_port,
            )
        )
    except KeyboardInterrupt:
        pass

shutdown()

Request a graceful server shutdown.

Safe to call from any thread or from a request handler.

Source code in httpserver/httpserver.py
def shutdown(self) -> None:
    """Request a graceful server shutdown.

    Safe to call from any thread or from a request handler.
    """
    if self._shutdown_event is None or self._loop is None:
        return
    if self._loop.is_closed():
        # Already stopped; a repeated shutdown is a no-op rather than an
        # ``Event loop is closed`` error from ``call_soon_threadsafe``.
        return
    try:
        self._loop.call_soon_threadsafe(self._shutdown_event.set)
        # Wake idle kept-alive connections so a host that waits for them
        # (``Server.wait_closed()`` on 3.12+) is not held up by the idle
        # window.  ``_serve`` does the same for signal-driven shutdowns.
        self._loop.call_soon_threadsafe(self._close_idle_connections)
    except RuntimeError:  # pragma: no cover - loop closed mid-call
        # The loop can finish between the ``is_closed()`` check and the
        # call when shutdown races the server thread's exit.
        pass

abort(status_code, message=None)

Raise an :class:HTTPException with the given status code.

Parameters:

Name Type Description Default
status_code int

HTTP status code.

required
message str | None

Optional error message.

None
Source code in httpserver/httpserver.py
def abort(status_code: int, message: str | None = None) -> None:
    """Raise an :class:`HTTPException` with the given status code.

    Args:
        status_code: HTTP status code.
        message: Optional error message.
    """
    raise HTTPException(status_code, message)