Gealber Morales
Posted on • Edited on • Originally published atgealber.com
Gzip Middleware recipe for FastAPI
Originally published on myblog
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.
fromfastapiimportFastAPIfromstarlette.typesimportMessagefromstarlette.requestsimportRequestfromstarlette.middleware.baseimportBaseHTTPMiddlewareimportgzipclassGZipedMiddleware(BaseHTTPMiddleware):asyncdefset_body(self,request:Request):receive_=awaitrequest._receive()if"gzip"inrequest.headers.getlist("Content-Encoding"):print(receive_)data=gzip.decompress(receive_.get('body'))receive_['body']=dataasyncdefreceive()->Message:returnreceive_request._receive=receiveasyncdefdispatch(self,request,call_next):awaitself.set_body(request)response=awaitcall_next(request)returnresponseapp=FastAPI()app.add_middleware(GZipedMiddleware)@app.post("/post")asyncdefpost(req:Request):body=awaitreq.body()# I decode here, assuming that I just compressed# a text file, in other use case you should use# the appropiate decoder.returnbody.decode("utf-8")
Top comments(2)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse