starlette 通过依赖注入和装饰器模式实现中间件,核心机制是将每个中间件类包装成 asgi 应用,并在请求到达最终路由前依次执行。开发者只需继承 starlette.middleware.base.basehttpmiddleware 或实现标准 asgi 接口,即可在 starlette 实例中通过 add_middleware 方法注册。这些中间件按注册顺序组成调用链,请求从外向内传递,响应从内向外返回。

如何自定义一个基于 BaseHTTPMiddleware 的中间件
使用 BaseHTTPMiddleware 可以简化中间件编写,它自动处理 HTTP 请求与响应的转换。你只需要重写 dispatch 方法,在其中定义请求进入和离开时的逻辑。该基类会自动将 scope、receive 和 send 转换为标准的 Request 和 Response 对象,使代码更易于阅读和维护。

from starlette.applications import Starlette
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response, PlainTextResponse
class CustomHeaderMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
# 请求进入时:添加自定义头
request.state.start_time = time.time()
response = await call_next(request)
# 响应离开时:添加处理时间头
process_time = time.time() - request.state.start_time
response.headers["X-Process-Time"] = str(process_time)
return response
app = Starlette()
app.add_middleware(CustomHeaderMiddleware)上述代码展示了如何创建一个记录处理时间的中间件。当请求到达时,我们记录当前时间并存储到 request.state 中。接着调用 call_next 将请求传递给下一个中间件或路由。最后,计算耗时并将其添加到响应头中返回。这种方式避免了手动处理低级别的 ASGI 协议细节。
Starlette 1.5.1 是轻量级 Python ASGI 框架与工具集,提供路由、请求响应、中间件、WebSocket 和后台任务等组件,适合构建异步 Web 服务。本下载为官方 PyPI 通用 wheel 包,可使用 pip 安装,并由包管理器处理依赖;运行应用时还需配置 ASGI 服务器。
如何实现符合 ASGI 标准的全功能中间件
如果需要更细粒度的控制或处理非 HTTP 协议(如 WebSocket),可以直接实现 ASGI 接口。这种中间件接收 scope、receive 和 send 三个参数,并返回一个可调用对象。它允许你在任何阶段修改数据流,但需要手动处理异常和生命周期管理。

import asyncio
from starlette.types import Scope, Receive, Send
class SimpleASGIMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send):
if scope['type'] != 'http':
await self.app(scope, receive, send)
return
# 预处理:例如验证 API Key
headers = dict(scope.get('headers', []))
api_key = headers.get(b'x-api-key')
if not api_key:
await send({
'type': 'http.response.start',
'status': 401,
'headers': [[b'content-type', b'text/plain']],
})
await send({
'type': 'http.response.body',
'body': b'Unauthorized',
})
return
# 传递给下一个应用
await self.app(scope, receive, send)
app = Starlette()
app.add_middleware(SimpleASGIMiddleware)这个示例展示了一个直接操作 ASGI 协议的中间件。它检查请求头中的 X-API-Key,如果缺失则直接发送 401 响应并终止流程。否则,它将控制权交给内部应用。这种写法虽然繁琐,但提供了最大的灵活性,适用于需要深度集成或处理复杂生命周期的场景。
中间件在处理 WebSocket 连接时如何处理关闭信号
在 WebSocket 场景中,中间件需要监听 websocket.disconnect 事件以清理资源。如果使用 BaseHTTPMiddleware,它仅适用于 HTTP 请求,无法处理 WebSocket。因此,对于 WebSocket 中间件,必须实现完整的 ASGI 接口,并在 __call__ 方法中捕获断开连接的事件,以便执行日志记录或资源释放操作。

















