我正在使用FastAPI,我想定义一个中间件,在其中可以截取前端传递的加密参数并解密,并将原始参数替换为解密后的参数,我该怎么办?我努力了
body = await request.body()
request._body = body
我也试过
async def set_body(request: Request, body: bytes):
async def receive() -> Message:
return {"type": "http.request", "body": body}
request._receive = receive
async def get_body(request: Request) -> bytes:
body = await request.body()
set_body(request, body)
return body
但是还是没有解决,哪位大神能解答一下,万分感谢!
==================================================== ========================
class GzipRequest(Request):
async def body(self) -> bytes:
# if not hasattr(self, "_body"):
body = await super().body()
# if "gzip" in self.headers.getlist("Content-Encoding"):
# body = gzip.decompress(body)
self._body = body
return self._body
class GzipRoute(APIRoute):
def get_route_handler(self) -> Callable:
original_route_handler = super().get_route_handler()
async def custom_route_handler(request: Request) -> Response:
request = GzipRequest(request.scope, request.receive)
return await original_route_handler(request)
return custom_route_handler
app.router.route_class = GzipRoute
这个方法我也试过了,还是不行!</p>
==================================================== =============
我已经解决了这个问题app.router.route_class = GzipRoute
,
主要提示:在另一个类中定义路由时,您还需要创建一个路由类,例如:
router = APIRouter(route_class=GzipRoute)