Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions starlette/middleware/gzip.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,37 @@


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, 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) -> None:
self.app = app
self.minimum_size = minimum_size
self.compresslevel = compresslevel
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=self.compresslevel
)

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