flask-squeeze 3.3.4__tar.gz → 3.4.0__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.4 → flask_squeeze-3.4.0}/PKG-INFO +37 -5
- {flask_squeeze-3.3.4 → flask_squeeze-3.4.0}/README.md +35 -4
- flask_squeeze-3.4.0/flask_squeeze/cache.py +101 -0
- {flask_squeeze-3.3.4 → flask_squeeze-3.4.0}/flask_squeeze/compress.py +13 -9
- {flask_squeeze-3.3.4 → flask_squeeze-3.4.0}/flask_squeeze/flask_squeeze.py +16 -10
- {flask_squeeze-3.3.4 → flask_squeeze-3.4.0}/flask_squeeze/minify.py +23 -17
- flask_squeeze-3.4.0/flask_squeeze/models.py +71 -0
- {flask_squeeze-3.3.4 → flask_squeeze-3.4.0}/flask_squeeze/utils.py +3 -3
- {flask_squeeze-3.3.4 → flask_squeeze-3.4.0}/flask_squeeze.egg-info/PKG-INFO +37 -5
- {flask_squeeze-3.3.4 → flask_squeeze-3.4.0}/flask_squeeze.egg-info/SOURCES.txt +3 -1
- {flask_squeeze-3.3.4 → flask_squeeze-3.4.0}/flask_squeeze.egg-info/requires.txt +1 -0
- {flask_squeeze-3.3.4 → flask_squeeze-3.4.0}/pyproject.toml +32 -20
- flask_squeeze-3.4.0/tests/test_compress.py +8 -0
- flask_squeeze-3.4.0/tests/test_flask_squeeze.py +760 -0
- flask_squeeze-3.4.0/tests/test_minify.py +8 -0
- flask_squeeze-3.3.4/flask_squeeze/cache.py +0 -45
- flask_squeeze-3.3.4/flask_squeeze/models.py +0 -69
- flask_squeeze-3.3.4/tests/test_flask_squeeze.py +0 -319
- {flask_squeeze-3.3.4 → flask_squeeze-3.4.0}/LICENSE +0 -0
- {flask_squeeze-3.3.4 → flask_squeeze-3.4.0}/flask_squeeze/__init__.py +0 -0
- {flask_squeeze-3.3.4 → flask_squeeze-3.4.0}/flask_squeeze/log.py +0 -0
- {flask_squeeze-3.3.4 → flask_squeeze-3.4.0}/flask_squeeze.egg-info/dependency_links.txt +0 -0
- {flask_squeeze-3.3.4 → flask_squeeze-3.4.0}/flask_squeeze.egg-info/top_level.txt +0 -0
- {flask_squeeze-3.3.4 → flask_squeeze-3.4.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: flask-squeeze
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.4.0
|
|
4
4
|
Summary: Compress and minify Flask responses!
|
|
5
5
|
Author-email: Marcel Kröker <kroeker.marcel@gmail.com>
|
|
6
6
|
License: MIT License
|
|
@@ -34,6 +34,7 @@ Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
|
34
34
|
Requires-Python: <3.14,>=3.8
|
|
35
35
|
Description-Content-Type: text/markdown
|
|
36
36
|
Requires-Dist: flask>=1
|
|
37
|
+
Requires-Dist: werkzeug>=0
|
|
37
38
|
Requires-Dist: brotli~=1.1
|
|
38
39
|
Requires-Dist: rjsmin~=1.2
|
|
39
40
|
Requires-Dist: rcssmin~=1.2
|
|
@@ -45,13 +46,16 @@ Requires-Dist: rcssmin~=1.2
|
|
|
45
46
|

|
|
46
47
|
|
|
47
48
|
Flask-Squeeze is a Flask extension that automatically:
|
|
48
|
-
- **Minifies**
|
|
49
|
+
- **Minifies** responses with the mimetypes javascript and css
|
|
49
50
|
- **Compresses** all responses with brotli if the browser supports it, or gzip if the browser supports it!
|
|
50
51
|
- **Protects** against the BREACH exploit
|
|
51
|
-
- **Caches** static files so that they don't have to be re-compressed.
|
|
52
|
+
- **Caches** static files so that they don't have to be re-compressed. By default, the cache is in-memory and will be cleared each time Flask restarts. With persistent caching enabled, compressed responses are saved to disk and survive server restarts.
|
|
53
|
+
- **Persistent caching** (optional) saves compressed static files to disk, improving startup times and reducing CPU usage across server restarts
|
|
54
|
+
|
|
55
|
+
Files are considered static if the substring "/static/" is in their request path.
|
|
52
56
|
|
|
53
57
|
## Compatibility
|
|
54
|
-
- Tested with Python 3.
|
|
58
|
+
- Tested with Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13
|
|
55
59
|
|
|
56
60
|
## Installation
|
|
57
61
|
```
|
|
@@ -86,8 +90,36 @@ You can configure Flask-Squeeze with the following options in your [Flask config
|
|
|
86
90
|
| --- | --- | --- |
|
|
87
91
|
| `SQUEEZE_COMPRESS` | `True` | Enables or disables compression |
|
|
88
92
|
| `SQUEEZE_MIN_SIZE` | `500` | Defines the minimum file size in bytes to activate the compression |
|
|
93
|
+
| `SQUEEZE_CACHE_DIR` | `None` | Directory to store persistent cache files. If `None`, only in-memory caching is used |
|
|
89
94
|
| `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
95
|
|
|
96
|
+
### Persistent Caching
|
|
97
|
+
Flask-Squeeze supports persistent caching of compressed static files. When enabled, compressed responses are saved to disk and reloaded on server restart, eliminating the need to recompress unchanged files.
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
app.config['SQUEEZE_CACHE_DIR'] = './cache/flask_squeeze/' # Enable persistent caching
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Benefits:
|
|
104
|
+
- **Faster server startup**: No need to recompress static files on restart
|
|
105
|
+
- **Reduced CPU usage**: Avoid redundant compression operations
|
|
106
|
+
- **Consistent performance**: Immediate cache hits after restart
|
|
107
|
+
|
|
108
|
+
Cache files are automatically managed:
|
|
109
|
+
- Cache entries are validated using file content hashes
|
|
110
|
+
- Stale cache entries are automatically replaced when files change
|
|
111
|
+
- Use `squeeze.clear_cache()` to manually clear the cache
|
|
112
|
+
|
|
113
|
+
#### Cache Management
|
|
114
|
+
```python
|
|
115
|
+
from flask_squeeze import Squeeze
|
|
116
|
+
|
|
117
|
+
squeeze = Squeeze(app)
|
|
118
|
+
|
|
119
|
+
# Clear all cached files (memory and disk)
|
|
120
|
+
squeeze.clear_cache()
|
|
121
|
+
```
|
|
122
|
+
|
|
91
123
|
### Minification options
|
|
92
124
|
| Option | Default | Description |
|
|
93
125
|
| --- | --- | --- |
|
|
@@ -95,7 +127,7 @@ You can configure Flask-Squeeze with the following options in your [Flask config
|
|
|
95
127
|
| `SQUEEZE_MINIFY_JS` | `True` | Enable or disable js minification using rjsmin |
|
|
96
128
|
|
|
97
129
|
### Compression level options
|
|
98
|
-
> Static files are
|
|
130
|
+
> Static files are cached, so they only have to be compressed once (and are persisted to disk if `SQUEEZE_CACHE_DIR` is configured).
|
|
99
131
|
> Dynamic files like generated HTML files will not be cached, so they will be compressed for each response.
|
|
100
132
|
|
|
101
133
|
| Option | Default | Description |
|
|
@@ -5,13 +5,16 @@
|
|
|
5
5
|

|
|
6
6
|
|
|
7
7
|
Flask-Squeeze is a Flask extension that automatically:
|
|
8
|
-
- **Minifies**
|
|
8
|
+
- **Minifies** responses with the mimetypes javascript and css
|
|
9
9
|
- **Compresses** all responses with brotli if the browser supports it, or gzip if the browser supports it!
|
|
10
10
|
- **Protects** against the BREACH exploit
|
|
11
|
-
- **Caches** static files so that they don't have to be re-compressed.
|
|
11
|
+
- **Caches** static files so that they don't have to be re-compressed. By default, the cache is in-memory and will be cleared each time Flask restarts. With persistent caching enabled, compressed responses are saved to disk and survive server restarts.
|
|
12
|
+
- **Persistent caching** (optional) saves compressed static files to disk, improving startup times and reducing CPU usage across server restarts
|
|
13
|
+
|
|
14
|
+
Files are considered static if the substring "/static/" is in their request path.
|
|
12
15
|
|
|
13
16
|
## Compatibility
|
|
14
|
-
- Tested with Python 3.
|
|
17
|
+
- Tested with Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13
|
|
15
18
|
|
|
16
19
|
## Installation
|
|
17
20
|
```
|
|
@@ -46,8 +49,36 @@ You can configure Flask-Squeeze with the following options in your [Flask config
|
|
|
46
49
|
| --- | --- | --- |
|
|
47
50
|
| `SQUEEZE_COMPRESS` | `True` | Enables or disables compression |
|
|
48
51
|
| `SQUEEZE_MIN_SIZE` | `500` | Defines the minimum file size in bytes to activate the compression |
|
|
52
|
+
| `SQUEEZE_CACHE_DIR` | `None` | Directory to store persistent cache files. If `None`, only in-memory caching is used |
|
|
49
53
|
| `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
54
|
|
|
55
|
+
### Persistent Caching
|
|
56
|
+
Flask-Squeeze supports persistent caching of compressed static files. When enabled, compressed responses are saved to disk and reloaded on server restart, eliminating the need to recompress unchanged files.
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
app.config['SQUEEZE_CACHE_DIR'] = './cache/flask_squeeze/' # Enable persistent caching
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Benefits:
|
|
63
|
+
- **Faster server startup**: No need to recompress static files on restart
|
|
64
|
+
- **Reduced CPU usage**: Avoid redundant compression operations
|
|
65
|
+
- **Consistent performance**: Immediate cache hits after restart
|
|
66
|
+
|
|
67
|
+
Cache files are automatically managed:
|
|
68
|
+
- Cache entries are validated using file content hashes
|
|
69
|
+
- Stale cache entries are automatically replaced when files change
|
|
70
|
+
- Use `squeeze.clear_cache()` to manually clear the cache
|
|
71
|
+
|
|
72
|
+
#### Cache Management
|
|
73
|
+
```python
|
|
74
|
+
from flask_squeeze import Squeeze
|
|
75
|
+
|
|
76
|
+
squeeze = Squeeze(app)
|
|
77
|
+
|
|
78
|
+
# Clear all cached files (memory and disk)
|
|
79
|
+
squeeze.clear_cache()
|
|
80
|
+
```
|
|
81
|
+
|
|
51
82
|
### Minification options
|
|
52
83
|
| Option | Default | Description |
|
|
53
84
|
| --- | --- | --- |
|
|
@@ -55,7 +86,7 @@ You can configure Flask-Squeeze with the following options in your [Flask config
|
|
|
55
86
|
| `SQUEEZE_MINIFY_JS` | `True` | Enable or disable js minification using rjsmin |
|
|
56
87
|
|
|
57
88
|
### Compression level options
|
|
58
|
-
> Static files are
|
|
89
|
+
> Static files are cached, so they only have to be compressed once (and are persisted to disk if `SQUEEZE_CACHE_DIR` is configured).
|
|
59
90
|
> Dynamic files like generated HTML files will not be cached, so they will be compressed for each response.
|
|
60
91
|
|
|
61
92
|
| Option | Default | Description |
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .models import Encoding
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
########################################################################################
|
|
13
|
+
#### MARK: Disk utils
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _save_cache_entry_to_disk(
|
|
17
|
+
cache_dir: Path,
|
|
18
|
+
cache_key: CacheKey,
|
|
19
|
+
original_hash: str,
|
|
20
|
+
data: bytes,
|
|
21
|
+
) -> None:
|
|
22
|
+
# Save metadata
|
|
23
|
+
with (cache_dir / f"{cache_key.normalized}.meta").open("w") as f:
|
|
24
|
+
f.write(original_hash)
|
|
25
|
+
|
|
26
|
+
# Save data
|
|
27
|
+
with (cache_dir / f"{cache_key.normalized}.cache").open("wb") as f:
|
|
28
|
+
f.write(data)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _read_cache_data_from_disk(cache_dir: Path) -> dict[str, tuple[str, bytes]]:
|
|
32
|
+
data: dict[str, tuple[str, bytes]] = {}
|
|
33
|
+
|
|
34
|
+
for meta_file in cache_dir.glob("*.meta"):
|
|
35
|
+
cache_key = meta_file.stem
|
|
36
|
+
with meta_file.open() as f:
|
|
37
|
+
original_hash = f.read()
|
|
38
|
+
|
|
39
|
+
cache_file = meta_file.with_suffix(".cache")
|
|
40
|
+
if cache_file.exists():
|
|
41
|
+
with cache_file.open("rb") as f:
|
|
42
|
+
cached_bytes = f.read()
|
|
43
|
+
|
|
44
|
+
data[cache_key] = (original_hash, cached_bytes)
|
|
45
|
+
|
|
46
|
+
return data
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
########################################################################################
|
|
50
|
+
#### MARK: Cache
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class CacheKey:
|
|
55
|
+
path: str
|
|
56
|
+
encoding: Encoding | None
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def normalized(self) -> str:
|
|
60
|
+
flat_path = self.path.replace("/", "_")
|
|
61
|
+
encoding = self.encoding.value if self.encoding else "none"
|
|
62
|
+
return f"{flat_path}.{encoding}"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class CachedData:
|
|
67
|
+
original_hash: str
|
|
68
|
+
data: bytes
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class Cache:
|
|
73
|
+
data: dict[str, tuple[str, bytes]]
|
|
74
|
+
""" Maps request path to original data hash and compressed bytes """
|
|
75
|
+
|
|
76
|
+
cache_dir: Path | None = None
|
|
77
|
+
""" Directory to store persistent cache files """
|
|
78
|
+
|
|
79
|
+
def __post_init__(self) -> None:
|
|
80
|
+
"""Initialize cache directory if specified."""
|
|
81
|
+
if self.cache_dir is not None:
|
|
82
|
+
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
|
83
|
+
self.data.update(_read_cache_data_from_disk(self.cache_dir))
|
|
84
|
+
|
|
85
|
+
def get(self, cache_key: CacheKey) -> CachedData | None:
|
|
86
|
+
"""Get the cached hash and data for a given cache key."""
|
|
87
|
+
|
|
88
|
+
if cache_key.normalized not in self.data:
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
original_hash, data = self.data[cache_key.normalized]
|
|
92
|
+
return CachedData(original_hash, data)
|
|
93
|
+
|
|
94
|
+
def set(self, cache_key: CacheKey, original_hash: str, data: bytes) -> None:
|
|
95
|
+
"""Set the cached data for a given cache key."""
|
|
96
|
+
|
|
97
|
+
self.data[cache_key.normalized] = (original_hash, data)
|
|
98
|
+
|
|
99
|
+
# Save to disk if persistent caching is enabled
|
|
100
|
+
if self.cache_dir is not None:
|
|
101
|
+
_save_cache_entry_to_disk(self.cache_dir, cache_key, original_hash, data)
|
|
@@ -31,22 +31,26 @@ class CompressionInfo:
|
|
|
31
31
|
|
|
32
32
|
def compress(
|
|
33
33
|
data: bytes,
|
|
34
|
-
|
|
34
|
+
encoding: Encoding,
|
|
35
35
|
quality: int,
|
|
36
36
|
) -> tuple[bytes, CompressionInfo]:
|
|
37
37
|
t0 = time.perf_counter()
|
|
38
38
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
39
|
+
if encoding is Encoding.br:
|
|
40
|
+
compressed_data = brotli.compress(data, quality=quality)
|
|
41
|
+
elif encoding is Encoding.deflate:
|
|
42
|
+
compressed_data = zlib.compress(data, level=quality)
|
|
43
|
+
elif encoding is Encoding.gzip:
|
|
44
|
+
compressed_data = gzip.compress(data, compresslevel=quality)
|
|
45
|
+
else:
|
|
46
|
+
msg = f"Unsupported encoding: {encoding}"
|
|
47
|
+
raise ValueError(msg)
|
|
44
48
|
|
|
45
|
-
|
|
49
|
+
ratio = len(data) / len(compressed_data) if len(compressed_data) > 0 else 1.0
|
|
46
50
|
|
|
47
51
|
return compressed_data, CompressionInfo(
|
|
48
|
-
encoding=
|
|
52
|
+
encoding=encoding,
|
|
49
53
|
quality=quality,
|
|
50
54
|
duration=time.perf_counter() - t0,
|
|
51
|
-
ratio=
|
|
55
|
+
ratio=ratio,
|
|
52
56
|
)
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import hashlib
|
|
4
|
+
from pathlib import Path
|
|
4
5
|
|
|
5
6
|
from flask import Flask, Response, request
|
|
6
7
|
|
|
@@ -8,13 +9,7 @@ from .cache import Cache, CacheKey
|
|
|
8
9
|
from .compress import CompressionInfo, compress
|
|
9
10
|
from .log import d_log, log
|
|
10
11
|
from .minify import MinificationInfo, minify
|
|
11
|
-
from .models import
|
|
12
|
-
Encoding,
|
|
13
|
-
Minification,
|
|
14
|
-
ResourceType,
|
|
15
|
-
choose_encoding_from_headers_and_config,
|
|
16
|
-
choose_minification_from_mimetype_and_config,
|
|
17
|
-
)
|
|
12
|
+
from .models import Encoding, Minification, ResourceType
|
|
18
13
|
from .utils import add_breach_exploit_protection_header, update_response_headers
|
|
19
14
|
|
|
20
15
|
|
|
@@ -27,7 +22,6 @@ class Squeeze:
|
|
|
27
22
|
|
|
28
23
|
def __init__(self, app: Flask | None = None) -> None:
|
|
29
24
|
"""Initialize Flask-Squeeze with or without app."""
|
|
30
|
-
self.cache_static = Cache(data={})
|
|
31
25
|
if app is None:
|
|
32
26
|
return
|
|
33
27
|
self.app = app
|
|
@@ -50,9 +44,21 @@ class Squeeze:
|
|
|
50
44
|
app.config.setdefault("SQUEEZE_MINIFY_JS", True)
|
|
51
45
|
app.config.setdefault("SQUEEZE_MINIFY_CSS", True)
|
|
52
46
|
app.config.setdefault("SQUEEZE_MINIFY_HTML", True)
|
|
47
|
+
# Caching options
|
|
48
|
+
app.config.setdefault("SQUEEZE_CACHE_DIR", None)
|
|
53
49
|
# Logging options
|
|
54
50
|
app.config.setdefault("SQUEEZE_VERBOSE_LOGGING", False)
|
|
55
51
|
|
|
52
|
+
# Initialize cache
|
|
53
|
+
|
|
54
|
+
cache_dir = app.config.get("SQUEEZE_CACHE_DIR")
|
|
55
|
+
self.cache_static = Cache(
|
|
56
|
+
data={},
|
|
57
|
+
cache_dir=Path(cache_dir) if cache_dir else None,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
# Initialize after_request hook
|
|
61
|
+
|
|
56
62
|
if (
|
|
57
63
|
app.config["SQUEEZE_COMPRESS"]
|
|
58
64
|
or app.config["SQUEEZE_MINIFY_JS"]
|
|
@@ -205,12 +211,12 @@ class Squeeze:
|
|
|
205
211
|
# Assert: The response is ok, the size is above threshold, and the response is
|
|
206
212
|
# not already encoded.
|
|
207
213
|
|
|
208
|
-
encode_choice =
|
|
214
|
+
encode_choice = Encoding.get_from_headers_and_config(
|
|
209
215
|
request.headers,
|
|
210
216
|
self.app.config,
|
|
211
217
|
)
|
|
212
218
|
|
|
213
|
-
minify_choice =
|
|
219
|
+
minify_choice = Minification.get_from_mimetype_and_config(
|
|
214
220
|
response.mimetype,
|
|
215
221
|
self.app.config,
|
|
216
222
|
)
|
|
@@ -26,7 +26,7 @@ class MinificationInfo:
|
|
|
26
26
|
return {"X-Flask-Squeeze-Minify": value}
|
|
27
27
|
|
|
28
28
|
|
|
29
|
-
def minify_html(
|
|
29
|
+
def minify_html(html_bytes: bytes) -> bytes:
|
|
30
30
|
"""
|
|
31
31
|
Minifies HTML by removing white space and comments.
|
|
32
32
|
Additionally it uses minify_css and minify_js functions
|
|
@@ -36,6 +36,8 @@ def minify_html(html_text: str) -> str:
|
|
|
36
36
|
|
|
37
37
|
# TODO: Find robust way to minify
|
|
38
38
|
|
|
39
|
+
# html_text = html_bytes.decode("utf-8")
|
|
40
|
+
|
|
39
41
|
# minified: list[str] = []
|
|
40
42
|
# parser = etree.HTMLParser(recover=False)
|
|
41
43
|
# html_fragments: list[etree._Element] = etree.fromstring(html_text,
|
|
@@ -67,38 +69,42 @@ def minify_html(html_text: str) -> str:
|
|
|
67
69
|
|
|
68
70
|
# return "".join(minified)
|
|
69
71
|
|
|
70
|
-
return
|
|
72
|
+
return html_bytes
|
|
71
73
|
|
|
72
74
|
|
|
73
|
-
def minify_css(data:
|
|
74
|
-
minified = rcssmin.cssmin(data
|
|
75
|
-
assert isinstance(minified,
|
|
75
|
+
def minify_css(data: bytes) -> bytes:
|
|
76
|
+
minified = rcssmin.cssmin(data)
|
|
77
|
+
assert isinstance(minified, bytes)
|
|
76
78
|
return minified
|
|
77
79
|
|
|
78
80
|
|
|
79
|
-
def minify_js(data:
|
|
80
|
-
minified = rjsmin.jsmin(data
|
|
81
|
-
assert isinstance(minified,
|
|
81
|
+
def minify_js(data: bytes) -> bytes:
|
|
82
|
+
minified = rjsmin.jsmin(data)
|
|
83
|
+
assert isinstance(minified, bytes)
|
|
82
84
|
return minified
|
|
83
85
|
|
|
84
86
|
|
|
85
|
-
def minify(data: bytes,
|
|
87
|
+
def minify(data: bytes, minification: Minification) -> tuple[bytes, MinificationInfo]:
|
|
86
88
|
"""
|
|
87
89
|
Run the minification using the correct minify function and return the minified data.
|
|
88
90
|
"""
|
|
89
91
|
|
|
90
92
|
t0 = time.perf_counter()
|
|
91
93
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
94
|
+
if minification is Minification.html:
|
|
95
|
+
minified_data = minify_html(data)
|
|
96
|
+
elif minification is Minification.css:
|
|
97
|
+
minified_data = minify_css(data)
|
|
98
|
+
elif minification is Minification.js:
|
|
99
|
+
minified_data = minify_js(data)
|
|
100
|
+
else:
|
|
101
|
+
msg = f"Unsupported minification: {minification}"
|
|
102
|
+
raise ValueError(msg)
|
|
97
103
|
|
|
98
|
-
|
|
104
|
+
ratio = len(data) / len(minified_data) if len(minified_data) > 0 else 1.0
|
|
99
105
|
|
|
100
106
|
return minified_data, MinificationInfo(
|
|
101
|
-
minification=
|
|
107
|
+
minification=minification,
|
|
102
108
|
duration=time.perf_counter() - t0,
|
|
103
|
-
ratio=
|
|
109
|
+
ratio=ratio,
|
|
104
110
|
)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from enum import Enum
|
|
4
|
+
from typing import TYPE_CHECKING, Union
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from flask import Config
|
|
8
|
+
from werkzeug.datastructures import Headers
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ResourceType(Enum):
|
|
12
|
+
static = "static"
|
|
13
|
+
dynamic = "dynamic"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Encoding(Enum):
|
|
17
|
+
gzip = "gzip"
|
|
18
|
+
deflate = "deflate"
|
|
19
|
+
br = "br"
|
|
20
|
+
|
|
21
|
+
@classmethod
|
|
22
|
+
def get_from_headers_and_config(
|
|
23
|
+
cls,
|
|
24
|
+
headers: Headers,
|
|
25
|
+
config: Config,
|
|
26
|
+
) -> Union[Encoding, None]:
|
|
27
|
+
"""
|
|
28
|
+
If the client supports brotli, gzip, or deflate, return the best encoding.
|
|
29
|
+
If the client does not accept any of these encodings, or if the config
|
|
30
|
+
variable SQUEEZE_COMPRESS is False, return None.
|
|
31
|
+
"""
|
|
32
|
+
if not config.get("SQUEEZE_COMPRESS"):
|
|
33
|
+
return None
|
|
34
|
+
encoding = headers.get("Accept-Encoding", "").lower()
|
|
35
|
+
if "br" in encoding:
|
|
36
|
+
return cls.br
|
|
37
|
+
if "deflate" in encoding:
|
|
38
|
+
return cls.deflate
|
|
39
|
+
if "gzip" in encoding:
|
|
40
|
+
return cls.gzip
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Minification(Enum):
|
|
45
|
+
js = "js"
|
|
46
|
+
css = "css"
|
|
47
|
+
html = "html"
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def get_from_mimetype_and_config(
|
|
51
|
+
cls,
|
|
52
|
+
mimetype: Union[str, None],
|
|
53
|
+
config: Config,
|
|
54
|
+
) -> Union[Minification, None]:
|
|
55
|
+
"""
|
|
56
|
+
Based on the response mimetype:
|
|
57
|
+
- `js` or `json`, and `SQUEEZE_MINIFY_JS=True`: return `Minification.js`
|
|
58
|
+
- `css` and `SQUEEZE_MINIFY_CSS=True`: return `Minification.css`
|
|
59
|
+
- `html` and `SQUEEZE_MINIFY_HTML=True`: return `Minification.html`
|
|
60
|
+
- Otherwise, return `None`
|
|
61
|
+
"""
|
|
62
|
+
if mimetype is None:
|
|
63
|
+
return None
|
|
64
|
+
is_js_or_json = mimetype.endswith(("javascript", "json"))
|
|
65
|
+
if is_js_or_json and config.get("SQUEEZE_MINIFY_JS"):
|
|
66
|
+
return cls.js
|
|
67
|
+
if mimetype.endswith("css") and config.get("SQUEEZE_MINIFY_CSS"):
|
|
68
|
+
return cls.css
|
|
69
|
+
if mimetype.endswith("html") and config.get("SQUEEZE_MINIFY_HTML"):
|
|
70
|
+
return cls.html
|
|
71
|
+
return None
|
|
@@ -14,8 +14,8 @@ def add_breach_exploit_protection_header(response: Response) -> None:
|
|
|
14
14
|
Protect against BREACH attack by adding random padding to the response.
|
|
15
15
|
"""
|
|
16
16
|
padding_length = secrets.randbelow(128) + 1
|
|
17
|
-
|
|
18
|
-
response.headers["X-Flask-Squeeze-Breach-Protection"] =
|
|
17
|
+
random_str = secrets.token_urlsafe(padding_length)
|
|
18
|
+
response.headers["X-Flask-Squeeze-Breach-Protection"] = random_str
|
|
19
19
|
|
|
20
20
|
|
|
21
21
|
def update_response_headers(response: Response, encode_choice: Encoding | None) -> None:
|
|
@@ -30,4 +30,4 @@ def update_response_headers(response: Response, encode_choice: Encoding | None)
|
|
|
30
30
|
vary = {x.strip() for x in response.headers.get("Vary", "").split(",")}
|
|
31
31
|
response.headers["Vary"] = ",".join((vary | {"Accept-Encoding"}) - {""})
|
|
32
32
|
|
|
33
|
-
response.headers["Content-Length"] = response.content_length
|
|
33
|
+
response.headers["Content-Length"] = str(response.content_length)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: flask-squeeze
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.4.0
|
|
4
4
|
Summary: Compress and minify Flask responses!
|
|
5
5
|
Author-email: Marcel Kröker <kroeker.marcel@gmail.com>
|
|
6
6
|
License: MIT License
|
|
@@ -34,6 +34,7 @@ Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
|
34
34
|
Requires-Python: <3.14,>=3.8
|
|
35
35
|
Description-Content-Type: text/markdown
|
|
36
36
|
Requires-Dist: flask>=1
|
|
37
|
+
Requires-Dist: werkzeug>=0
|
|
37
38
|
Requires-Dist: brotli~=1.1
|
|
38
39
|
Requires-Dist: rjsmin~=1.2
|
|
39
40
|
Requires-Dist: rcssmin~=1.2
|
|
@@ -45,13 +46,16 @@ Requires-Dist: rcssmin~=1.2
|
|
|
45
46
|

|
|
46
47
|
|
|
47
48
|
Flask-Squeeze is a Flask extension that automatically:
|
|
48
|
-
- **Minifies**
|
|
49
|
+
- **Minifies** responses with the mimetypes javascript and css
|
|
49
50
|
- **Compresses** all responses with brotli if the browser supports it, or gzip if the browser supports it!
|
|
50
51
|
- **Protects** against the BREACH exploit
|
|
51
|
-
- **Caches** static files so that they don't have to be re-compressed.
|
|
52
|
+
- **Caches** static files so that they don't have to be re-compressed. By default, the cache is in-memory and will be cleared each time Flask restarts. With persistent caching enabled, compressed responses are saved to disk and survive server restarts.
|
|
53
|
+
- **Persistent caching** (optional) saves compressed static files to disk, improving startup times and reducing CPU usage across server restarts
|
|
54
|
+
|
|
55
|
+
Files are considered static if the substring "/static/" is in their request path.
|
|
52
56
|
|
|
53
57
|
## Compatibility
|
|
54
|
-
- Tested with Python 3.
|
|
58
|
+
- Tested with Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13
|
|
55
59
|
|
|
56
60
|
## Installation
|
|
57
61
|
```
|
|
@@ -86,8 +90,36 @@ You can configure Flask-Squeeze with the following options in your [Flask config
|
|
|
86
90
|
| --- | --- | --- |
|
|
87
91
|
| `SQUEEZE_COMPRESS` | `True` | Enables or disables compression |
|
|
88
92
|
| `SQUEEZE_MIN_SIZE` | `500` | Defines the minimum file size in bytes to activate the compression |
|
|
93
|
+
| `SQUEEZE_CACHE_DIR` | `None` | Directory to store persistent cache files. If `None`, only in-memory caching is used |
|
|
89
94
|
| `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
95
|
|
|
96
|
+
### Persistent Caching
|
|
97
|
+
Flask-Squeeze supports persistent caching of compressed static files. When enabled, compressed responses are saved to disk and reloaded on server restart, eliminating the need to recompress unchanged files.
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
app.config['SQUEEZE_CACHE_DIR'] = './cache/flask_squeeze/' # Enable persistent caching
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Benefits:
|
|
104
|
+
- **Faster server startup**: No need to recompress static files on restart
|
|
105
|
+
- **Reduced CPU usage**: Avoid redundant compression operations
|
|
106
|
+
- **Consistent performance**: Immediate cache hits after restart
|
|
107
|
+
|
|
108
|
+
Cache files are automatically managed:
|
|
109
|
+
- Cache entries are validated using file content hashes
|
|
110
|
+
- Stale cache entries are automatically replaced when files change
|
|
111
|
+
- Use `squeeze.clear_cache()` to manually clear the cache
|
|
112
|
+
|
|
113
|
+
#### Cache Management
|
|
114
|
+
```python
|
|
115
|
+
from flask_squeeze import Squeeze
|
|
116
|
+
|
|
117
|
+
squeeze = Squeeze(app)
|
|
118
|
+
|
|
119
|
+
# Clear all cached files (memory and disk)
|
|
120
|
+
squeeze.clear_cache()
|
|
121
|
+
```
|
|
122
|
+
|
|
91
123
|
### Minification options
|
|
92
124
|
| Option | Default | Description |
|
|
93
125
|
| --- | --- | --- |
|
|
@@ -95,7 +127,7 @@ You can configure Flask-Squeeze with the following options in your [Flask config
|
|
|
95
127
|
| `SQUEEZE_MINIFY_JS` | `True` | Enable or disable js minification using rjsmin |
|
|
96
128
|
|
|
97
129
|
### Compression level options
|
|
98
|
-
> Static files are
|
|
130
|
+
> Static files are cached, so they only have to be compressed once (and are persisted to disk if `SQUEEZE_CACHE_DIR` is configured).
|
|
99
131
|
> Dynamic files like generated HTML files will not be cached, so they will be compressed for each response.
|
|
100
132
|
|
|
101
133
|
| Option | Default | Description |
|
|
@@ -14,4 +14,6 @@ flask_squeeze.egg-info/SOURCES.txt
|
|
|
14
14
|
flask_squeeze.egg-info/dependency_links.txt
|
|
15
15
|
flask_squeeze.egg-info/requires.txt
|
|
16
16
|
flask_squeeze.egg-info/top_level.txt
|
|
17
|
-
tests/
|
|
17
|
+
tests/test_compress.py
|
|
18
|
+
tests/test_flask_squeeze.py
|
|
19
|
+
tests/test_minify.py
|