fastapi自定义中间件
1、自定义中间件类
python
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
class MyMiddleware(BaseHTTPMiddleware):
def __init__(self, app,*args, **kwargs):
super().__init__(app,*args, **kwargs)
async def dispatch(self, request: Request, call_next):
print("MyMiddleware =============================== ")
# 接收来自客户端的Request请求;
headers = dict(request.scope['headers'])
# 将Request请求传回原路由
response = await call_next(request)
return response
2、使用自定义中间件
python
app.add_middleware(MyMiddleware)
3、中间件执行顺序,从下往上执行
python
app.add_middleware(xx1)
app.add_middleware(xx2)
会先执行xx2
再执行xx1