Gzip Middleware recipe for FastAPI

gealber

Gealber Morales

Posted on March 5, 2022

Gzip Middleware recipe for FastAPI

Originally published on my blog

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")

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
gealber
Gealber Morales

Posted on March 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related