Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Gealber Morales
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")
Enter fullscreen modeExit fullscreen mode

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
nlile profile image
Nathan
Recurrent rabbit hole victim.
  • Joined

Isn't this already baked in with

from starlette.middleware.gzip import GZipMiddleware?

CollapseExpand
 
__masashi__ profile image
Masashi
Just an ordinary human who loves programming.IG: masashi.iguess
  • Location
    The Internet
  • Joined

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

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Backend developer, working mostly with Golang. Reverse Engineer novice, most of the time just learning to reverse stuffs.
  • Location
    Montenegro
  • Education
    University of Havana
  • Work
    Backend developer
  • Joined

More fromGealber Morales

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp