flask-squeeze 3.3.2__tar.gz → 3.3.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/PKG-INFO +2 -3
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/README.md +0 -1
- flask_squeeze-3.3.4/flask_squeeze/cache.py +45 -0
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/flask_squeeze/compress.py +17 -14
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/flask_squeeze/flask_squeeze.py +73 -77
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/flask_squeeze/minify.py +18 -15
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/flask_squeeze/utils.py +5 -13
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/flask_squeeze.egg-info/PKG-INFO +2 -3
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/flask_squeeze.egg-info/SOURCES.txt +1 -1
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/pyproject.toml +2 -2
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/tests/test_flask_squeeze.py +54 -18
- flask_squeeze-3.3.2/flask_squeeze/debug.py +0 -47
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/LICENSE +0 -0
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/flask_squeeze/__init__.py +0 -0
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/flask_squeeze/log.py +0 -0
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/flask_squeeze/models.py +0 -0
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/flask_squeeze.egg-info/dependency_links.txt +0 -0
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/flask_squeeze.egg-info/requires.txt +0 -0
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/flask_squeeze.egg-info/top_level.txt +0 -0
- {flask_squeeze-3.3.2 → flask_squeeze-3.3.4}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: flask-squeeze
|
|
3
|
-
Version: 3.3.
|
|
3
|
+
Version: 3.3.4
|
|
4
4
|
Summary: Compress and minify Flask responses!
|
|
5
5
|
Author-email: Marcel Kröker <kroeker.marcel@gmail.com>
|
|
6
6
|
License: MIT License
|
|
@@ -87,7 +87,6 @@ You can configure Flask-Squeeze with the following options in your [Flask config
|
|
|
87
87
|
| `SQUEEZE_COMPRESS` | `True` | Enables or disables compression |
|
|
88
88
|
| `SQUEEZE_MIN_SIZE` | `500` | Defines the minimum file size in bytes to activate the compression |
|
|
89
89
|
| `SQUEEZE_VERBOSE_LOGGING` | `False` | Enable or disable verbose logging. If enabled, Flask-Squeeze will print what it does into the terminal in a highlighted color |
|
|
90
|
-
| `SQUEEZE_ADD_DEBUG_HEADERS` | `False` | Add debug infos into the response headers, like call durations and cache hit infos. ONLY USE THIS IN DEVELOPMENT.
|
|
91
90
|
|
|
92
91
|
### Minification options
|
|
93
92
|
| Option | Default | Description |
|
|
@@ -47,7 +47,6 @@ You can configure Flask-Squeeze with the following options in your [Flask config
|
|
|
47
47
|
| `SQUEEZE_COMPRESS` | `True` | Enables or disables compression |
|
|
48
48
|
| `SQUEEZE_MIN_SIZE` | `500` | Defines the minimum file size in bytes to activate the compression |
|
|
49
49
|
| `SQUEEZE_VERBOSE_LOGGING` | `False` | Enable or disable verbose logging. If enabled, Flask-Squeeze will print what it does into the terminal in a highlighted color |
|
|
50
|
-
| `SQUEEZE_ADD_DEBUG_HEADERS` | `False` | Add debug infos into the response headers, like call durations and cache hit infos. ONLY USE THIS IN DEVELOPMENT.
|
|
51
50
|
|
|
52
51
|
### Minification options
|
|
53
52
|
| Option | Default | Description |
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from .models import Encoding
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class CacheKey:
|
|
12
|
+
path: str
|
|
13
|
+
encoding: Encoding | None
|
|
14
|
+
|
|
15
|
+
@property
|
|
16
|
+
def normalized(self) -> str:
|
|
17
|
+
flat_path = self.path.replace("/", "_")
|
|
18
|
+
encoding = self.encoding.value if self.encoding else "none"
|
|
19
|
+
return f"{flat_path}.{encoding}"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class CachedData:
|
|
24
|
+
original_hash: str
|
|
25
|
+
data: bytes
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class Cache:
|
|
30
|
+
data: dict[str, tuple[str, bytes]]
|
|
31
|
+
""" Maps request path to original data hash and compressed bytes """
|
|
32
|
+
|
|
33
|
+
def get(self, cache_key: CacheKey) -> CachedData | None:
|
|
34
|
+
"""Get the cached hash and data for a given cache key."""
|
|
35
|
+
|
|
36
|
+
if cache_key.normalized not in self.data:
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
original_hash, data = self.data[cache_key.normalized]
|
|
40
|
+
return CachedData(original_hash, data)
|
|
41
|
+
|
|
42
|
+
def set(self, cache_key: CacheKey, original_hash: str, data: bytes) -> None:
|
|
43
|
+
"""Set the cached data for a given cache key."""
|
|
44
|
+
|
|
45
|
+
self.data[cache_key.normalized] = (original_hash, data)
|
|
@@ -1,28 +1,39 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
1
3
|
import gzip
|
|
2
4
|
import time
|
|
3
5
|
import zlib
|
|
4
6
|
from dataclasses import dataclass
|
|
5
7
|
|
|
6
8
|
import brotli
|
|
7
|
-
from flask import Response
|
|
8
9
|
|
|
9
|
-
from
|
|
10
|
+
from .models import Encoding
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
@dataclass(frozen=True)
|
|
13
|
-
class
|
|
14
|
-
data: bytes
|
|
14
|
+
class CompressionInfo:
|
|
15
15
|
encoding: Encoding
|
|
16
16
|
quality: int
|
|
17
17
|
duration: float
|
|
18
18
|
ratio: float
|
|
19
19
|
|
|
20
|
+
@property
|
|
21
|
+
def headers(self) -> dict:
|
|
22
|
+
value = "; ".join(
|
|
23
|
+
[
|
|
24
|
+
f"ratio={self.ratio:.1f}x",
|
|
25
|
+
f"qualtiy={self.quality}",
|
|
26
|
+
f"duration={self.duration * 1000:.1f}ms",
|
|
27
|
+
],
|
|
28
|
+
)
|
|
29
|
+
return {"X-Flask-Squeeze-Compress": value}
|
|
30
|
+
|
|
20
31
|
|
|
21
32
|
def compress(
|
|
22
33
|
data: bytes,
|
|
23
34
|
encode_choice: Encoding,
|
|
24
35
|
quality: int,
|
|
25
|
-
) ->
|
|
36
|
+
) -> tuple[bytes, CompressionInfo]:
|
|
26
37
|
t0 = time.perf_counter()
|
|
27
38
|
|
|
28
39
|
compressors = {
|
|
@@ -33,17 +44,9 @@ def compress(
|
|
|
33
44
|
|
|
34
45
|
compressed_data = compressors[encode_choice](data, quality)
|
|
35
46
|
|
|
36
|
-
return
|
|
37
|
-
data=compressed_data,
|
|
47
|
+
return compressed_data, CompressionInfo(
|
|
38
48
|
encoding=encode_choice,
|
|
39
49
|
quality=quality,
|
|
40
50
|
duration=time.perf_counter() - t0,
|
|
41
51
|
ratio=len(data) / len(compressed_data),
|
|
42
52
|
)
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
def update_response_with_compressed_data(response: Response, result: CompressionResult) -> None:
|
|
46
|
-
response.set_data(result.data)
|
|
47
|
-
response.headers["X-Flask-Squeeze-Compression-Quality"] = str(result.quality)
|
|
48
|
-
response.headers["X-Flask-Squeeze-Compression-Duration"] = f"{result.duration * 1000:.1f}ms"
|
|
49
|
-
response.headers["X-Flask-Squeeze-Compression-Ratio"] = f"{result.ratio:.1f}x"
|
|
@@ -4,12 +4,10 @@ import hashlib
|
|
|
4
4
|
|
|
5
5
|
from flask import Flask, Response, request
|
|
6
6
|
|
|
7
|
-
from
|
|
8
|
-
|
|
9
|
-
from .compress import compress, update_response_with_compressed_data
|
|
10
|
-
from .debug import add_debug_header
|
|
7
|
+
from .cache import Cache, CacheKey
|
|
8
|
+
from .compress import CompressionInfo, compress
|
|
11
9
|
from .log import d_log, log
|
|
12
|
-
from .minify import
|
|
10
|
+
from .minify import MinificationInfo, minify
|
|
13
11
|
from .models import (
|
|
14
12
|
Encoding,
|
|
15
13
|
Minification,
|
|
@@ -17,18 +15,19 @@ from .models import (
|
|
|
17
15
|
choose_encoding_from_headers_and_config,
|
|
18
16
|
choose_minification_from_mimetype_and_config,
|
|
19
17
|
)
|
|
18
|
+
from .utils import add_breach_exploit_protection_header, update_response_headers
|
|
20
19
|
|
|
21
20
|
|
|
22
21
|
class Squeeze:
|
|
23
22
|
__slots__ = "app", "cache_static"
|
|
24
23
|
app: Flask
|
|
25
24
|
|
|
26
|
-
cache_static:
|
|
25
|
+
cache_static: Cache
|
|
27
26
|
""" (request.path, encoding) -> (original file sha256 hash, compressed bytes) """
|
|
28
27
|
|
|
29
28
|
def __init__(self, app: Flask | None = None) -> None:
|
|
30
29
|
"""Initialize Flask-Squeeze with or without app."""
|
|
31
|
-
self.cache_static = {}
|
|
30
|
+
self.cache_static = Cache(data={})
|
|
32
31
|
if app is None:
|
|
33
32
|
return
|
|
34
33
|
self.app = app
|
|
@@ -53,7 +52,6 @@ class Squeeze:
|
|
|
53
52
|
app.config.setdefault("SQUEEZE_MINIFY_HTML", True)
|
|
54
53
|
# Logging options
|
|
55
54
|
app.config.setdefault("SQUEEZE_VERBOSE_LOGGING", False)
|
|
56
|
-
app.config.setdefault("SQUEEZE_ADD_DEBUG_HEADERS", False)
|
|
57
55
|
|
|
58
56
|
if (
|
|
59
57
|
app.config["SQUEEZE_COMPRESS"]
|
|
@@ -91,23 +89,20 @@ class Squeeze:
|
|
|
91
89
|
) -> None:
|
|
92
90
|
assert encode_choice or minify_choice
|
|
93
91
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
92
|
+
data, minification_info, compression_info = self.squeeze(
|
|
93
|
+
response.get_data(as_text=False),
|
|
94
|
+
ResourceType.dynamic,
|
|
95
|
+
minify_choice,
|
|
96
|
+
encode_choice,
|
|
97
|
+
)
|
|
97
98
|
|
|
98
|
-
|
|
99
|
-
minification_result = minify(response.get_data(as_text=False), minify_choice)
|
|
100
|
-
update_response_with_minified_data(response, minification_result)
|
|
99
|
+
response.set_data(data)
|
|
101
100
|
|
|
102
|
-
|
|
101
|
+
if minification_info:
|
|
102
|
+
response.headers.update(minification_info.headers)
|
|
103
103
|
|
|
104
|
-
if
|
|
105
|
-
|
|
106
|
-
response.get_data(as_text=False),
|
|
107
|
-
encode_choice,
|
|
108
|
-
self.get_configured_quality(encode_choice, ResourceType.dynamic),
|
|
109
|
-
)
|
|
110
|
-
update_response_with_compressed_data(response, compression_result)
|
|
104
|
+
if compression_info:
|
|
105
|
+
response.headers.update(compression_info.headers)
|
|
111
106
|
add_breach_exploit_protection_header(response)
|
|
112
107
|
|
|
113
108
|
####################################################################################
|
|
@@ -119,75 +114,75 @@ class Squeeze:
|
|
|
119
114
|
encode_choice: Encoding | None,
|
|
120
115
|
minify_choice: Minification | None,
|
|
121
116
|
) -> None:
|
|
122
|
-
|
|
117
|
+
"""
|
|
118
|
+
If the hash of the current response matches the hash of the cached response,
|
|
119
|
+
return the cached response. Otherwise, compress and minify the response and
|
|
120
|
+
cache the compressed response.
|
|
121
|
+
"""
|
|
122
|
+
assert encode_choice or minify_choice
|
|
123
123
|
|
|
124
|
-
|
|
125
|
-
|
|
124
|
+
data = response.get_data(as_text=False)
|
|
125
|
+
data_hash = hashlib.sha256(data).hexdigest()
|
|
126
126
|
|
|
127
|
-
|
|
127
|
+
cache_key = CacheKey(request.path, encode_choice)
|
|
128
|
+
cached = self.cache_static.get(cache_key)
|
|
128
129
|
|
|
129
|
-
if
|
|
130
|
-
|
|
130
|
+
if cached is not None and data_hash == cached.original_hash:
|
|
131
|
+
log(2, "Found in cache, hashes match. RETURN")
|
|
132
|
+
response.set_data(cached.data)
|
|
133
|
+
response.headers["X-Flask-Squeeze-Cache"] = "HIT"
|
|
134
|
+
return
|
|
131
135
|
|
|
132
|
-
|
|
136
|
+
# Not in cache, compress and minify
|
|
133
137
|
|
|
134
|
-
|
|
135
|
-
|
|
138
|
+
log(2, "Not in cache or hashes don't match. Squeeze and cache.")
|
|
139
|
+
data, minification_info, compression_info = self.squeeze(
|
|
140
|
+
data,
|
|
141
|
+
ResourceType.static,
|
|
142
|
+
minify_choice,
|
|
143
|
+
encode_choice,
|
|
144
|
+
)
|
|
136
145
|
|
|
137
|
-
|
|
138
|
-
log(2, "Found in cache, hashes match. RETURN")
|
|
139
|
-
response.set_data(compressed_data)
|
|
140
|
-
response.headers["X-Flask-Squeeze-Cache"] = "HIT"
|
|
141
|
-
return
|
|
146
|
+
response.set_data(data)
|
|
142
147
|
|
|
143
|
-
|
|
148
|
+
if minification_info:
|
|
149
|
+
response.headers.update(minification_info.headers)
|
|
144
150
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
update_response_with_minified_data(response, minfication_result)
|
|
148
|
-
current_data = minfication_result.data
|
|
149
|
-
if encode_choice is not None:
|
|
150
|
-
compression_result = compress(
|
|
151
|
-
current_data,
|
|
152
|
-
encode_choice,
|
|
153
|
-
self.get_configured_quality(encode_choice, ResourceType.static),
|
|
154
|
-
)
|
|
155
|
-
update_response_with_compressed_data(response, compression_result)
|
|
156
|
-
current_data = compression_result.data
|
|
151
|
+
if compression_info:
|
|
152
|
+
response.headers.update(compression_info.headers)
|
|
157
153
|
|
|
158
|
-
|
|
154
|
+
response.headers["X-Flask-Squeeze-Cache"] = "MISS"
|
|
159
155
|
|
|
160
|
-
|
|
161
|
-
|
|
156
|
+
# Cache the compressed data, with the dash of the original data
|
|
157
|
+
self.cache_static.set(cache_key, data_hash, data)
|
|
162
158
|
|
|
163
|
-
|
|
159
|
+
def squeeze(
|
|
160
|
+
self,
|
|
161
|
+
data: bytes,
|
|
162
|
+
resource_type: ResourceType,
|
|
163
|
+
minify_choice: Minification | None,
|
|
164
|
+
encode_choice: Encoding | None,
|
|
165
|
+
) -> tuple[bytes, MinificationInfo | None, CompressionInfo | None]:
|
|
166
|
+
assert encode_choice or minify_choice
|
|
164
167
|
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
update_response_with_compressed_data(response, compression_result)
|
|
179
|
-
|
|
180
|
-
# Assert: At least one of minify or compress was run
|
|
181
|
-
|
|
182
|
-
compressed_data = response.get_data(as_text=False)
|
|
183
|
-
self.cache_static[(request.path, encode_choice_str)] = (original_sha256, compressed_data)
|
|
184
|
-
response.headers["X-Flask-Squeeze-Cache"] = "MISS"
|
|
168
|
+
minification_info = None
|
|
169
|
+
if minify_choice is not None:
|
|
170
|
+
data, minification_info = minify(data, minify_choice)
|
|
171
|
+
|
|
172
|
+
compression_info = None
|
|
173
|
+
if encode_choice is not None:
|
|
174
|
+
data, compression_info = compress(
|
|
175
|
+
data,
|
|
176
|
+
encode_choice,
|
|
177
|
+
self.get_configured_quality(encode_choice, resource_type),
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
return data, minification_info, compression_info
|
|
185
181
|
|
|
186
182
|
####################################################################################
|
|
187
183
|
#### MARK: After Request
|
|
188
184
|
|
|
189
185
|
@d_log(level=0, with_args=[1])
|
|
190
|
-
@add_debug_header("X-Flask-Squeeze-Total-Duration")
|
|
191
186
|
def after_request(self, response: Response) -> Response:
|
|
192
187
|
log(1, f"Enter after_request({response})")
|
|
193
188
|
|
|
@@ -226,13 +221,14 @@ class Squeeze:
|
|
|
226
221
|
|
|
227
222
|
# At least one of minify or compress is requested
|
|
228
223
|
|
|
229
|
-
|
|
224
|
+
response.direct_passthrough = False # In both cases, we need to read the data
|
|
230
225
|
|
|
231
226
|
if request.path.startswith("/static/"):
|
|
232
227
|
self.run_static(response, encode_choice, minify_choice)
|
|
233
228
|
else:
|
|
234
229
|
self.run_dynamic(response, encode_choice, minify_choice)
|
|
235
230
|
|
|
236
|
-
update_response_headers(response,
|
|
237
|
-
|
|
231
|
+
update_response_headers(response, encode_choice)
|
|
232
|
+
|
|
233
|
+
log(1, f"Static cache: {self.cache_static.data.keys()}")
|
|
238
234
|
return response
|
|
@@ -1,20 +1,30 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
1
3
|
import time
|
|
2
4
|
from dataclasses import dataclass
|
|
3
5
|
|
|
4
6
|
import rcssmin
|
|
5
7
|
import rjsmin
|
|
6
|
-
from flask import Response
|
|
7
8
|
|
|
8
|
-
from
|
|
9
|
+
from .models import Minification
|
|
9
10
|
|
|
10
11
|
|
|
11
12
|
@dataclass(frozen=True)
|
|
12
|
-
class
|
|
13
|
-
data: bytes
|
|
13
|
+
class MinificationInfo:
|
|
14
14
|
minification: Minification
|
|
15
15
|
duration: float
|
|
16
16
|
ratio: float
|
|
17
17
|
|
|
18
|
+
@property
|
|
19
|
+
def headers(self) -> dict:
|
|
20
|
+
value = "; ".join(
|
|
21
|
+
[
|
|
22
|
+
f"ratio={self.ratio:.1f}x",
|
|
23
|
+
f"duration={self.duration * 1000:.1f}ms",
|
|
24
|
+
],
|
|
25
|
+
)
|
|
26
|
+
return {"X-Flask-Squeeze-Minify": value}
|
|
27
|
+
|
|
18
28
|
|
|
19
29
|
def minify_html(html_text: str) -> str:
|
|
20
30
|
"""
|
|
@@ -72,7 +82,7 @@ def minify_js(data: str) -> str:
|
|
|
72
82
|
return minified
|
|
73
83
|
|
|
74
84
|
|
|
75
|
-
def minify(data: bytes, minify_choice: Minification) ->
|
|
85
|
+
def minify(data: bytes, minify_choice: Minification) -> tuple[bytes, MinificationInfo]:
|
|
76
86
|
"""
|
|
77
87
|
Run the minification using the correct minify function and return the minified data.
|
|
78
88
|
"""
|
|
@@ -85,17 +95,10 @@ def minify(data: bytes, minify_choice: Minification) -> MinificationResult:
|
|
|
85
95
|
Minification.js: lambda d: minify_js(d),
|
|
86
96
|
}
|
|
87
97
|
|
|
88
|
-
|
|
98
|
+
minified_data = minifiers[minify_choice](data.decode("utf-8")).encode("utf-8")
|
|
89
99
|
|
|
90
|
-
return
|
|
91
|
-
data=minified,
|
|
100
|
+
return minified_data, MinificationInfo(
|
|
92
101
|
minification=minify_choice,
|
|
93
102
|
duration=time.perf_counter() - t0,
|
|
94
|
-
ratio=len(data) / len(
|
|
103
|
+
ratio=len(data) / len(minified_data),
|
|
95
104
|
)
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
def update_response_with_minified_data(response: Response, result: MinificationResult) -> None:
|
|
99
|
-
response.set_data(result.data)
|
|
100
|
-
response.headers["X-Flask-Squeeze-Minify-Duration"] = f"{result.duration * 1000:.1f}ms"
|
|
101
|
-
response.headers["X-Flask-Squeeze-Minify-Ratio"] = f"{result.ratio:.1f}x"
|
|
@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING
|
|
|
6
6
|
if TYPE_CHECKING:
|
|
7
7
|
from flask import Response
|
|
8
8
|
|
|
9
|
-
from
|
|
9
|
+
from .models import Encoding
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
def add_breach_exploit_protection_header(response: Response) -> None:
|
|
@@ -15,14 +15,10 @@ def add_breach_exploit_protection_header(response: Response) -> None:
|
|
|
15
15
|
"""
|
|
16
16
|
padding_length = secrets.randbelow(128) + 1
|
|
17
17
|
rand_str = secrets.token_urlsafe(padding_length)
|
|
18
|
-
response.headers["X-Breach-
|
|
18
|
+
response.headers["X-Flask-Squeeze-Breach-Protection"] = rand_str
|
|
19
19
|
|
|
20
20
|
|
|
21
|
-
def update_response_headers(
|
|
22
|
-
response: Response,
|
|
23
|
-
original_content_length: int,
|
|
24
|
-
encode_choice: Encoding | None,
|
|
25
|
-
) -> None:
|
|
21
|
+
def update_response_headers(response: Response, encode_choice: Encoding | None) -> None:
|
|
26
22
|
"""
|
|
27
23
|
Set the Content-Length header if it has changed.
|
|
28
24
|
Set the Content-Encoding header if compressed data is served.
|
|
@@ -32,10 +28,6 @@ def update_response_headers(
|
|
|
32
28
|
if encode_choice is not None:
|
|
33
29
|
response.headers["Content-Encoding"] = encode_choice.value
|
|
34
30
|
vary = {x.strip() for x in response.headers.get("Vary", "").split(",")}
|
|
35
|
-
|
|
36
|
-
vary.discard("")
|
|
37
|
-
response.headers["Vary"] = ",".join(vary)
|
|
31
|
+
response.headers["Vary"] = ",".join((vary | {"Accept-Encoding"}) - {""})
|
|
38
32
|
|
|
39
|
-
|
|
40
|
-
response.headers["Content-Length"] = response.content_length
|
|
41
|
-
response.headers["X-Uncompressed-Content-Length"] = original_content_length
|
|
33
|
+
response.headers["Content-Length"] = response.content_length
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: flask-squeeze
|
|
3
|
-
Version: 3.3.
|
|
3
|
+
Version: 3.3.4
|
|
4
4
|
Summary: Compress and minify Flask responses!
|
|
5
5
|
Author-email: Marcel Kröker <kroeker.marcel@gmail.com>
|
|
6
6
|
License: MIT License
|
|
@@ -87,7 +87,6 @@ You can configure Flask-Squeeze with the following options in your [Flask config
|
|
|
87
87
|
| `SQUEEZE_COMPRESS` | `True` | Enables or disables compression |
|
|
88
88
|
| `SQUEEZE_MIN_SIZE` | `500` | Defines the minimum file size in bytes to activate the compression |
|
|
89
89
|
| `SQUEEZE_VERBOSE_LOGGING` | `False` | Enable or disable verbose logging. If enabled, Flask-Squeeze will print what it does into the terminal in a highlighted color |
|
|
90
|
-
| `SQUEEZE_ADD_DEBUG_HEADERS` | `False` | Add debug infos into the response headers, like call durations and cache hit infos. ONLY USE THIS IN DEVELOPMENT.
|
|
91
90
|
|
|
92
91
|
### Minification options
|
|
93
92
|
| Option | Default | Description |
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "flask-squeeze"
|
|
3
|
-
version = "3.3.
|
|
3
|
+
version = "3.3.4"
|
|
4
4
|
description = "Compress and minify Flask responses!"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
authors = [{ name = "Marcel Kröker", email = "kroeker.marcel@gmail.com" }]
|
|
@@ -30,7 +30,7 @@ dependencies = [
|
|
|
30
30
|
|
|
31
31
|
[dependency-groups]
|
|
32
32
|
dev = [
|
|
33
|
-
"pytest-cov ~=
|
|
33
|
+
"pytest-cov ~= 5.0.0",
|
|
34
34
|
"ruff>=0.9.3",
|
|
35
35
|
]
|
|
36
36
|
|
|
@@ -75,7 +75,8 @@ def test_get_index(client: FlaskClient, use_encoding: str) -> None:
|
|
|
75
75
|
def test_get_css_file(client: FlaskClient, use_encoding: str, use_minify_css: bool) -> None:
|
|
76
76
|
print("test_get_css_file with", use_encoding, "minify:", use_minify_css)
|
|
77
77
|
client.application.config.update({"SQUEEZE_MINIFY_CSS": use_minify_css})
|
|
78
|
-
|
|
78
|
+
url = "/static/fomantic.css"
|
|
79
|
+
r = client.get(url, headers={"Accept-Encoding": use_encoding})
|
|
79
80
|
assert content_length_correct(r)
|
|
80
81
|
response_length = int(r.headers.get("Content-Length", "0"))
|
|
81
82
|
encoding = r.headers.get("Content-Encoding", "")
|
|
@@ -110,7 +111,6 @@ def test_get_jquery_no_minify(client: FlaskClient) -> None:
|
|
|
110
111
|
assert content_length_correct(r_orig)
|
|
111
112
|
assert "Content-Encoding" not in r_orig.headers
|
|
112
113
|
assert r_orig.headers["Content-Length"] == "292458"
|
|
113
|
-
assert "X-Uncompressed-Content-Length" not in r_orig.headers
|
|
114
114
|
|
|
115
115
|
|
|
116
116
|
def test_get_from_cache(client: FlaskClient, use_encoding: str) -> None:
|
|
@@ -144,7 +144,7 @@ def test_get_same_repeatedly(client: FlaskClient) -> None:
|
|
|
144
144
|
|
|
145
145
|
|
|
146
146
|
def response_has_breach_header(r: Response) -> bool:
|
|
147
|
-
return "X-Breach-
|
|
147
|
+
return "X-Flask-Squeeze-Breach-Protection" in r.headers
|
|
148
148
|
|
|
149
149
|
|
|
150
150
|
def response_has_vary_header(r: Response) -> bool:
|
|
@@ -173,14 +173,14 @@ def test_disable_minification(client: FlaskClient) -> None:
|
|
|
173
173
|
},
|
|
174
174
|
)
|
|
175
175
|
r = client.get("/static/jquery.js", headers={"Accept-Encoding": "gzip"})
|
|
176
|
-
assert "X-Flask-Squeeze-Minify
|
|
176
|
+
assert "X-Flask-Squeeze-Minify" not in r.headers
|
|
177
177
|
|
|
178
178
|
|
|
179
179
|
def test_html_response_minification(client: FlaskClient) -> None:
|
|
180
180
|
"""Test minification of HTML responses."""
|
|
181
181
|
client.application.config.update({"SQUEEZE_MINIFY_HTML": True})
|
|
182
182
|
r = client.get("/", headers={"Accept-Encoding": "gzip"})
|
|
183
|
-
assert "X-Flask-Squeeze-Minify
|
|
183
|
+
assert "X-Flask-Squeeze-Minify" in r.headers, r.headers
|
|
184
184
|
|
|
185
185
|
|
|
186
186
|
def test_breach_header_presence(client: FlaskClient) -> None:
|
|
@@ -200,18 +200,10 @@ def test_minification_and_compression_together(client: FlaskClient) -> None:
|
|
|
200
200
|
client.application.config.update({"SQUEEZE_MINIFY_CSS": True})
|
|
201
201
|
r = client.get("/static/fomantic.css", headers={"Accept-Encoding": "gzip"})
|
|
202
202
|
assert "Content-Encoding" in r.headers
|
|
203
|
-
assert "X-Flask-Squeeze-Minify
|
|
203
|
+
assert "X-Flask-Squeeze-Minify" in r.headers
|
|
204
204
|
assert content_length_correct(r)
|
|
205
205
|
|
|
206
206
|
|
|
207
|
-
def test_debug_headers_presence(client: FlaskClient) -> None:
|
|
208
|
-
"""Test if debug headers are added when enabled."""
|
|
209
|
-
client.application.config.update({"SQUEEZE_ADD_DEBUG_HEADERS": True})
|
|
210
|
-
r = client.get("/static/fomantic.css", headers={"Accept-Encoding": "gzip"})
|
|
211
|
-
assert "X-Flask-Squeeze-Total-Duration" in r.headers
|
|
212
|
-
assert "X-Flask-Squeeze-Compress-Duration" in r.headers or "X-Flask-Squeeze-Minify-Duration" in r.headers
|
|
213
|
-
|
|
214
|
-
|
|
215
207
|
def test_no_minify_no_compress(client: FlaskClient) -> None:
|
|
216
208
|
client.application.config.update(
|
|
217
209
|
{
|
|
@@ -226,15 +218,15 @@ def test_no_minify_no_compress(client: FlaskClient) -> None:
|
|
|
226
218
|
|
|
227
219
|
r = client.get("/static/fomantic.css", headers={"Accept-Encoding": "gzip"})
|
|
228
220
|
assert "Content-Encoding" not in r.headers
|
|
229
|
-
assert "X-Flask-Squeeze-Minify
|
|
230
|
-
assert "X-Flask-Squeeze-
|
|
221
|
+
assert "X-Flask-Squeeze-Minify" not in r.headers
|
|
222
|
+
assert "X-Flask-Squeeze-Compress" not in r.headers
|
|
231
223
|
|
|
232
224
|
# Dynamic file with no minification or compression
|
|
233
225
|
|
|
234
226
|
r = client.get("/", headers={"Accept-Encoding": "gzip"})
|
|
235
227
|
assert "Content-Encoding" not in r.headers
|
|
236
|
-
assert "X-Flask-Squeeze-Minify
|
|
237
|
-
assert "X-Flask-Squeeze-
|
|
228
|
+
assert "X-Flask-Squeeze-Minify" not in r.headers
|
|
229
|
+
assert "X-Flask-Squeeze-Compress" not in r.headers
|
|
238
230
|
|
|
239
231
|
|
|
240
232
|
def test_static_file_cache_behavior(
|
|
@@ -281,3 +273,47 @@ def test_static_file_cache_behavior(
|
|
|
281
273
|
# Fourth request: HIT
|
|
282
274
|
r = client.get(url_path, headers={"Accept-Encoding": use_encoding})
|
|
283
275
|
assert r.headers.get("X-Flask-Squeeze-Cache") == "HIT"
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def test_malformed_accept_encoding(client: FlaskClient) -> None:
|
|
279
|
+
# Case 1: Missing Accept-Encoding
|
|
280
|
+
r = client.get("/static/jquery.js")
|
|
281
|
+
assert "Content-Encoding" not in r.headers
|
|
282
|
+
|
|
283
|
+
# Case 2: Malformed Accept-Encoding
|
|
284
|
+
r = client.get("/static/jquery.js", headers={"Accept-Encoding": "invalid-encoding"})
|
|
285
|
+
assert "Content-Encoding" not in r.headers
|
|
286
|
+
|
|
287
|
+
# Case 3: Conflicting Accept-Encoding values
|
|
288
|
+
r = client.get("/static/jquery.js", headers={"Accept-Encoding": "gzip, br"})
|
|
289
|
+
assert r.headers.get("Content-Encoding") in {"gzip", "br"}
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def test_cache_invalidation_on_compression_disable(client: FlaskClient) -> None:
|
|
293
|
+
# Enable compression and fetch the file
|
|
294
|
+
client.application.config.update({"SQUEEZE_COMPRESS": True})
|
|
295
|
+
r = client.get("/static/jquery.js", headers={"Accept-Encoding": "gzip"})
|
|
296
|
+
assert r.headers.get("X-Flask-Squeeze-Cache") == "MISS"
|
|
297
|
+
|
|
298
|
+
# Fetch again to ensure it is cached
|
|
299
|
+
r = client.get("/static/jquery.js", headers={"Accept-Encoding": "gzip"})
|
|
300
|
+
assert r.headers.get("X-Flask-Squeeze-Cache") == "HIT"
|
|
301
|
+
|
|
302
|
+
# Disable compression
|
|
303
|
+
client.application.config.update({"SQUEEZE_COMPRESS": False})
|
|
304
|
+
|
|
305
|
+
# Fetch again, cache should be invalidated
|
|
306
|
+
r = client.get("/static/jquery.js", headers={"Accept-Encoding": "gzip"})
|
|
307
|
+
assert r.headers.get("X-Flask-Squeeze-Cache") == "MISS"
|
|
308
|
+
assert "Content-Encoding" not in r.headers
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def test_small_response_below_min_size(client: FlaskClient) -> None:
|
|
312
|
+
min_size = 1000
|
|
313
|
+
client.application.config.update({"SQUEEZE_MIN_SIZE": min_size})
|
|
314
|
+
|
|
315
|
+
# A small response
|
|
316
|
+
r = client.get("/static/smallfile.js", headers={"Accept-Encoding": "gzip"})
|
|
317
|
+
assert r.content_length < min_size # Ensure response is small
|
|
318
|
+
assert "Content-Encoding" not in r.headers
|
|
319
|
+
assert "X-Flask-Squeeze-Minify" not in r.headers
|
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
import functools
|
|
4
|
-
import time
|
|
5
|
-
from typing import TYPE_CHECKING, Any
|
|
6
|
-
|
|
7
|
-
from flask import Response, current_app
|
|
8
|
-
|
|
9
|
-
if TYPE_CHECKING:
|
|
10
|
-
from collections.abc import Callable
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
def _write_benchmark_debug_header(response: Response, header_name: str, t1: float, t2: float) -> None:
|
|
14
|
-
if current_app.config["SQUEEZE_ADD_DEBUG_HEADERS"]:
|
|
15
|
-
dur_ms_str = f"{(t2 - t1) * 1000:.1f}ms"
|
|
16
|
-
response.headers[header_name] = dur_ms_str
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
class add_debug_header: # noqa: N801
|
|
20
|
-
def __init__(self, header_name: str) -> None:
|
|
21
|
-
self.header_name = header_name
|
|
22
|
-
|
|
23
|
-
def get_response(self, args: tuple, kwargs: dict) -> Response:
|
|
24
|
-
for arg in args:
|
|
25
|
-
if isinstance(arg, Response):
|
|
26
|
-
return arg
|
|
27
|
-
for kwarg in kwargs.values():
|
|
28
|
-
if isinstance(kwarg, Response):
|
|
29
|
-
return kwarg
|
|
30
|
-
msg = "You can only deocrate a function with 'add_debug_header' that has a Response as an argument or kwarg."
|
|
31
|
-
raise ValueError(msg)
|
|
32
|
-
|
|
33
|
-
def __call__(self, method: Callable) -> Callable:
|
|
34
|
-
@functools.wraps(method)
|
|
35
|
-
def wrapper(*args: tuple, **kwargs: dict[str, Any]):
|
|
36
|
-
if not current_app.config["SQUEEZE_ADD_DEBUG_HEADERS"]:
|
|
37
|
-
return method(*args, **kwargs)
|
|
38
|
-
|
|
39
|
-
response = self.get_response(args, kwargs)
|
|
40
|
-
t1 = time.perf_counter()
|
|
41
|
-
res = method(*args, **kwargs)
|
|
42
|
-
t2 = time.perf_counter()
|
|
43
|
-
|
|
44
|
-
_write_benchmark_debug_header(response, self.header_name, t1, t2)
|
|
45
|
-
return res
|
|
46
|
-
|
|
47
|
-
return wrapper
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|