I am using FastAPI, I want to define a Middleware in which I can intercept the encrypted parameters passed by the front-end and decrypt them, and replace the original parameters with the decrypted ones, what should I do? I have tried
body = await request.body()
request._body = body
Also I have tried
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
But still no solution, can anyone give a solution to the problem, thanks a lot!
=========================================================================
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
I also tested this method, but it still didn't work!
==============================================================
I have solved this problem by app.router.route_class = GzipRoute
,
main tip: when defining a route in another class, you also need to make a route class, for example:
router = APIRouter(route_class=GzipRoute)