Gzip Middleware recipe for FastAPI
Not a full and long article, but a hacking recipe to process incoming Gzipped requests. This example is with FastAPI, but could be used as well with Starlette applications.
from fastapi import FastAPI
from starlette.types import Message
from starlette.requests import Request
from starlette.middleware.base import BaseHTTPMiddleware
import gzip
class GZipedMiddleware(BaseHTTPMiddleware):
async def set_body(self, request: Request):
receive_ = await request._receive()
if "gzip" in request.headers.getlist("Content-Encoding"):
print(receive_)
data = gzip.decompress(receive_.get('body'))
receive_['body'] = data
async def receive() -> Message:
return receive_
request._receive = receive
async def dispatch(self, request, call_next):
await self.set_body(request)
response = await call_next(request)
return response
app = FastAPI()
app.add_middleware(GZipedMiddleware)
@app.post("/post")
async def post(req: Request):
body = await req.body()
# I decode here, assuming that I just compressed
# a text file, in other use case you should use
# the appropiate decoder.
return body.decode("utf-8")