starlette 通过 lifespan 参数接收一个生命周期管理器来处理启动和关闭事件。你需要定义一个异步函数,在其中使用 async with 上下文管理器包裹初始化代码(启动)和清理代码(关闭),然后将该函数传递给 starlette 实例的 lifespan 参数。

如何定义并注册 lifespan 管理器
在 Starlette 中,生命周期管理依赖于一个符合特定签名的异步可调用对象。这个对象必须接收一个名为 receive 的字典参数,并根据其中包含的事件类型执行不同的逻辑。当收到 "lifespan.startup" 事件时,执行资源初始化;当收到 "lifespan.shutdown" 事件时,执行资源释放。最后,必须向外部发送 "lifespan.state" 事件以传递状态,或发送 "lifespan.complete" 表示结束。
import asyncio
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.responses import PlainTextResponse
# 全局状态存储
db_connection = None
async def lifespan_manager(event_type: str):
global db_connection
if event_type == "startup":
print("正在连接数据库...")
await asyncio.sleep(1) # 模拟耗时操作
db_connection = {"status": "connected"}
yield {"db": db_connection} # 将状态传递给应用
elif event_type == "shutdown":
print("正在断开数据库连接...")
await asyncio.sleep(1)
db_connection = None
async def homepage(request):
return PlainTextResponse("Hello World")
app = Starlette(
routes=[Route("/", homepage)],
lifespan=lifespan_manager
)上述代码展示了最基础的生命周期实现。注意 yield 的使用:它允许函数暂停执行,等待应用运行,直到收到关闭信号时才继续执行 yield 之后的代码。这种结构确保了启动和关闭逻辑的原子性。
如何在路由中访问生命周期状态
通过 yield 传递给 lifespan 的状态字典会被注入到每个请求的 request.scope["state"] 中。这使得你可以在路由处理函数中安全地访问在启动阶段初始化的资源,如数据库连接池、配置对象或缓存客户端。这种方式避免了在每个路由中重复初始化资源,也保证了线程安全。
Starlette 1.5.1 是轻量级 Python ASGI 框架与工具集,提供路由、请求响应、中间件、WebSocket 和后台任务等组件,适合构建异步 Web 服务。本下载为官方 PyPI 通用 wheel 包,可使用 pip 安装,并由包管理器处理依赖;运行应用时还需配置 ASGI 服务器。
async def get_db_status(request):
# 从 request.scope 中获取 lifespan 传递的状态
state = request.scope.get("state", {})
db = state.get("db")
if db and db.get("status") == "connected":
return PlainTextResponse("Database is ready")
else:
return PlainTextResponse("Database not connected", status_code=503)
app = Starlette(
routes=[
Route("/", homepage),
Route("/db-status", get_db_status)
],
lifespan=lifespan_manager
)在这个例子中,/db-status 端点直接读取了 lifespan_manager 中 yield 出来的 {"db": db_connection}。如果启动失败或未执行,db 将为 None,从而返回 503 错误。这是 Starlette 推荐的资源管理模式,它将资源的生存周期与应用的生命周期紧密绑定。
如何处理 lifespan 中的异常与错误恢复
如果在 startup 阶段发生异常,Starlette 会阻止应用进入就绪状态,并记录错误日志。此时,应用不会接受任何 HTTP 请求。对于 shutdown 阶段的异常,通常建议捕获并记录,以免阻塞进程退出。你可以使用 try...except 块来确保清理逻辑的健壮性,即使某些资源已经失效也能安全退出。
async def robust_lifespan(event_type: str):
global db_connection
try:
if event_type == "startup":
print("Starting up...")
db_connection = await connect_to_db() # 假设此函数可能失败
yield {"db": db_connection}
elif event_type == "shutdown":
print("Shutting down...")
if db_connection:
await db_connection.close()
except Exception as e:
print(f"Lifespan error: {e}")
raise # 重新抛出异常以确保应用状态正确反映错误
async def connect_to_db():
# 模拟可能失败的连接
raise ConnectionError("DB unreachable")
app = Starlette(lifespan=robust_lifespan, routes=[])在上面的代码中,如果 connect_to_db 抛出异常,startup 流程中断,yield 不会执行,应用保持非就绪状态。在 shutdown 中,我们检查 db_connection 是否存在再调用 close,防止因启动失败导致的空指针异常。这种模式确保了应用在各种边界条件下都能稳定运行。

















