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

Exclude User Agents from compression #34

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,5 @@ Within your Flask application's settings you can provide the following settings
| `COMPRESS_CACHE_BACKEND` | Specified the backend for storing the cached response data. | `None` |
| `COMPRESS_REGISTER` | Specifies if compression should be automatically registered. | `True` |
| `COMPRESS_ALGORITHM` | Supported compression algorithms. | `['br', 'gzip', 'deflate']` |
| `COMPRESS_EXCLUDE_UA` | Do not compress User Agents containing one of the strings in the list. | `[]` |
| `COMPRESS_TRACE` | Log debug information. | `False` |
9 changes: 9 additions & 0 deletions flask_compress/flask_compress.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ def init_app(self, app):
('COMPRESS_CACHE_BACKEND', None),
('COMPRESS_REGISTER', True),
('COMPRESS_ALGORITHM', ['br', 'gzip', 'deflate']),
('COMPRESS_EXCLUDE_UA', []),
('COMPRESS_TRACE', False)
]

for k, v in defaults:
Expand Down Expand Up @@ -166,6 +168,9 @@ def after_request(self, response):
app = self.app or current_app

vary = response.headers.get('Vary')
if app.config["COMPRESS_TRACE"]:
app.logger.info('COMPRESS_TRACE_UA: "%s"',
request.headers.get('user-agent'))
if not vary:
response.headers['Vary'] = 'Accept-Encoding'
elif 'accept-encoding' not in vary.lower():
Expand All @@ -175,13 +180,17 @@ def after_request(self, response):
chosen_algorithm = self._choose_compress_algorithm(accept_encoding)

if (chosen_algorithm is None or
any([i in request.headers.get('user-agent')
for i in app.config["COMPRESS_EXCLUDE_UA"]]) or
response.mimetype not in app.config["COMPRESS_MIMETYPES"] or
response.status_code < 200 or
response.status_code >= 300 or
response.is_streamed or
"Content-Encoding" in response.headers or
(response.content_length is not None and
response.content_length < app.config["COMPRESS_MIN_SIZE"])):
if app.config["COMPRESS_TRACE"]:
app.logger.info('COMPRESS_TRACE: no compression')
return response

response.direct_passthrough = False
Expand Down