Skip to content

Commit

Permalink
Fix zstd compression context for streaming
Browse files Browse the repository at this point in the history
  • Loading branch information
Zaczero committed May 7, 2024
1 parent 5e18761 commit 59a1361
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 11 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ license = "Unlicense"
name = "starlette-compress"
readme = "README.md"
repository = "https://github.com/Zaczero/starlette-compress"
version = "1.0.0"
version = "1.0.1"

[tool.poetry.dependencies]
brotli = {version = ">=1", markers = "platform_python_implementation == 'CPython'"}
Expand Down
16 changes: 6 additions & 10 deletions starlette_compress/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,6 @@ class CompressMiddleware:
'_gzip',
)

app: ASGIApp
_zstd: _ZstdResponder | None
_brotli: _BrotliResponder | None
_gzip: _GZipResponder | None

def __init__(
self,
app: ASGIApp,
Expand All @@ -56,7 +51,7 @@ def __init__(
gzip_level: int = 4,
) -> None:
self.app = app
self._zstd = _ZstdResponder(app, minimum_size, ZstdCompressor(level=zstd_level)) if zstd else None
self._zstd = _ZstdResponder(app, minimum_size, zstd_level) if zstd else None
self._brotli = _BrotliResponder(app, minimum_size, brotli_quality) if brotli else None
self._gzip = _GZipResponder(app, minimum_size, gzip_level) if gzip else None

Expand Down Expand Up @@ -87,13 +82,15 @@ class _ZstdResponder:
__slots__ = (
'app',
'minimum_size',
'level',
'compressor',
)

def __init__(self, app: ASGIApp, minimum_size: int, compressor: ZstdCompressor) -> None:
def __init__(self, app: ASGIApp, minimum_size: int, level: int) -> None:
self.app = app
self.minimum_size = minimum_size
self.compressor = compressor
self.level = level
self.compressor = ZstdCompressor(level=level)

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
start_message: Message | None = None
Expand Down Expand Up @@ -149,7 +146,7 @@ async def wrapper(message: Message) -> None:
content_length: int = int(headers.get('Content-Length', -1))
del headers['Content-Length']
await send(start_message)
chunker = self.compressor.chunker(content_length)
chunker = ZstdCompressor(level=self.level).chunker(content_length)

# streaming
for chunk in chunker.compress(body):
Expand All @@ -169,7 +166,6 @@ class _BrotliResponder:
'app',
'minimum_size',
'quality',
'compressor',
)

def __init__(self, app: ASGIApp, minimum_size: int, quality: int) -> None:
Expand Down

0 comments on commit 59a1361

Please sign in to comment.