在FastApi中有时候我们有要获取请求参数的需求,就需要在这中间件中拦截请求request来获取参数做处理。
通过中间件,拿到request我们能看到,路径参数和query_params都能轻易取到。
获取request_body,这里提供两种方式,直接通过receive = await request._receive()获取,会导致请求阻塞,所以需要把数据放获取,在中间环节拿到数据。
def de(func):
async def wrapper():
return func
return wrapper
async def set_body(request: Request):
receive_ = await request._receive()
async def receive():
return receive_
request._receive = receive
@fast_app.middleware("http")
async def sendErrorLog(request: Request, call_next):
"""获取request body"""
# 1
# receive = await request._receive()
# request._receive = de(receive)
# 2
await set_body(request)
# data = await request.json() # 直接拿json格式
# data = await request.body()
response = await call_next(request)
网友评论