Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make brotli configurable by environment variable #117

Merged
merged 3 commits into from
Jan 4, 2023
Merged
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
11 changes: 9 additions & 2 deletions django_brotli/middleware.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- encoding: utf-8 -*-
# ! python3

import os
import re

import brotli
Expand All @@ -14,10 +15,16 @@

RE_ACCEPT_ENCODING_BROTLI = re.compile(r"\bbr\b")
MIN_LEN_FOR_RESPONSE_TO_PROCESS = 200
BROTLI_MODE = getattr(brotli, os.environ.get("BROTLI_MODE", "MODE_GENERIC"))
BROTLI_QUALITY = int(os.environ.get("BROTLI_QUALITY", 4))

__all__ = ["BrotliMiddleware"]


def compress(obj):
return brotli.compress(obj, BROTLI_MODE, BROTLI_QUALITY)


# noinspection PyClassHasNoInit
class BrotliMiddleware(MiddlewareMixin):
"""
Expand Down Expand Up @@ -56,7 +63,7 @@ def process_response(
# we won't know the compressed size until we stream it.
del response["Content-Length"]
else:
compressed_content = brotli.compress(response.content)
compressed_content = compress(response.content)

# Return the compressed content only if it's actually shorter.
if len(compressed_content) >= len(response.content):
Expand All @@ -75,7 +82,7 @@ def process_response(
def compress_stream(self, streaming_content):
streaming_content = [line.decode("utf-8") for line in list(streaming_content)]
streaming_content = "".join(streaming_content).encode()
streaming_content = map(lambda x: x, [brotli.compress(streaming_content)])
streaming_content = map(lambda x: x, [compress(streaming_content)])

return streaming_content

Expand Down