DEV Community

Gealber Morales
Gealber Morales

Posted on • Edited on • Originally published at gealber.com

9 1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (2)

Collapse
 
nlile profile image
Nathan

Isn't this already baked in with

from starlette.middleware.gzip import GZipMiddleware?

Collapse
 
__masashi__ profile image
Masashi

It is there. Gealber showed us how it worked internally.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more