Skip to content

Commit

Permalink
Add compresslevel to GZipMiddleware (#1128)
Browse files Browse the repository at this point in the history
* Add compresslevel to GZipMiddleware
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

* Add compresslevel to GZipMiddleware

Default level = 9

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

Co-authored-by: Tom Christie <tom@tomchristie.com>
  • Loading branch information
andamound and tomchristie committed Jun 11, 2021
1 parent f7aa776 commit 467eb1c
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: Send = unattached_send
self.initial_message: 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 467eb1c

Please sign in to comment.