示例工程 35-asgi-fastapi

35-asgi-fastapi/05-lifespan-resource/README.md

markdown · 0.6 KB

# 05 · lifespan-resource
 
**演示**:`@asynccontextmanager` 定义 lifespan,`yield` 前初始化、后清理;`TestClient` 作为上下文管理器时触发 startup/shutdown。
**运行**:
 
```sh
uv run python examples/35-asgi-fastapi/05-lifespan-resource/lifespan_resource.py
```
 
**预期输出**(3.12.9 + FastAPI 0.165):
 
```text
health: {'ok': True}
during: ['start']
after: ['start', 'stop']
```
 
**依赖**:`uv sync --group service`(fastapi/httpx)。
**注意**:不用 `with TestClient(...)` 时 lifespan 不会执行;真实服务由 ASGI 服务器在启动/关闭时调用。