Skip to content

Commit

Permalink
Add compresslevel to GZipMiddleware
Browse files Browse the repository at this point in the history
Current default level = 9
New default level = 1

Documentation gzip: https://docs.python.org/3/library/gzip.html
Benchmarks: https://tukaani.org/lzma/benchmarks.html

Reformate code

Default compress level in gzip now = 9
  • Loading branch information
andamound committed Jan 24, 2021
1 parent e430706 commit d38ffa7
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions starlette/middleware/gzip.py
Expand Up @@ -6,29 +6,36 @@


class GZipMiddleware:
def __init__(self, app: ASGIApp, minimum_size: int = 500) -> None:
def __init__(
self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9
) -> None:
self.app = app
self.minimum_size = minimum_size
self.compresslevel = compresslevel

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] == "http":
headers = Headers(scope=scope)
if "gzip" in headers.get("Accept-Encoding", ""):
responder = GZipResponder(self.app, self.minimum_size)
responder = GZipResponder(
self.app, self.minimum_size, compresslevel=self.compresslevel
)
await responder(scope, receive, send)
return
await self.app(scope, receive, send)


class GZipResponder:
def __init__(self, app: ASGIApp, minimum_size: int) -> None:
def __init__(self, app: ASGIApp, minimum_size: int, compresslevel: int = 9) -> None:
self.app = app
self.minimum_size = minimum_size
self.send = unattached_send # type: Send
self.initial_message = {} # type: Message
self.started = False
self.gzip_buffer = io.BytesIO()
self.gzip_file = gzip.GzipFile(mode="wb", fileobj=self.gzip_buffer)
self.gzip_file = gzip.GzipFile(
mode="wb", fileobj=self.gzip_buffer, compresslevel=compresslevel
)

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
self.send = send
Expand Down

0 comments on commit d38ffa7

Please sign in to comment.