flask-squeeze 3.3.3__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.
Files changed (24) hide show
  1. {flask_squeeze-3.3.3 → flask_squeeze-3.4.0}/PKG-INFO +38 -6
  2. {flask_squeeze-3.3.3 → flask_squeeze-3.4.0}/README.md +35 -4
  3. flask_squeeze-3.4.0/flask_squeeze/cache.py +101 -0
  4. flask_squeeze-3.4.0/flask_squeeze/compress.py +56 -0
  5. {flask_squeeze-3.3.3 → flask_squeeze-3.4.0}/flask_squeeze/flask_squeeze.py +88 -83
  6. {flask_squeeze-3.3.3 → flask_squeeze-3.4.0}/flask_squeeze/minify.py +31 -30
  7. flask_squeeze-3.4.0/flask_squeeze/models.py +71 -0
  8. {flask_squeeze-3.3.3 → flask_squeeze-3.4.0}/flask_squeeze/utils.py +6 -13
  9. {flask_squeeze-3.3.3 → flask_squeeze-3.4.0}/flask_squeeze.egg-info/PKG-INFO +38 -6
  10. {flask_squeeze-3.3.3 → flask_squeeze-3.4.0}/flask_squeeze.egg-info/SOURCES.txt +4 -1
  11. {flask_squeeze-3.3.3 → flask_squeeze-3.4.0}/flask_squeeze.egg-info/requires.txt +1 -0
  12. {flask_squeeze-3.3.3 → flask_squeeze-3.4.0}/pyproject.toml +32 -20
  13. flask_squeeze-3.4.0/tests/test_compress.py +8 -0
  14. flask_squeeze-3.4.0/tests/test_flask_squeeze.py +760 -0
  15. flask_squeeze-3.4.0/tests/test_minify.py +8 -0
  16. flask_squeeze-3.3.3/flask_squeeze/compress.py +0 -57
  17. flask_squeeze-3.3.3/flask_squeeze/models.py +0 -69
  18. flask_squeeze-3.3.3/tests/test_flask_squeeze.py +0 -274
  19. {flask_squeeze-3.3.3 → flask_squeeze-3.4.0}/LICENSE +0 -0
  20. {flask_squeeze-3.3.3 → flask_squeeze-3.4.0}/flask_squeeze/__init__.py +0 -0
  21. {flask_squeeze-3.3.3 → flask_squeeze-3.4.0}/flask_squeeze/log.py +0 -0
  22. {flask_squeeze-3.3.3 → flask_squeeze-3.4.0}/flask_squeeze.egg-info/dependency_links.txt +0 -0
  23. {flask_squeeze-3.3.3 → flask_squeeze-3.4.0}/flask_squeeze.egg-info/top_level.txt +0 -0
  24. {flask_squeeze-3.3.3 → flask_squeeze-3.4.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: flask-squeeze
3
- Version: 3.3.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
  ![Coverage](https://github.com/mkrd/Flask-Squeeze/blob/master/assets/coverage.svg?raw=1)
46
47
 
47
48
  Flask-Squeeze is a Flask extension that automatically:
48
- - **Minifies** repsonses with the mimetypes javascript and css
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. The cache will be cleared each time Flask restarts. Files are considered static if the the substring "/static/" is in their request path.
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.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13
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 chached, so they only have to be compressed once.
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
  ![Coverage](https://github.com/mkrd/Flask-Squeeze/blob/master/assets/coverage.svg?raw=1)
6
6
 
7
7
  Flask-Squeeze is a Flask extension that automatically:
8
- - **Minifies** repsonses with the mimetypes javascript and css
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. The cache will be cleared each time Flask restarts. Files are considered static if the the substring "/static/" is in their request path.
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.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13
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 chached, so they only have to be compressed once.
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)
@@ -0,0 +1,56 @@
1
+ from __future__ import annotations
2
+
3
+ import gzip
4
+ import time
5
+ import zlib
6
+ from dataclasses import dataclass
7
+
8
+ import brotli
9
+
10
+ from .models import Encoding
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class CompressionInfo:
15
+ encoding: Encoding
16
+ quality: int
17
+ duration: float
18
+ ratio: float
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
+
31
+
32
+ def compress(
33
+ data: bytes,
34
+ encoding: Encoding,
35
+ quality: int,
36
+ ) -> tuple[bytes, CompressionInfo]:
37
+ t0 = time.perf_counter()
38
+
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)
48
+
49
+ ratio = len(data) / len(compressed_data) if len(compressed_data) > 0 else 1.0
50
+
51
+ return compressed_data, CompressionInfo(
52
+ encoding=encoding,
53
+ quality=quality,
54
+ duration=time.perf_counter() - t0,
55
+ ratio=ratio,
56
+ )
@@ -1,33 +1,27 @@
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
 
7
- from flask_squeeze.utils import add_breach_exploit_protection_header, update_response_headers
8
-
9
- from .compress import compress, update_response_with_compressed_data
8
+ from .cache import Cache, CacheKey
9
+ from .compress import CompressionInfo, compress
10
10
  from .log import d_log, log
11
- from .minify import minify, update_response_with_minified_data
12
- from .models import (
13
- Encoding,
14
- Minification,
15
- ResourceType,
16
- choose_encoding_from_headers_and_config,
17
- choose_minification_from_mimetype_and_config,
18
- )
11
+ from .minify import MinificationInfo, minify
12
+ from .models import Encoding, Minification, ResourceType
13
+ from .utils import add_breach_exploit_protection_header, update_response_headers
19
14
 
20
15
 
21
16
  class Squeeze:
22
17
  __slots__ = "app", "cache_static"
23
18
  app: Flask
24
19
 
25
- cache_static: dict[tuple[str, str], tuple[str, bytes]]
20
+ cache_static: Cache
26
21
  """ (request.path, encoding) -> (original file sha256 hash, compressed bytes) """
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 = {}
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"]
@@ -89,23 +95,20 @@ class Squeeze:
89
95
  ) -> None:
90
96
  assert encode_choice or minify_choice
91
97
 
92
- response.direct_passthrough = False
93
-
94
- # Minification
98
+ data, minification_info, compression_info = self.squeeze(
99
+ response.get_data(as_text=False),
100
+ ResourceType.dynamic,
101
+ minify_choice,
102
+ encode_choice,
103
+ )
95
104
 
96
- if minify_choice is not None:
97
- minification_result = minify(response.get_data(as_text=False), minify_choice)
98
- update_response_with_minified_data(response, minification_result)
105
+ response.set_data(data)
99
106
 
100
- # Compression
107
+ if minification_info:
108
+ response.headers.update(minification_info.headers)
101
109
 
102
- if encode_choice is not None:
103
- compression_result = compress(
104
- response.get_data(as_text=False),
105
- encode_choice,
106
- self.get_configured_quality(encode_choice, ResourceType.dynamic),
107
- )
108
- update_response_with_compressed_data(response, compression_result)
110
+ if compression_info:
111
+ response.headers.update(compression_info.headers)
109
112
  add_breach_exploit_protection_header(response)
110
113
 
111
114
  ####################################################################################
@@ -117,69 +120,70 @@ class Squeeze:
117
120
  encode_choice: Encoding | None,
118
121
  minify_choice: Minification | None,
119
122
  ) -> None:
120
- response.direct_passthrough = False # Ensure we can read the data
123
+ """
124
+ If the hash of the current response matches the hash of the cached response,
125
+ return the cached response. Otherwise, compress and minify the response and
126
+ cache the compressed response.
127
+ """
128
+ assert encode_choice or minify_choice
129
+
130
+ data = response.get_data(as_text=False)
131
+ data_hash = hashlib.sha256(data).hexdigest()
132
+
133
+ cache_key = CacheKey(request.path, encode_choice)
134
+ cached = self.cache_static.get(cache_key)
121
135
 
122
- encode_choice_str = encode_choice.value if encode_choice else "none"
123
- cache_entry = self.cache_static.get((request.path, encode_choice_str))
136
+ if cached is not None and data_hash == cached.original_hash:
137
+ log(2, "Found in cache, hashes match. RETURN")
138
+ response.set_data(cached.data)
139
+ response.headers["X-Flask-Squeeze-Cache"] = "HIT"
140
+ return
124
141
 
125
- # Serve from cache
142
+ # Not in cache, compress and minify
126
143
 
127
- if cache_entry is not None:
128
- original_sha256, compressed_data = cache_entry
144
+ log(2, "Not in cache or hashes don't match. Squeeze and cache.")
145
+ data, minification_info, compression_info = self.squeeze(
146
+ data,
147
+ ResourceType.static,
148
+ minify_choice,
149
+ encode_choice,
150
+ )
129
151
 
130
- # Compare the original file hash with the current file hash
152
+ response.set_data(data)
131
153
 
132
- current_data = response.get_data(as_text=False)
133
- current_sha256 = hashlib.sha256(current_data).hexdigest()
154
+ if minification_info:
155
+ response.headers.update(minification_info.headers)
134
156
 
135
- if current_sha256 == original_sha256:
136
- log(2, "Found in cache, hashes match. RETURN")
137
- response.set_data(compressed_data)
138
- response.headers["X-Flask-Squeeze-Cache"] = "HIT"
139
- return
157
+ if compression_info:
158
+ response.headers.update(compression_info.headers)
140
159
 
141
- log(2, "File has changed.")
160
+ response.headers["X-Flask-Squeeze-Cache"] = "MISS"
142
161
 
143
- if minify_choice is not None:
144
- minfication_result = minify(current_data, minify_choice)
145
- update_response_with_minified_data(response, minfication_result)
146
- current_data = minfication_result.data
147
- if encode_choice is not None:
148
- compression_result = compress(
149
- current_data,
150
- encode_choice,
151
- self.get_configured_quality(encode_choice, ResourceType.static),
152
- )
153
- update_response_with_compressed_data(response, compression_result)
154
- current_data = compression_result.data
162
+ # Cache the compressed data, with the dash of the original data
163
+ self.cache_static.set(cache_key, data_hash, data)
155
164
 
156
- # Assert: At least one of minify or compress was run
165
+ def squeeze(
166
+ self,
167
+ data: bytes,
168
+ resource_type: ResourceType,
169
+ minify_choice: Minification | None,
170
+ encode_choice: Encoding | None,
171
+ ) -> tuple[bytes, MinificationInfo | None, CompressionInfo | None]:
172
+ assert encode_choice or minify_choice
157
173
 
158
- response.headers["X-Flask-Squeeze-Cache"] = "MISS"
159
- self.cache_static[(request.path, encode_choice_str)] = (current_sha256, current_data)
174
+ minification_info = None
175
+ if minify_choice is not None:
176
+ data, minification_info = minify(data, minify_choice)
160
177
 
161
- # Not in cache, compress and minify
178
+ compression_info = None
179
+ if encode_choice is not None:
180
+ data, compression_info = compress(
181
+ data,
182
+ encode_choice,
183
+ self.get_configured_quality(encode_choice, resource_type),
184
+ )
162
185
 
163
- else:
164
- original_data = response.get_data(as_text=False)
165
- original_sha256 = hashlib.sha256(original_data).hexdigest()
166
-
167
- if minify_choice is not None:
168
- minification_result = minify(original_data, minify_choice)
169
- update_response_with_minified_data(response, minification_result)
170
- if encode_choice is not None:
171
- compression_result = compress(
172
- response.get_data(as_text=False),
173
- encode_choice,
174
- self.get_configured_quality(encode_choice, ResourceType.static),
175
- )
176
- update_response_with_compressed_data(response, compression_result)
177
-
178
- # Assert: At least one of minify or compress was run
179
-
180
- compressed_data = response.get_data(as_text=False)
181
- self.cache_static[(request.path, encode_choice_str)] = (original_sha256, compressed_data)
182
- response.headers["X-Flask-Squeeze-Cache"] = "MISS"
186
+ return data, minification_info, compression_info
183
187
 
184
188
  ####################################################################################
185
189
  #### MARK: After Request
@@ -207,12 +211,12 @@ class Squeeze:
207
211
  # Assert: The response is ok, the size is above threshold, and the response is
208
212
  # not already encoded.
209
213
 
210
- encode_choice = choose_encoding_from_headers_and_config(
214
+ encode_choice = Encoding.get_from_headers_and_config(
211
215
  request.headers,
212
216
  self.app.config,
213
217
  )
214
218
 
215
- minify_choice = choose_minification_from_mimetype_and_config(
219
+ minify_choice = Minification.get_from_mimetype_and_config(
216
220
  response.mimetype,
217
221
  self.app.config,
218
222
  )
@@ -223,13 +227,14 @@ class Squeeze:
223
227
 
224
228
  # At least one of minify or compress is requested
225
229
 
226
- original_content_length = response.content_length
230
+ response.direct_passthrough = False # In both cases, we need to read the data
227
231
 
228
232
  if request.path.startswith("/static/"):
229
233
  self.run_static(response, encode_choice, minify_choice)
230
234
  else:
231
235
  self.run_dynamic(response, encode_choice, minify_choice)
232
236
 
233
- update_response_headers(response, original_content_length, encode_choice)
234
- log(1, f"Static cache: {self.cache_static.keys()}")
237
+ update_response_headers(response, encode_choice)
238
+
239
+ log(1, f"Static cache: {self.cache_static.data.keys()}")
235
240
  return response
@@ -1,31 +1,32 @@
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 flask_squeeze.models import Minification
9
+ from .models import Minification
9
10
 
10
11
 
11
12
  @dataclass(frozen=True)
12
- class MinificationResult:
13
- data: bytes
13
+ class MinificationInfo:
14
14
  minification: Minification
15
15
  duration: float
16
16
  ratio: float
17
17
 
18
18
  @property
19
- def info(self) -> str:
20
- return "; ".join(
19
+ def headers(self) -> dict:
20
+ value = "; ".join(
21
21
  [
22
22
  f"ratio={self.ratio:.1f}x",
23
23
  f"duration={self.duration * 1000:.1f}ms",
24
24
  ],
25
25
  )
26
+ return {"X-Flask-Squeeze-Minify": value}
26
27
 
27
28
 
28
- def minify_html(html_text: str) -> str:
29
+ def minify_html(html_bytes: bytes) -> bytes:
29
30
  """
30
31
  Minifies HTML by removing white space and comments.
31
32
  Additionally it uses minify_css and minify_js functions
@@ -35,6 +36,8 @@ def minify_html(html_text: str) -> str:
35
36
 
36
37
  # TODO: Find robust way to minify
37
38
 
39
+ # html_text = html_bytes.decode("utf-8")
40
+
38
41
  # minified: list[str] = []
39
42
  # parser = etree.HTMLParser(recover=False)
40
43
  # html_fragments: list[etree._Element] = etree.fromstring(html_text,
@@ -66,44 +69,42 @@ def minify_html(html_text: str) -> str:
66
69
 
67
70
  # return "".join(minified)
68
71
 
69
- return html_text
72
+ return html_bytes
70
73
 
71
74
 
72
- def minify_css(data: str) -> str:
73
- minified = rcssmin.cssmin(data, keep_bang_comments=False)
74
- assert isinstance(minified, str)
75
+ def minify_css(data: bytes) -> bytes:
76
+ minified = rcssmin.cssmin(data)
77
+ assert isinstance(minified, bytes)
75
78
  return minified
76
79
 
77
80
 
78
- def minify_js(data: str) -> str:
79
- minified = rjsmin.jsmin(data, keep_bang_comments=False)
80
- assert isinstance(minified, str)
81
+ def minify_js(data: bytes) -> bytes:
82
+ minified = rjsmin.jsmin(data)
83
+ assert isinstance(minified, bytes)
81
84
  return minified
82
85
 
83
86
 
84
- def minify(data: bytes, minify_choice: Minification) -> MinificationResult:
87
+ def minify(data: bytes, minification: Minification) -> tuple[bytes, MinificationInfo]:
85
88
  """
86
89
  Run the minification using the correct minify function and return the minified data.
87
90
  """
88
91
 
89
92
  t0 = time.perf_counter()
90
93
 
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
- }
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)
96
103
 
97
- minified = minifiers[minify_choice](data.decode("utf-8")).encode("utf-8")
104
+ ratio = len(data) / len(minified_data) if len(minified_data) > 0 else 1.0
98
105
 
99
- return MinificationResult(
100
- data=minified,
101
- minification=minify_choice,
106
+ return minified_data, MinificationInfo(
107
+ minification=minification,
102
108
  duration=time.perf_counter() - t0,
103
- ratio=len(data) / len(minified),
109
+ ratio=ratio,
104
110
  )
105
-
106
-
107
- def update_response_with_minified_data(response: Response, result: MinificationResult) -> None:
108
- response.set_data(result.data)
109
- response.headers["X-Flask-Squeeze-Minify"] = result.info