示例工程 35-asgi-fastapi
35-asgi-fastapi/01-handwritten-asgi/handwritten_asgi.py
"""手写最小 ASGI 应用并直接驱动协议消息。"""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from typing import Any
Scope = dict[str, Any]
Message = dict[str, Any]
Receive = Callable[[], Awaitable[Message]]
Send = Callable[[Message], Awaitable[None]]
async def app(scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
raise ValueError("unsupported scope")
if scope["path"] == "/hello":
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [(b"content-type", b"text/plain; charset=utf-8")],
}
)
await send({"type": "http.response.body", "body": b"hello asgi"})
return
await send(
{
"type": "http.response.start",
"status": 404,
"headers": [(b"content-type", b"text/plain; charset=utf-8")],
}
)
await send({"type": "http.response.body", "body": b"not found"})
async def call(path: str) -> tuple[int, bytes]:
messages: list[Message] = []
async def receive() -> Message:
return {"type": "http.request", "body": b"", "more_body": False}
async def send(message: Message) -> None:
messages.append(message)
await app({"type": "http", "path": path}, receive, send)
status = int(messages[0]["status"])
body = b"".join(message.get("body", b"") for message in messages[1:])
return status, body
def main() -> None:
status, body = asyncio.run(call("/hello"))
print(f"status: {status}")
print(f"body: {body.decode()}")
status, body = asyncio.run(call("/missing"))
print(f"missing: {status} {body.decode()}")
if __name__ == "__main__":
main()