flask-squeeze 3.3.1__tar.gz → 3.3.3__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.1 → flask_squeeze-3.3.3}/PKG-INFO +1 -2
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/README.md +0 -1
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/flask_squeeze/compress.py +18 -11
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/flask_squeeze/flask_squeeze.py +15 -42
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/flask_squeeze/log.py +6 -4
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/flask_squeeze/minify.py +18 -12
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/flask_squeeze/models.py +2 -2
- flask_squeeze-3.3.3/flask_squeeze/utils.py +40 -0
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/flask_squeeze.egg-info/PKG-INFO +1 -2
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/flask_squeeze.egg-info/SOURCES.txt +0 -1
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/pyproject.toml +39 -15
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/tests/test_flask_squeeze.py +64 -29
- flask_squeeze-3.3.1/flask_squeeze/debug.py +0 -44
- flask_squeeze-3.3.1/flask_squeeze/utils.py +0 -12
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/LICENSE +0 -0
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/flask_squeeze/__init__.py +0 -0
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/flask_squeeze.egg-info/dependency_links.txt +0 -0
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/flask_squeeze.egg-info/requires.txt +0 -0
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/flask_squeeze.egg-info/top_level.txt +0 -0
- {flask_squeeze-3.3.1 → flask_squeeze-3.3.3}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.2
|
|
2
2
|
Name: flask-squeeze
|
|
3
|
-
Version: 3.3.
|
|
3
|
+
Version: 3.3.3
|
|
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 |
|
|
@@ -17,6 +17,16 @@ class CompressionResult:
|
|
|
17
17
|
duration: float
|
|
18
18
|
ratio: float
|
|
19
19
|
|
|
20
|
+
@property
|
|
21
|
+
def info(self) -> str:
|
|
22
|
+
return "; ".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
|
+
|
|
20
30
|
|
|
21
31
|
def compress(
|
|
22
32
|
data: bytes,
|
|
@@ -25,14 +35,13 @@ def compress(
|
|
|
25
35
|
) -> CompressionResult:
|
|
26
36
|
t0 = time.perf_counter()
|
|
27
37
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
raise ValueError(f"Invalid encoding choice {encode_choice}")
|
|
38
|
+
compressors = {
|
|
39
|
+
Encoding.br: lambda d, q: brotli.compress(d, quality=q),
|
|
40
|
+
Encoding.deflate: lambda d, q: zlib.compress(d, level=q),
|
|
41
|
+
Encoding.gzip: lambda d, q: gzip.compress(d, compresslevel=q),
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
compressed_data = compressors[encode_choice](data, quality)
|
|
36
45
|
|
|
37
46
|
return CompressionResult(
|
|
38
47
|
data=compressed_data,
|
|
@@ -45,6 +54,4 @@ def compress(
|
|
|
45
54
|
|
|
46
55
|
def update_response_with_compressed_data(response: Response, result: CompressionResult) -> None:
|
|
47
56
|
response.set_data(result.data)
|
|
48
|
-
response.headers["X-Flask-Squeeze-
|
|
49
|
-
response.headers["X-Flask-Squeeze-Compression-Duration"] = f"{result.duration * 1000:.1f}ms"
|
|
50
|
-
response.headers["X-Flask-Squeeze-Compression-Ratio"] = f"{result.ratio:.1f}x"
|
|
57
|
+
response.headers["X-Flask-Squeeze-Compress"] = result.info
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
1
3
|
import hashlib
|
|
2
|
-
from typing import Dict, Tuple, Union
|
|
3
4
|
|
|
4
5
|
from flask import Flask, Response, request
|
|
5
6
|
|
|
6
|
-
from flask_squeeze.utils import add_breach_exploit_protection_header
|
|
7
|
+
from flask_squeeze.utils import add_breach_exploit_protection_header, update_response_headers
|
|
7
8
|
|
|
8
9
|
from .compress import compress, update_response_with_compressed_data
|
|
9
|
-
from .debug import add_debug_header
|
|
10
10
|
from .log import d_log, log
|
|
11
11
|
from .minify import minify, update_response_with_minified_data
|
|
12
12
|
from .models import (
|
|
@@ -22,10 +22,10 @@ class Squeeze:
|
|
|
22
22
|
__slots__ = "app", "cache_static"
|
|
23
23
|
app: Flask
|
|
24
24
|
|
|
25
|
-
cache_static:
|
|
25
|
+
cache_static: dict[tuple[str, str], tuple[str, bytes]]
|
|
26
26
|
""" (request.path, encoding) -> (original file sha256 hash, compressed bytes) """
|
|
27
27
|
|
|
28
|
-
def __init__(self, app:
|
|
28
|
+
def __init__(self, app: Flask | None = None) -> None:
|
|
29
29
|
"""Initialize Flask-Squeeze with or without app."""
|
|
30
30
|
self.cache_static = {}
|
|
31
31
|
if app is None:
|
|
@@ -52,7 +52,6 @@ class Squeeze:
|
|
|
52
52
|
app.config.setdefault("SQUEEZE_MINIFY_HTML", True)
|
|
53
53
|
# Logging options
|
|
54
54
|
app.config.setdefault("SQUEEZE_VERBOSE_LOGGING", False)
|
|
55
|
-
app.config.setdefault("SQUEEZE_ADD_DEBUG_HEADERS", False)
|
|
56
55
|
|
|
57
56
|
if (
|
|
58
57
|
app.config["SQUEEZE_COMPRESS"]
|
|
@@ -75,47 +74,20 @@ class Squeeze:
|
|
|
75
74
|
(Encoding.gzip, ResourceType.dynamic): "SQUEEZE_LEVEL_GZIP_DYNAMIC",
|
|
76
75
|
}
|
|
77
76
|
|
|
78
|
-
|
|
79
|
-
msg = f"Invalid encoding choice {encode_choice} for {resource_type} resource at {request.path}"
|
|
80
|
-
raise ValueError(msg)
|
|
77
|
+
option = options[(encode_choice, resource_type)]
|
|
81
78
|
|
|
82
79
|
return self.app.config[option]
|
|
83
80
|
|
|
84
|
-
def recompute_headers(
|
|
85
|
-
self,
|
|
86
|
-
response: Response,
|
|
87
|
-
original_content_length: int,
|
|
88
|
-
encode_choice: Union[Encoding, None],
|
|
89
|
-
) -> None:
|
|
90
|
-
"""
|
|
91
|
-
Set the Content-Length header if it has changed.
|
|
92
|
-
Set the Content-Encoding header if compressed data is served.
|
|
93
|
-
"""
|
|
94
|
-
if response.direct_passthrough:
|
|
95
|
-
return
|
|
96
|
-
|
|
97
|
-
if encode_choice is not None:
|
|
98
|
-
response.headers["Content-Encoding"] = encode_choice.value
|
|
99
|
-
vary = {x.strip() for x in response.headers.get("Vary", "").split(",")}
|
|
100
|
-
vary.add("Accept-Encoding")
|
|
101
|
-
vary.discard("")
|
|
102
|
-
response.headers["Vary"] = ",".join(vary)
|
|
103
|
-
|
|
104
|
-
if original_content_length != response.content_length:
|
|
105
|
-
response.headers["Content-Length"] = response.content_length
|
|
106
|
-
response.headers["X-Uncompressed-Content-Length"] = original_content_length
|
|
107
|
-
|
|
108
81
|
####################################################################################
|
|
109
82
|
#### MARK: Dynamic
|
|
110
83
|
|
|
111
84
|
def run_dynamic(
|
|
112
85
|
self,
|
|
113
86
|
response: Response,
|
|
114
|
-
encode_choice:
|
|
115
|
-
minify_choice:
|
|
87
|
+
encode_choice: Encoding | None,
|
|
88
|
+
minify_choice: Minification | None,
|
|
116
89
|
) -> None:
|
|
117
|
-
|
|
118
|
-
return # Early exit if no compression or minification is requested
|
|
90
|
+
assert encode_choice or minify_choice
|
|
119
91
|
|
|
120
92
|
response.direct_passthrough = False
|
|
121
93
|
|
|
@@ -142,8 +114,8 @@ class Squeeze:
|
|
|
142
114
|
def run_static(
|
|
143
115
|
self,
|
|
144
116
|
response: Response,
|
|
145
|
-
encode_choice:
|
|
146
|
-
minify_choice:
|
|
117
|
+
encode_choice: Encoding | None,
|
|
118
|
+
minify_choice: Minification | None,
|
|
147
119
|
) -> None:
|
|
148
120
|
response.direct_passthrough = False # Ensure we can read the data
|
|
149
121
|
|
|
@@ -213,7 +185,6 @@ class Squeeze:
|
|
|
213
185
|
#### MARK: After Request
|
|
214
186
|
|
|
215
187
|
@d_log(level=0, with_args=[1])
|
|
216
|
-
@add_debug_header("X-Flask-Squeeze-Total-Duration")
|
|
217
188
|
def after_request(self, response: Response) -> Response:
|
|
218
189
|
log(1, f"Enter after_request({response})")
|
|
219
190
|
|
|
@@ -221,7 +192,7 @@ class Squeeze:
|
|
|
221
192
|
log(1, "Response status code or content length is None. RETURN")
|
|
222
193
|
return response
|
|
223
194
|
|
|
224
|
-
if response.status_code
|
|
195
|
+
if response.status_code not in range(200, 300):
|
|
225
196
|
log(1, "Response status code is not ok. RETURN")
|
|
226
197
|
return response
|
|
227
198
|
|
|
@@ -250,6 +221,8 @@ class Squeeze:
|
|
|
250
221
|
log(1, "No compression or minification requested. RETURN")
|
|
251
222
|
return response
|
|
252
223
|
|
|
224
|
+
# At least one of minify or compress is requested
|
|
225
|
+
|
|
253
226
|
original_content_length = response.content_length
|
|
254
227
|
|
|
255
228
|
if request.path.startswith("/static/"):
|
|
@@ -257,6 +230,6 @@ class Squeeze:
|
|
|
257
230
|
else:
|
|
258
231
|
self.run_dynamic(response, encode_choice, minify_choice)
|
|
259
232
|
|
|
260
|
-
|
|
233
|
+
update_response_headers(response, original_content_length, encode_choice)
|
|
261
234
|
log(1, f"Static cache: {self.cache_static.keys()}")
|
|
262
235
|
return response
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
1
3
|
import functools
|
|
2
4
|
import time
|
|
3
|
-
from typing import Any, Callable,
|
|
5
|
+
from typing import Any, Callable, Union
|
|
4
6
|
|
|
5
7
|
from flask import Request, current_app, request
|
|
6
8
|
|
|
@@ -35,8 +37,8 @@ class d_log: # noqa: N801
|
|
|
35
37
|
def __init__(
|
|
36
38
|
self,
|
|
37
39
|
level: int = 0,
|
|
38
|
-
with_args: Union[
|
|
39
|
-
with_kwargs: Union[
|
|
40
|
+
with_args: Union[list, None] = None,
|
|
41
|
+
with_kwargs: Union[list, None] = None,
|
|
40
42
|
) -> None:
|
|
41
43
|
self.level = level
|
|
42
44
|
self.with_args = with_args if with_args is not None else []
|
|
@@ -44,7 +46,7 @@ class d_log: # noqa: N801
|
|
|
44
46
|
|
|
45
47
|
def __call__(self, method: Callable) -> Callable:
|
|
46
48
|
@functools.wraps(method)
|
|
47
|
-
def wrapper(*args: tuple, **kwargs:
|
|
49
|
+
def wrapper(*args: tuple, **kwargs: dict[str, Any]):
|
|
48
50
|
if not current_app.config["SQUEEZE_VERBOSE_LOGGING"]:
|
|
49
51
|
return method(*args, **kwargs)
|
|
50
52
|
|
|
@@ -3,7 +3,7 @@ from dataclasses import dataclass
|
|
|
3
3
|
|
|
4
4
|
import rcssmin
|
|
5
5
|
import rjsmin
|
|
6
|
-
from flask import Response
|
|
6
|
+
from flask import Response
|
|
7
7
|
|
|
8
8
|
from flask_squeeze.models import Minification
|
|
9
9
|
|
|
@@ -15,6 +15,15 @@ class MinificationResult:
|
|
|
15
15
|
duration: float
|
|
16
16
|
ratio: float
|
|
17
17
|
|
|
18
|
+
@property
|
|
19
|
+
def info(self) -> str:
|
|
20
|
+
return "; ".join(
|
|
21
|
+
[
|
|
22
|
+
f"ratio={self.ratio:.1f}x",
|
|
23
|
+
f"duration={self.duration * 1000:.1f}ms",
|
|
24
|
+
],
|
|
25
|
+
)
|
|
26
|
+
|
|
18
27
|
|
|
19
28
|
def minify_html(html_text: str) -> str:
|
|
20
29
|
"""
|
|
@@ -79,15 +88,13 @@ def minify(data: bytes, minify_choice: Minification) -> MinificationResult:
|
|
|
79
88
|
|
|
80
89
|
t0 = time.perf_counter()
|
|
81
90
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
raise ValueError(f"Invalid minify choice {minify_choice} at {request.path}")
|
|
90
|
-
minified = minified.encode("utf-8")
|
|
91
|
+
minifiers = {
|
|
92
|
+
Minification.html: lambda d: minify_html(d),
|
|
93
|
+
Minification.css: lambda d: minify_css(d),
|
|
94
|
+
Minification.js: lambda d: minify_js(d),
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
minified = minifiers[minify_choice](data.decode("utf-8")).encode("utf-8")
|
|
91
98
|
|
|
92
99
|
return MinificationResult(
|
|
93
100
|
data=minified,
|
|
@@ -99,5 +106,4 @@ def minify(data: bytes, minify_choice: Minification) -> MinificationResult:
|
|
|
99
106
|
|
|
100
107
|
def update_response_with_minified_data(response: Response, result: MinificationResult) -> None:
|
|
101
108
|
response.set_data(result.data)
|
|
102
|
-
response.headers["X-Flask-Squeeze-Minify
|
|
103
|
-
response.headers["X-Flask-Squeeze-Minify-Ratio"] = f"{result.ratio:.1f}x"
|
|
109
|
+
response.headers["X-Flask-Squeeze-Minify"] = result.info
|
|
@@ -34,7 +34,7 @@ def choose_encoding_from_headers_and_config(
|
|
|
34
34
|
If the client does not accept any of these encodings, or if the config
|
|
35
35
|
variable SQUEEZE_COMPRESS is False, return None.
|
|
36
36
|
"""
|
|
37
|
-
if not config.get("SQUEEZE_COMPRESS")
|
|
37
|
+
if not config.get("SQUEEZE_COMPRESS"):
|
|
38
38
|
return None
|
|
39
39
|
encoding = headers.get("Accept-Encoding", "").lower()
|
|
40
40
|
if "br" in encoding:
|
|
@@ -59,7 +59,7 @@ def choose_minification_from_mimetype_and_config(
|
|
|
59
59
|
"""
|
|
60
60
|
if mimetype is None:
|
|
61
61
|
return None
|
|
62
|
-
is_js_or_json = mimetype.endswith("javascript"
|
|
62
|
+
is_js_or_json = mimetype.endswith(("javascript", "json"))
|
|
63
63
|
if is_js_or_json and config.get("SQUEEZE_MINIFY_JS"):
|
|
64
64
|
return Minification.js
|
|
65
65
|
if mimetype.endswith("css") and config.get("SQUEEZE_MINIFY_CSS"):
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import secrets
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from flask import Response
|
|
8
|
+
|
|
9
|
+
from flask_squeeze.models import Encoding
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def add_breach_exploit_protection_header(response: Response) -> None:
|
|
13
|
+
"""
|
|
14
|
+
Protect against BREACH attack by adding random padding to the response.
|
|
15
|
+
"""
|
|
16
|
+
padding_length = secrets.randbelow(128) + 1
|
|
17
|
+
rand_str = secrets.token_urlsafe(padding_length)
|
|
18
|
+
response.headers["X-Flask-Squeeze-Breach-Protection"] = rand_str
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def update_response_headers(
|
|
22
|
+
response: Response,
|
|
23
|
+
original_content_length: int,
|
|
24
|
+
encode_choice: Encoding | None,
|
|
25
|
+
) -> None:
|
|
26
|
+
"""
|
|
27
|
+
Set the Content-Length header if it has changed.
|
|
28
|
+
Set the Content-Encoding header if compressed data is served.
|
|
29
|
+
"""
|
|
30
|
+
assert not response.direct_passthrough # At least one of minify or compress was run
|
|
31
|
+
|
|
32
|
+
if encode_choice is not None:
|
|
33
|
+
response.headers["Content-Encoding"] = encode_choice.value
|
|
34
|
+
vary = {x.strip() for x in response.headers.get("Vary", "").split(",")}
|
|
35
|
+
vary.add("Accept-Encoding")
|
|
36
|
+
vary.discard("")
|
|
37
|
+
response.headers["Vary"] = ",".join(vary)
|
|
38
|
+
|
|
39
|
+
if original_content_length != response.content_length:
|
|
40
|
+
response.headers["Content-Length"] = response.content_length
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.2
|
|
2
2
|
Name: flask-squeeze
|
|
3
|
-
Version: 3.3.
|
|
3
|
+
Version: 3.3.3
|
|
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.3"
|
|
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" }]
|
|
@@ -14,6 +14,12 @@ classifiers=[
|
|
|
14
14
|
"Topic :: Software Development :: Libraries :: Python Modules"
|
|
15
15
|
]
|
|
16
16
|
requires-python = ">=3.8, <3.14"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
########################################################################################
|
|
20
|
+
#### MARK: Dependencies
|
|
21
|
+
|
|
22
|
+
|
|
17
23
|
dependencies = [
|
|
18
24
|
"flask>=1",
|
|
19
25
|
"brotli~=1.1",
|
|
@@ -25,9 +31,14 @@ dependencies = [
|
|
|
25
31
|
[dependency-groups]
|
|
26
32
|
dev = [
|
|
27
33
|
"pytest-cov ~= 4.0.0",
|
|
34
|
+
"ruff>=0.9.3",
|
|
28
35
|
]
|
|
29
36
|
|
|
30
37
|
|
|
38
|
+
########################################################################################
|
|
39
|
+
#### MARK: Packaging
|
|
40
|
+
|
|
41
|
+
|
|
31
42
|
[tool.setuptools]
|
|
32
43
|
packages = ["flask_squeeze"]
|
|
33
44
|
license-files = [] # Workaround for https://github.com/astral-sh/uv/issues/9513
|
|
@@ -37,32 +48,45 @@ license-files = [] # Workaround for https://github.com/astral-sh/uv/issues/9513
|
|
|
37
48
|
package = true
|
|
38
49
|
|
|
39
50
|
|
|
51
|
+
########################################################################################
|
|
52
|
+
#### MARK: Ruff
|
|
53
|
+
|
|
54
|
+
|
|
40
55
|
[tool.ruff]
|
|
41
56
|
show-fixes = true
|
|
42
57
|
line-length = 120
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
"E", # style errors
|
|
48
|
-
"F", # flakes
|
|
49
|
-
"I", # import sorting
|
|
50
|
-
"M", # meta
|
|
51
|
-
"N", # naming
|
|
52
|
-
"U", # upgrade
|
|
53
|
-
"W", # style warnings
|
|
54
|
-
"YTT", # sys.version
|
|
55
|
-
]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
[tool.ruff.lint]
|
|
61
|
+
select = ["ALL"]
|
|
56
62
|
ignore = [
|
|
57
|
-
"ANN101", # missing type annotation for self
|
|
58
63
|
"ANN202", # Missing return type annotation for private function
|
|
59
64
|
"E501", # line length
|
|
60
65
|
"UP006", # use Dict (not possible in python 3.8)
|
|
61
66
|
"UP007", # use X | Y for union (not possible in python 3.8)
|
|
62
67
|
"UP035", # use typing Dict and List (not possible in python 3.8)
|
|
63
68
|
"W191", # indentation contains tabs
|
|
69
|
+
"S101", # Use of `assert` detected
|
|
70
|
+
"ERA001", # Found commented-out code
|
|
71
|
+
"D", # docstrings
|
|
72
|
+
"T201", # `print` found
|
|
73
|
+
"FBT001", # Boolean-typed positional argument in function definition
|
|
74
|
+
"INP001", # File is part of an implicit namespace package. Add an `__init__.py`.
|
|
75
|
+
"FIX002", # Line contains TODO, consider resolving the issue
|
|
76
|
+
"TD002", # Missing author in TODO; try: `# TODO(<author_name>): ...`
|
|
77
|
+
"TD003", # Missing issue link on the line following this TODO
|
|
64
78
|
]
|
|
65
79
|
|
|
80
|
+
|
|
66
81
|
[tool.ruff.format]
|
|
67
82
|
indent-style = "tab"
|
|
68
83
|
quote-style = "double"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
########################################################################################
|
|
87
|
+
#### MARK: Testing
|
|
88
|
+
|
|
89
|
+
[tool.coverage.report]
|
|
90
|
+
exclude_also = [
|
|
91
|
+
"if TYPE_CHECKING:",
|
|
92
|
+
]
|
|
@@ -1,17 +1,20 @@
|
|
|
1
|
-
import os
|
|
2
1
|
import tempfile
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Any, Generator
|
|
3
4
|
|
|
4
5
|
import pytest
|
|
5
6
|
from flask.testing import FlaskClient
|
|
6
7
|
from test_app import create_app
|
|
7
8
|
from werkzeug.wrappers import Response
|
|
8
9
|
|
|
10
|
+
STATUS_CODE_NOT_FOUND_404 = 404
|
|
11
|
+
|
|
9
12
|
########################################################################################
|
|
10
13
|
#### MARK: Fixtures
|
|
11
14
|
|
|
12
15
|
|
|
13
16
|
@pytest.fixture
|
|
14
|
-
def client():
|
|
17
|
+
def client() -> Generator[FlaskClient, Any, None]:
|
|
15
18
|
app = create_app()
|
|
16
19
|
app.testing = True
|
|
17
20
|
with app.test_client() as test_client:
|
|
@@ -19,17 +22,17 @@ def client(): # noqa
|
|
|
19
22
|
|
|
20
23
|
|
|
21
24
|
@pytest.fixture(params=["", "gzip", "br", "deflate"])
|
|
22
|
-
def use_encoding(request):
|
|
25
|
+
def use_encoding(request: pytest.FixtureRequest) -> str:
|
|
23
26
|
return request.param
|
|
24
27
|
|
|
25
28
|
|
|
26
29
|
@pytest.fixture(params=[False, True])
|
|
27
|
-
def use_minify_js(request):
|
|
30
|
+
def use_minify_js(request: pytest.FixtureRequest) -> bool:
|
|
28
31
|
return request.param
|
|
29
32
|
|
|
30
33
|
|
|
31
34
|
@pytest.fixture(params=[False, True])
|
|
32
|
-
def use_minify_css(request):
|
|
35
|
+
def use_minify_css(request: pytest.FixtureRequest) -> bool:
|
|
33
36
|
return request.param
|
|
34
37
|
|
|
35
38
|
|
|
@@ -37,7 +40,7 @@ def use_minify_css(request):
|
|
|
37
40
|
#### MARK: Utilities
|
|
38
41
|
|
|
39
42
|
|
|
40
|
-
def almost_equal(a, b, percent=0.01):
|
|
43
|
+
def almost_equal(a: float, b: float, percent: float = 0.01) -> bool:
|
|
41
44
|
diff = abs(int(a) - int(b))
|
|
42
45
|
return diff < percent * int(a) and diff < percent * int(b)
|
|
43
46
|
|
|
@@ -54,7 +57,7 @@ def test_get_index(client: FlaskClient, use_encoding: str) -> None:
|
|
|
54
57
|
print("test_get_index")
|
|
55
58
|
r = client.get("/", headers={"Accept-Encoding": use_encoding})
|
|
56
59
|
assert content_length_correct(r)
|
|
57
|
-
length = r.headers.get("Content-Length")
|
|
60
|
+
length = int(r.headers.get("Content-Length", "0"))
|
|
58
61
|
encoding = r.headers.get("Content-Encoding", "")
|
|
59
62
|
|
|
60
63
|
assert use_encoding == encoding
|
|
@@ -74,7 +77,7 @@ def test_get_css_file(client: FlaskClient, use_encoding: str, use_minify_css: bo
|
|
|
74
77
|
client.application.config.update({"SQUEEZE_MINIFY_CSS": use_minify_css})
|
|
75
78
|
r = client.get("/static/fomantic.css", headers={"Accept-Encoding": use_encoding})
|
|
76
79
|
assert content_length_correct(r)
|
|
77
|
-
response_length = r.headers.get("Content-Length")
|
|
80
|
+
response_length = int(r.headers.get("Content-Length", "0"))
|
|
78
81
|
encoding = r.headers.get("Content-Encoding", "")
|
|
79
82
|
|
|
80
83
|
assert use_encoding == encoding
|
|
@@ -107,7 +110,6 @@ def test_get_jquery_no_minify(client: FlaskClient) -> None:
|
|
|
107
110
|
assert content_length_correct(r_orig)
|
|
108
111
|
assert "Content-Encoding" not in r_orig.headers
|
|
109
112
|
assert r_orig.headers["Content-Length"] == "292458"
|
|
110
|
-
assert "X-Uncompressed-Content-Length" not in r_orig.headers
|
|
111
113
|
|
|
112
114
|
|
|
113
115
|
def test_get_from_cache(client: FlaskClient, use_encoding: str) -> None:
|
|
@@ -119,7 +121,7 @@ def test_get_from_cache(client: FlaskClient, use_encoding: str) -> None:
|
|
|
119
121
|
|
|
120
122
|
def test_get_unknown_url(client: FlaskClient) -> None:
|
|
121
123
|
r = client.get("/static/unknown.js", headers={"Accept-Encoding": "gzip"})
|
|
122
|
-
assert r.status_code ==
|
|
124
|
+
assert r.status_code == STATUS_CODE_NOT_FOUND_404
|
|
123
125
|
|
|
124
126
|
|
|
125
127
|
def test_get_same_repeatedly(client: FlaskClient) -> None:
|
|
@@ -141,7 +143,7 @@ def test_get_same_repeatedly(client: FlaskClient) -> None:
|
|
|
141
143
|
|
|
142
144
|
|
|
143
145
|
def response_has_breach_header(r: Response) -> bool:
|
|
144
|
-
return "X-Breach-
|
|
146
|
+
return "X-Flask-Squeeze-Breach-Protection" in r.headers
|
|
145
147
|
|
|
146
148
|
|
|
147
149
|
def response_has_vary_header(r: Response) -> bool:
|
|
@@ -163,17 +165,21 @@ def test_disable_compression(client: FlaskClient) -> None:
|
|
|
163
165
|
def test_disable_minification(client: FlaskClient) -> None:
|
|
164
166
|
"""Test that minification can be disabled."""
|
|
165
167
|
client.application.config.update(
|
|
166
|
-
{
|
|
168
|
+
{
|
|
169
|
+
"SQUEEZE_MINIFY_JS": False,
|
|
170
|
+
"SQUEEZE_MINIFY_CSS": False,
|
|
171
|
+
"SQUEEZE_MINIFY_HTML": False,
|
|
172
|
+
},
|
|
167
173
|
)
|
|
168
174
|
r = client.get("/static/jquery.js", headers={"Accept-Encoding": "gzip"})
|
|
169
|
-
assert "X-Flask-Squeeze-Minify
|
|
175
|
+
assert "X-Flask-Squeeze-Minify" not in r.headers
|
|
170
176
|
|
|
171
177
|
|
|
172
178
|
def test_html_response_minification(client: FlaskClient) -> None:
|
|
173
179
|
"""Test minification of HTML responses."""
|
|
174
180
|
client.application.config.update({"SQUEEZE_MINIFY_HTML": True})
|
|
175
181
|
r = client.get("/", headers={"Accept-Encoding": "gzip"})
|
|
176
|
-
assert "X-Flask-Squeeze-Minify
|
|
182
|
+
assert "X-Flask-Squeeze-Minify" in r.headers, r.headers
|
|
177
183
|
|
|
178
184
|
|
|
179
185
|
def test_breach_header_presence(client: FlaskClient) -> None:
|
|
@@ -193,47 +199,76 @@ def test_minification_and_compression_together(client: FlaskClient) -> None:
|
|
|
193
199
|
client.application.config.update({"SQUEEZE_MINIFY_CSS": True})
|
|
194
200
|
r = client.get("/static/fomantic.css", headers={"Accept-Encoding": "gzip"})
|
|
195
201
|
assert "Content-Encoding" in r.headers
|
|
196
|
-
assert "X-Flask-Squeeze-Minify
|
|
202
|
+
assert "X-Flask-Squeeze-Minify" in r.headers
|
|
197
203
|
assert content_length_correct(r)
|
|
198
204
|
|
|
199
205
|
|
|
200
|
-
def
|
|
201
|
-
|
|
202
|
-
|
|
206
|
+
def test_no_minify_no_compress(client: FlaskClient) -> None:
|
|
207
|
+
client.application.config.update(
|
|
208
|
+
{
|
|
209
|
+
"SQUEEZE_MINIFY_JS": False,
|
|
210
|
+
"SQUEEZE_MINIFY_CSS": False,
|
|
211
|
+
"SQUEEZE_MINIFY_HTML": False,
|
|
212
|
+
"SQUEEZE_COMPRESS": False,
|
|
213
|
+
},
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
# Static file with no minification or compression
|
|
217
|
+
|
|
203
218
|
r = client.get("/static/fomantic.css", headers={"Accept-Encoding": "gzip"})
|
|
204
|
-
assert "
|
|
205
|
-
assert "X-Flask-Squeeze-
|
|
219
|
+
assert "Content-Encoding" not in r.headers
|
|
220
|
+
assert "X-Flask-Squeeze-Minify" not in r.headers
|
|
221
|
+
assert "X-Flask-Squeeze-Compress" not in r.headers
|
|
206
222
|
|
|
223
|
+
# Dynamic file with no minification or compression
|
|
207
224
|
|
|
208
|
-
|
|
225
|
+
r = client.get("/", headers={"Accept-Encoding": "gzip"})
|
|
226
|
+
assert "Content-Encoding" not in r.headers
|
|
227
|
+
assert "X-Flask-Squeeze-Minify" not in r.headers
|
|
228
|
+
assert "X-Flask-Squeeze-Compress" not in r.headers
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def test_static_file_cache_behavior(
|
|
232
|
+
client: FlaskClient,
|
|
233
|
+
use_encoding: str,
|
|
234
|
+
use_minify_css: bool,
|
|
235
|
+
) -> None:
|
|
209
236
|
"""Test cache behavior for a temporary static file."""
|
|
210
237
|
|
|
238
|
+
# Skip if encoding is not set
|
|
239
|
+
if not use_encoding:
|
|
240
|
+
return
|
|
241
|
+
|
|
242
|
+
client.application.config.update({"SQUEEZE_MINIFY_CSS": use_minify_css})
|
|
243
|
+
|
|
211
244
|
# Ensure the static directory is set
|
|
212
245
|
if (static_dir := client.application.static_folder) is None:
|
|
213
|
-
|
|
246
|
+
msg = "Static directory not found"
|
|
247
|
+
raise ValueError(msg)
|
|
214
248
|
|
|
215
249
|
# Use a temporary file within the static directory
|
|
216
|
-
with tempfile.NamedTemporaryFile(dir=static_dir, suffix=".
|
|
250
|
+
with tempfile.NamedTemporaryFile(dir=static_dir, suffix=".css", delete=True) as temp_file:
|
|
217
251
|
file_path = temp_file.name
|
|
218
|
-
|
|
252
|
+
url_path = "/static/" + Path(file_path).name
|
|
253
|
+
temp_file.write(b"body { color: #000; } " * 1000)
|
|
219
254
|
temp_file.flush() # Ensure content is written to disk
|
|
220
255
|
|
|
221
256
|
# First request: MISS
|
|
222
|
-
r = client.get(
|
|
257
|
+
r = client.get(url_path, headers={"Accept-Encoding": use_encoding})
|
|
223
258
|
assert r.headers.get("X-Flask-Squeeze-Cache") == "MISS"
|
|
224
259
|
|
|
225
260
|
# Second request: HIT
|
|
226
|
-
r = client.get(
|
|
261
|
+
r = client.get(url_path, headers={"Accept-Encoding": use_encoding})
|
|
227
262
|
assert r.headers.get("X-Flask-Squeeze-Cache") == "HIT"
|
|
228
263
|
|
|
229
264
|
# Modify the file content
|
|
230
|
-
temp_file.write(b"
|
|
265
|
+
temp_file.write(b"body { color: #123456; } " * 1000)
|
|
231
266
|
temp_file.flush() # Ensure the new content is written
|
|
232
267
|
|
|
233
268
|
# Third request: MISS
|
|
234
|
-
r = client.get(
|
|
269
|
+
r = client.get(url_path, headers={"Accept-Encoding": use_encoding})
|
|
235
270
|
assert r.headers.get("X-Flask-Squeeze-Cache") == "MISS"
|
|
236
271
|
|
|
237
272
|
# Fourth request: HIT
|
|
238
|
-
r = client.get(
|
|
273
|
+
r = client.get(url_path, headers={"Accept-Encoding": use_encoding})
|
|
239
274
|
assert r.headers.get("X-Flask-Squeeze-Cache") == "HIT"
|
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import functools
|
|
2
|
-
import time
|
|
3
|
-
from collections.abc import Callable
|
|
4
|
-
from typing import Any, Dict, Tuple
|
|
5
|
-
|
|
6
|
-
from flask import Response, current_app
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
def _write_benchmark_debug_header(response: Response, header_name: str, t1: float, t2: float) -> None:
|
|
10
|
-
if current_app.config["SQUEEZE_ADD_DEBUG_HEADERS"]:
|
|
11
|
-
dur_ms_str = f"{(t2 - t1) * 1000:.1f}ms"
|
|
12
|
-
response.headers[header_name] = dur_ms_str
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
class add_debug_header: # noqa: N801
|
|
16
|
-
def __init__(self, header_name: str) -> None:
|
|
17
|
-
self.header_name = header_name
|
|
18
|
-
|
|
19
|
-
def get_response(self, args: Tuple, kwargs: Dict) -> Response:
|
|
20
|
-
for arg in args:
|
|
21
|
-
if isinstance(arg, Response):
|
|
22
|
-
return arg
|
|
23
|
-
for kwarg in kwargs.values():
|
|
24
|
-
if isinstance(kwarg, Response):
|
|
25
|
-
return kwarg
|
|
26
|
-
raise ValueError(
|
|
27
|
-
"You can only deocrate a function with 'add_debug_header' that has a Response as an argument or kwarg."
|
|
28
|
-
)
|
|
29
|
-
|
|
30
|
-
def __call__(self, method: Callable) -> Callable:
|
|
31
|
-
@functools.wraps(method)
|
|
32
|
-
def wrapper(*args: tuple, **kwargs: Dict[str, Any]):
|
|
33
|
-
if not current_app.config["SQUEEZE_ADD_DEBUG_HEADERS"]:
|
|
34
|
-
return method(*args, **kwargs)
|
|
35
|
-
|
|
36
|
-
response = self.get_response(args, kwargs)
|
|
37
|
-
t1 = time.perf_counter()
|
|
38
|
-
res = method(*args, **kwargs)
|
|
39
|
-
t2 = time.perf_counter()
|
|
40
|
-
|
|
41
|
-
_write_benchmark_debug_header(response, self.header_name, t1, t2)
|
|
42
|
-
return res
|
|
43
|
-
|
|
44
|
-
return wrapper
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import secrets
|
|
2
|
-
|
|
3
|
-
from flask import Response
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
def add_breach_exploit_protection_header(response: Response) -> None:
|
|
7
|
-
"""
|
|
8
|
-
Protect against BREACH attack by adding random padding to the response.
|
|
9
|
-
"""
|
|
10
|
-
padding_length = secrets.randbelow(128) + 1
|
|
11
|
-
rand_str = secrets.token_urlsafe(padding_length)
|
|
12
|
-
response.headers["X-Breach-Exploit-Protection-Padding"] = rand_str
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|