flask-squeeze 2.1.2__tar.gz → 2.2.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: flask-squeeze
3
- Version: 2.1.2
3
+ Version: 2.2.0
4
4
  Summary: Compress and minify Flask responses!
5
5
  Home-page: https://github.com/mkrd/Flask-Squeeze
6
6
  License: MIT
@@ -20,7 +20,6 @@ Classifier: Programming Language :: Python :: 3
20
20
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
21
  Requires-Dist: brotli (>=1,<2)
22
22
  Requires-Dist: flask (>1)
23
- Requires-Dist: htmlmin (>=0.1,<0.2)
24
23
  Requires-Dist: rcssmin (>=1,<2)
25
24
  Requires-Dist: rjsmin (>=1,<2)
26
25
  Project-URL: Repository, https://github.com/mkrd/Flask-Squeeze
@@ -71,6 +70,7 @@ You can configure Flask-Squeeze with the following options in your [Flask config
71
70
  | `COMPRESS_FLAG` | `True` | Globally enables or disables Flask-Squeeze |
72
71
  | `COMPRESS_MIN_SIZE` | `500` | Defines the minimum file size in bytes to activate the compression |
73
72
  | `COMPRESS_VERBOSE_LOGGING` | `False` | Enable or disable verbose logging. If enabled, Flask-Squeeze will print what it does into the terminal in a highlighted color |
73
+ | `COMPRESS_ADD_DEBUG_HEADERS` | `False` | Add debug infos into the response headers, like call durations and cache hit infos. ONLY USE THIS IN DEVELOPMENT.
74
74
 
75
75
  ### Minification options
76
76
  | Option | Default | Description |
@@ -43,6 +43,7 @@ You can configure Flask-Squeeze with the following options in your [Flask config
43
43
  | `COMPRESS_FLAG` | `True` | Globally enables or disables Flask-Squeeze |
44
44
  | `COMPRESS_MIN_SIZE` | `500` | Defines the minimum file size in bytes to activate the compression |
45
45
  | `COMPRESS_VERBOSE_LOGGING` | `False` | Enable or disable verbose logging. If enabled, Flask-Squeeze will print what it does into the terminal in a highlighted color |
46
+ | `COMPRESS_ADD_DEBUG_HEADERS` | `False` | Add debug infos into the response headers, like call durations and cache hit infos. ONLY USE THIS IN DEVELOPMENT.
46
47
 
47
48
  ### Minification options
48
49
  | Option | Default | Description |
@@ -0,0 +1,37 @@
1
+ from typing import Dict, Tuple, Union
2
+
3
+ from .logging import d_log
4
+ from .utils import Encoding, Minifcation
5
+
6
+
7
+ class Cache:
8
+ data: Dict[Tuple[str, Encoding, Minifcation], bytes]
9
+
10
+
11
+ def __init__(self) -> None:
12
+ self.data = {}
13
+
14
+ def __repr__(self) -> str:
15
+ keys = ", ".join("-".join([str(v) for v in key]) for key in self.data)
16
+ return f"Cache({keys})"
17
+
18
+
19
+ @d_log(level=2, with_args=[1, 2, 3])
20
+ def get(self,
21
+ request_path: str,
22
+ encoding: Encoding,
23
+ minification: Minifcation,
24
+ ) -> Union[bytes, None]:
25
+ file = request_path.replace("/static/", "")
26
+ return self.data.get((file, encoding, minification), None)
27
+
28
+
29
+ @d_log(level=2, with_args=[1, 2, 3])
30
+ def insert(self,
31
+ request_path: str,
32
+ encoding: Encoding,
33
+ minification: Minifcation,
34
+ value: bytes,
35
+ ) -> None:
36
+ file = request_path.replace("/static/", "")
37
+ self.data[(file, encoding, minification)] = value
@@ -1,4 +1,4 @@
1
- from typing import Tuple, Dict, Generator
1
+ from typing import Tuple, Dict, Generator, Callable
2
2
  from contextlib import contextmanager
3
3
  import functools
4
4
  import time
@@ -37,7 +37,7 @@ class add_debug_header:
37
37
  return kwarg
38
38
  raise ValueError("You can only deocrate a function with 'add_debug_header' that has a Response as an argument or kwarg.")
39
39
 
40
- def __call__(self, method):
40
+ def __call__(self, method) -> Callable:
41
41
  @functools.wraps(method)
42
42
  def wrapper(*args, **kwargs):
43
43
  if not current_app.config["COMPRESS_ADD_DEBUG_HEADERS"]:
@@ -0,0 +1,270 @@
1
+ from typing import Union
2
+ import gzip
3
+ import time
4
+ import zlib
5
+ import secrets
6
+ import random
7
+
8
+ from flask import Flask, Response, request
9
+ import brotli
10
+
11
+ from .cache import (
12
+ Cache,
13
+ )
14
+
15
+ from .logging import (
16
+ d_log,
17
+ log,
18
+ )
19
+
20
+ from .debugging import (
21
+ ctx_add_debug_header,
22
+ add_debug_header,
23
+ )
24
+
25
+ from .utils import (
26
+ choose_encoding,
27
+ choose_minification,
28
+ Encoding,
29
+ Minifcation,
30
+ )
31
+
32
+ from .minifiers import (
33
+ minify_html,
34
+ minify_css,
35
+ minify_js,
36
+ )
37
+
38
+
39
+
40
+ class Squeeze(object):
41
+
42
+ __slots__ = "cache", "app", "encode_choice", "minify_choice", "resource_type"
43
+ cache: Cache
44
+ app: Flask
45
+ encode_choice: Union[Encoding, None]
46
+ minify_choice: Union[Minifcation, None]
47
+ resource_type: Union[str, None]
48
+
49
+
50
+ def __init__(self, app: Flask = None) -> None:
51
+ """ Initialize Flask-Squeeze with or without app. """
52
+ self.cache = Cache()
53
+ self.app = app
54
+ if app is not None:
55
+ self.init_app(app)
56
+
57
+
58
+ def init_app(self, app: Flask) -> None:
59
+ """ Initialize Flask-Squeeze with app """
60
+ self.app = app
61
+ app.config.setdefault("COMPRESS_FLAG", True)
62
+ app.config.setdefault("COMPRESS_MIN_SIZE", 500)
63
+
64
+ app.config.setdefault("COMPRESS_LEVEL_GZIP_STATIC", 9)
65
+ app.config.setdefault("COMPRESS_LEVEL_GZIP_DYNAMIC", 1)
66
+ app.config.setdefault("COMPRESS_LEVEL_BROTLI_STATIC", 11)
67
+ app.config.setdefault("COMPRESS_LEVEL_BROTLI_DYNAMIC", 1)
68
+ app.config.setdefault("COMPRESS_LEVEL_DEFLATE_STATIC", 9)
69
+ app.config.setdefault("COMPRESS_LEVEL_DEFLATE_DYNAMIC", 1)
70
+
71
+ app.config.setdefault("COMPRESS_MINIFY_JS", True)
72
+ app.config.setdefault("COMPRESS_MINIFY_CSS", True)
73
+ app.config.setdefault("COMPRESS_MINIFY_HTML", True)
74
+
75
+ app.config.setdefault("COMPRESS_VERBOSE_LOGGING", False)
76
+ app.config.setdefault("COMPRESS_ADD_DEBUG_HEADERS", False)
77
+
78
+ if app.config["COMPRESS_FLAG"]:
79
+ app.after_request(self.after_request)
80
+
81
+
82
+ # Minification
83
+ ####################################################################################
84
+
85
+
86
+ @d_log(level=2, with_args=[1])
87
+ def execute_minify(self, response: Response) -> None:
88
+ """
89
+ Dispatch minification to the correct function.
90
+ Exit early if minification is not enabled for the repsonse mimetype.
91
+ """
92
+ response.direct_passthrough = False
93
+ data = response.get_data(as_text=True)
94
+
95
+ log(3, f"Minifying {self.minify_choice.value} resource")
96
+
97
+ with ctx_add_debug_header("X-Flask-Squeeze-Minify-Duration", response):
98
+ if self.minify_choice == Minifcation.html:
99
+ minified = minify_html(data)
100
+ elif self.minify_choice == Minifcation.css:
101
+ minified = minify_css(data)
102
+ elif self.minify_choice == Minifcation.js:
103
+ minified = minify_js(data)
104
+ minified = minified.encode("utf-8")
105
+
106
+ log(3, f"Minify ratio: {len(data) / len(minified):.2f}x")
107
+ response.set_data(minified)
108
+
109
+
110
+ # Compression
111
+ ####################################################################################
112
+
113
+
114
+ def select_quality_from_config(self) -> str:
115
+ options = {
116
+ (Encoding.br, "static"): "COMPRESS_LEVEL_BROTLI_STATIC",
117
+ (Encoding.br, "dynamic"): "COMPRESS_LEVEL_BROTLI_DYNAMIC",
118
+ (Encoding.deflate, "static"): "COMPRESS_LEVEL_DEFLATE_STATIC",
119
+ (Encoding.deflate, "dynamic"): "COMPRESS_LEVEL_DEFLATE_DYNAMIC",
120
+ (Encoding.gzip, "static"): "COMPRESS_LEVEL_GZIP_STATIC",
121
+ (Encoding.gzip, "dynamic"): "COMPRESS_LEVEL_GZIP_DYNAMIC",
122
+ }
123
+ return self.app.config[options[(self.encode_choice, self.resource_type)]]
124
+
125
+
126
+
127
+ @d_log(level=2, with_args=[1, 2, 3])
128
+ def execute_compress(self, response: Response) -> None:
129
+ response.direct_passthrough = False
130
+ data = response.get_data(as_text=False)
131
+ quality = self.select_quality_from_config()
132
+
133
+ log(3, (
134
+ f"Compressing resource with {self.encode_choice.value} encoding",
135
+ f", and quality {quality}."
136
+ ))
137
+
138
+ with ctx_add_debug_header("X-Flask-Squeeze-Compress-Duration", response):
139
+ if self.encode_choice == Encoding.br:
140
+ compressed_data = brotli.compress(data, quality=quality)
141
+ elif self.encode_choice == Encoding.deflate:
142
+ compressed_data = zlib.compress(data, level=quality)
143
+ elif self.encode_choice == Encoding.gzip:
144
+ compressed_data = gzip.compress(data, compresslevel=quality)
145
+
146
+ log(3, (
147
+ f"Compression ratio: { len(data) / len(compressed_data):.1f}x, "
148
+ f"used {self.encode_choice.value}"
149
+ ))
150
+
151
+ response.set_data(compressed_data)
152
+
153
+
154
+
155
+ @d_log(level=1)
156
+ def run_for_dynamic_resource(self, response: Response) -> None:
157
+ """
158
+ Compress a dynamic resource.
159
+ - No caching is done.
160
+ """
161
+
162
+ if self.minify_choice:
163
+ self.execute_minify(response)
164
+ if self.encode_choice:
165
+ self.execute_compress(response)
166
+ # Protect against BREACH attack
167
+ if self.encode_choice:
168
+ tx = 2 if int(time.time() ** 3.141592) % 2 else 1
169
+ rand_str: str = secrets.token_urlsafe(random.randint(32 * tx, 128 * tx))
170
+ response.headers["X-Breach-Exploit-Protection-Padding"] = rand_str
171
+
172
+
173
+
174
+ @d_log(level=1)
175
+ def run_for_static_resource(self,
176
+ response: Response,
177
+ ) -> None:
178
+ """
179
+ Compress a static resource.
180
+ """
181
+
182
+ path = request.path
183
+ from_cache = self.cache.get(path, self.encode_choice, self.minify_choice)
184
+ if from_cache is not None:
185
+ log(2, "Found in cache. RETURN")
186
+ response.direct_passthrough = False
187
+ response.set_data(from_cache)
188
+ response.headers["X-Flask-Squeeze-Cache"] = "HIT"
189
+ return
190
+
191
+ # Assert: not in cache
192
+
193
+ if self.minify_choice:
194
+ self.execute_minify(response)
195
+ if self.encode_choice:
196
+ self.execute_compress(response)
197
+
198
+ # If compression or minification was done, insert into cache
199
+ if self.encode_choice or self.minify_choice:
200
+ response.headers["X-Flask-Squeeze-Cache"] = "MISS"
201
+ data = response.get_data(as_text=False)
202
+ self.cache.insert(path, self.encode_choice, self.minify_choice, data)
203
+
204
+
205
+
206
+ @d_log(level=1, with_args=[1, 2])
207
+ def recompute_headers(self,
208
+ response: Response,
209
+ original_content_length: int
210
+ ) -> None:
211
+ # If direct_passthrough is set, the response was not modified.
212
+ if response.direct_passthrough:
213
+ return
214
+
215
+ if self.encode_choice:
216
+ response.headers["Content-Encoding"] = self.encode_choice.value
217
+ vary = {x.strip() for x in response.headers.get("Vary", "").split(",")}
218
+ vary.add("Accept-Encoding")
219
+ vary.discard("")
220
+ response.headers["Vary"] = ",".join(vary)
221
+
222
+ if original_content_length != response.content_length:
223
+ response.headers["Content-Length"] = response.content_length
224
+ response.headers["X-Uncompressed-Content-Length"] = original_content_length
225
+
226
+
227
+
228
+ @d_log(level=0, with_args=[1])
229
+ @add_debug_header("X-Flask-Squeeze-Total-Duration")
230
+ def after_request(self, response: Response) -> Response:
231
+ log(1, f"Enter after_request({response})")
232
+
233
+ if response.status_code < 200 or response.status_code >= 300:
234
+ log(1, "Response status code is not ok. RETURN")
235
+ return response
236
+
237
+ if response.content_length < self.app.config["COMPRESS_MIN_SIZE"]:
238
+ log(1, "Response size is smaller than the defined minimum. RETURN")
239
+ return response
240
+
241
+ if "Content-Encoding" in response.headers:
242
+ log(1, "Response already encoded. RETURN")
243
+ return response
244
+
245
+ # Assert: The response is ok, the size is above threshold, and the response is
246
+ # not already encoded.
247
+
248
+ self.encode_choice = choose_encoding(request)
249
+ self.minify_choice = choose_minification(response)
250
+
251
+ if not self.encode_choice and not self.minify_choice:
252
+ log(1, "No compression or minification requested. RETURN")
253
+ return response
254
+
255
+ original_content_length = response.content_length
256
+
257
+ if "/static/" not in request.path:
258
+ log(1, "Dynamic resource.")
259
+ self.resource_type = "dynamic"
260
+ self.run_for_dynamic_resource(response)
261
+ else:
262
+ log(1, "Static resource.")
263
+ self.resource_type = "static"
264
+ self.run_for_static_resource(response)
265
+
266
+ self.recompute_headers(response, original_content_length)
267
+
268
+ log(1, f"{self.cache}")
269
+
270
+ return response
@@ -1,3 +1,4 @@
1
+ from typing import Callable
1
2
  import time
2
3
  import functools
3
4
 
@@ -41,7 +42,7 @@ class d_log:
41
42
  self.with_kwargs = with_kwargs if with_kwargs is not None else []
42
43
 
43
44
 
44
- def __call__(self, method):
45
+ def __call__(self, method) -> Callable:
45
46
  @functools.wraps(method)
46
47
  def wrapper(*args, **kwargs):
47
48
  if not current_app.config["COMPRESS_VERBOSE_LOGGING"]:
@@ -0,0 +1,82 @@
1
+ from html.parser import HTMLParser
2
+ import rjsmin
3
+ import rcssmin
4
+
5
+
6
+ class MinifyHTMLParser(HTMLParser):
7
+ def __init__(self):
8
+ super().__init__()
9
+ self.minified_html = []
10
+
11
+ def write(self, data: str) -> None:
12
+ self.minified_html.append(data)
13
+
14
+ def get_minified_html(self) -> str:
15
+ return "".join(self.minified_html)
16
+
17
+ def handle_decl(self, decl: str) -> None:
18
+ self.write(f"<!{decl}>")
19
+
20
+ def unknown_decl(self, data: str) -> None:
21
+ self.write(f"<!{data}>")
22
+
23
+ def handle_pi(self, data):
24
+ self.write(f"<?{data}>")
25
+
26
+ def handle_startendtag(self, tag, attrs):
27
+ self.add_tag(tag, attrs, "/>")
28
+
29
+ def handle_entityref(self, name):
30
+ self.write(f"&{name};")
31
+
32
+ def handle_charref(self, name):
33
+ self.write(f"&#x{name};")
34
+
35
+ def handle_starttag(self, tag, attrs):
36
+ self.add_tag(tag, attrs, ">")
37
+
38
+ # TODO Rename this here and in `handle_startendtag` and `handle_starttag`
39
+ def add_tag(self, tag, attrs, end_tag):
40
+ self.write(f"<{tag}")
41
+ for attr in attrs:
42
+ self.write(f' {attr[0]}')
43
+ if attr[1] is not None:
44
+ self.write(f'="{attr[1]}"')
45
+ self.write(end_tag)
46
+
47
+ def handle_endtag(self, tag):
48
+ self.write(f"</{tag}>")
49
+
50
+ def handle_data(self, data):
51
+ if self.lasttag == "style":
52
+ self.write(minify_css(data).strip())
53
+ elif self.lasttag == "script":
54
+ self.write(minify_js(data).strip())
55
+ elif self.lasttag in ["textarea", "pre", "code"]:
56
+ self.write(data)
57
+ else:
58
+ self.write(data.strip())
59
+
60
+
61
+
62
+ def minify_html(html_text: str) -> str:
63
+ """
64
+ Minifies HTML by removing white space and comments.
65
+ Additionally it uses minify_css and minify_js functions
66
+ to minify css in style tags and js in script tags
67
+ respectively.
68
+ """
69
+
70
+ parser = MinifyHTMLParser()
71
+ parser.feed(html_text)
72
+ return parser.get_minified_html()
73
+
74
+
75
+
76
+ def minify_css(data: str) -> str:
77
+ return rcssmin.cssmin(data, keep_bang_comments=False)
78
+
79
+
80
+
81
+ def minify_js(data: str) -> str:
82
+ return rjsmin.jsmin(data, keep_bang_comments=False)
@@ -0,0 +1,43 @@
1
+ from enum import Enum
2
+
3
+ from flask import Request, Response, current_app
4
+
5
+
6
+
7
+ class Encoding(Enum):
8
+ gzip = "gzip"
9
+ deflate = "deflate"
10
+ br = "br"
11
+
12
+
13
+
14
+ class Minifcation(Enum):
15
+ js = "js"
16
+ css = "css"
17
+ html = "html"
18
+
19
+
20
+
21
+ def choose_encoding(request: Request):
22
+ if not current_app.config["COMPRESS_FLAG"]:
23
+ return None
24
+ encoding = request.headers.get("Accept-Encoding", "").lower()
25
+ if "br" in encoding:
26
+ return Encoding.br
27
+ elif "deflate" in encoding:
28
+ return Encoding.deflate
29
+ elif "gzip" in encoding:
30
+ return Encoding.gzip
31
+ return None
32
+
33
+
34
+
35
+ def choose_minification(response: Response):
36
+ mimetype = response.mimetype
37
+ if (mimetype.endswith("javascript") or mimetype.endswith("json")) and current_app.config["COMPRESS_MINIFY_JS"]:
38
+ return Minifcation.js
39
+ elif mimetype.endswith("css") and current_app.config["COMPRESS_MINIFY_CSS"]:
40
+ return Minifcation.css
41
+ elif mimetype.endswith("html") and current_app.config["COMPRESS_MINIFY_HTML"]:
42
+ return Minifcation.html
43
+ return None
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "flask-squeeze"
3
- version = "2.1.2"
3
+ version = "2.2.0"
4
4
  repository = "https://github.com/mkrd/Flask-Squeeze"
5
5
  description = "Compress and minify Flask responses!"
6
6
  readme = "README.md"
@@ -21,7 +21,6 @@ flask = ">1"
21
21
  brotli = "^1"
22
22
  rjsmin = "^1"
23
23
  rcssmin = "^1"
24
- htmlmin = "^0.1"
25
24
 
26
25
  [tool.poetry.dev-dependencies]
27
26
  pycodestyle = "^2.10.0"
@@ -33,5 +32,5 @@ build-backend = "poetry.masonry.api"
33
32
 
34
33
  [tool.ruff]
35
34
  ignore = ["E501"]
36
- extend-select = ["C4", "SIM", "TCH", "ANN201", "ANN202", "ANN204", "ANN205", "ANN206"]
35
+ extend-select = ["C4", "SIM", "TCH", "ANN201", "ANN203", "ANN204", "ANN205", "ANN206"]
37
36
  show-fixes = true
@@ -1,293 +0,0 @@
1
- from typing import Tuple, Dict, Union
2
- import gzip
3
- import time
4
- import zlib
5
- import secrets
6
- import random
7
-
8
- from flask import Flask, Response, request
9
- from rjsmin import jsmin
10
- from rcssmin import cssmin
11
- import htmlmin
12
- import brotli
13
-
14
- from .logger import (
15
- d_log,
16
- log,
17
- )
18
- from .debugger import (
19
- ctx_add_debug_header,
20
- add_debug_header,
21
- )
22
- from .utils import (
23
- get_requested_encoding,
24
- is_html,
25
- is_css,
26
- is_js,
27
- )
28
-
29
-
30
-
31
- class Squeeze(object):
32
- cache: Dict[Tuple[str, str, bool], bytes] # keys are (request.path, encoding, is_minified)
33
- app: Flask
34
-
35
-
36
- def __init__(self, app: Flask = None) -> None:
37
- """ Initialize Flask-Squeeze with or without app. """
38
- self.cache = {}
39
- self.app = app
40
- if app is not None:
41
- self.init_app(app)
42
-
43
-
44
- def init_app(self, app: Flask) -> None:
45
- """ Initialize Flask-Squeeze with app """
46
- self.app = app
47
- app.config.setdefault("COMPRESS_FLAG", True)
48
- app.config.setdefault("COMPRESS_MIN_SIZE", 500)
49
-
50
- app.config.setdefault("COMPRESS_LEVEL_GZIP_STATIC", 9)
51
- app.config.setdefault("COMPRESS_LEVEL_GZIP_DYNAMIC", 1)
52
- app.config.setdefault("COMPRESS_LEVEL_BROTLI_STATIC", 11)
53
- app.config.setdefault("COMPRESS_LEVEL_BROTLI_DYNAMIC", 1)
54
- app.config.setdefault("COMPRESS_LEVEL_DEFLATE_STATIC", 9)
55
- app.config.setdefault("COMPRESS_LEVEL_DEFLATE_DYNAMIC", 1)
56
-
57
- app.config.setdefault("COMPRESS_MINIFY_JS", True)
58
- app.config.setdefault("COMPRESS_MINIFY_CSS", True)
59
- app.config.setdefault("COMPRESS_MINIFY_HTML", True)
60
-
61
- app.config.setdefault("COMPRESS_VERBOSE_LOGGING", False)
62
- app.config.setdefault("COMPRESS_ADD_DEBUG_HEADERS", False)
63
-
64
- if app.config["COMPRESS_FLAG"]:
65
- app.after_request(self.after_request)
66
-
67
- # Cache
68
- ####################################################################################
69
-
70
- @d_log(level=2, with_args=[1, 2, 3])
71
- def get_from_cache(self, request_path: str, encoding: str, is_minified: bool) -> Union[bytes, None]:
72
- file = request_path.replace("/static/", "")
73
- return self.cache.get((file, encoding, is_minified), None)
74
-
75
-
76
- @d_log(level=2, with_args=[1, 2, 3])
77
- def insert_to_cache(self, request_path: str, encoding: str, is_minified: bool, value: bytes) -> None:
78
- file = request_path.replace("/static/", "")
79
- self.cache[(file, encoding, is_minified)] = value
80
-
81
-
82
- # Minification
83
- ####################################################################################
84
-
85
-
86
- def execute_minify(self, response: Response, file_type: str) -> None:
87
- response.direct_passthrough = False
88
- data = response.get_data(as_text=True)
89
-
90
- if file_type == "html":
91
- minified = htmlmin.main.minify(data)
92
- elif file_type == "css":
93
- minified = cssmin(data, keep_bang_comments=False)
94
- elif file_type == "js":
95
- minified = jsmin(data, keep_bang_comments=False)
96
- minified = minified.encode("utf-8")
97
-
98
- log(3, f"Minify ratio: {len(data) / len(minified):.2f}x")
99
- response.set_data(minified)
100
-
101
-
102
- @d_log(level=2)
103
- def minify_if_js(self, response: Response) -> bool:
104
- if not self.app.config["COMPRESS_MINIFY_JS"]:
105
- log(2, "Minifying javascript is disabled. EXIT.")
106
- return False
107
- if not is_js(response.mimetype):
108
- log(3, f"MimeType is not js or json but {response.mimetype}. EXIT.")
109
- return False
110
- with ctx_add_debug_header("X-Flask-Squeeze-Minify-Duration", response):
111
- self.execute_minify(response, "js")
112
- return True
113
-
114
-
115
- @d_log(level=2)
116
- def minify_if_css(self, response: Response) -> bool:
117
- if not self.app.config["COMPRESS_MINIFY_CSS"]:
118
- log(3, "Minifying css is disabled. EXIT.")
119
- return False
120
- if not is_css(response.mimetype):
121
- log(3, f"MimeType is not css but {response.mimetype}. EXIT.")
122
- return False
123
- self.execute_minify(response, "css")
124
- return True
125
-
126
-
127
- @d_log(level=2)
128
- def minify_if_html(self, response: Response) -> bool:
129
- if not self.app.config["COMPRESS_MINIFY_HTML"]:
130
- log(3, "Minifying HTML is disabled. EXIT.")
131
- return False
132
- if not is_html(response.mimetype):
133
- log(3, f"MimeType is not HTML but {response.mimetype}. EXIT.")
134
- return False
135
- self.execute_minify(response, "html")
136
- return True
137
-
138
-
139
- # Compression
140
- ####################################################################################
141
-
142
-
143
- def select_quality_from_config(self, encoding: str, resource_type: str) -> str:
144
- options = {
145
- ("br", "static"): "COMPRESS_LEVEL_BROTLI_STATIC",
146
- ("br", "dynamic"): "COMPRESS_LEVEL_BROTLI_DYNAMIC",
147
- ("deflate", "static"): "COMPRESS_LEVEL_DEFLATE_STATIC",
148
- ("deflate", "dynamic"): "COMPRESS_LEVEL_DEFLATE_DYNAMIC",
149
- ("gzip", "static"): "COMPRESS_LEVEL_GZIP_STATIC",
150
- ("gzip", "dynamic"): "COMPRESS_LEVEL_GZIP_DYNAMIC",
151
- }
152
- return self.app.config[options[(encoding, resource_type)]]
153
-
154
-
155
- def execute_compress(self, response: Response, encoding: str, resource_type: str) -> None:
156
- response.direct_passthrough = False
157
- data = response.get_data(as_text=False)
158
-
159
- quality = self.select_quality_from_config(encoding, resource_type)
160
- log(3, f"Compressing {resource_type} resource with {encoding}, quality {quality}.")
161
-
162
- with ctx_add_debug_header("X-Flask-Squeeze-Compress-Duration", response):
163
- if encoding == "br":
164
- compressed_data = brotli.compress(data, quality=quality)
165
- elif encoding == "deflate":
166
- compressed_data = zlib.compress(data, level=quality)
167
- elif encoding == "gzip":
168
- compressed_data = gzip.compress(data, compresslevel=quality)
169
-
170
- compress_ratio = len(response.get_data(as_text=False)) / len(compressed_data)
171
- log(3, f"Compression ratio: {compress_ratio:.1f}x")
172
-
173
- response.set_data(compressed_data)
174
-
175
-
176
- @d_log(level=2, with_args=[1, 2, 3])
177
- def compress_if_requested(self, response: Response, encoding: str, resource_type: str) -> bool:
178
- """
179
- For a given response, return its contents
180
- as a brotli compressed bytes object.
181
- quality can be 0-11 for brotli, 0-9 for gzip.
182
- """
183
-
184
- if encoding not in ["br", "gzip", "deflate"]:
185
- return False
186
- with ctx_add_debug_header("X-Flask-Squeeze-Compress-Duration", response):
187
- self.execute_compress(response, encoding, resource_type)
188
- return True
189
-
190
-
191
- @d_log(level=1)
192
- def recompute_headers(self, response: Response, encoding: str, original_content_length: int) -> None:
193
- # If direct_passthrough is set, the response was not modified.
194
- if response.direct_passthrough:
195
- return
196
-
197
- if encoding != "none":
198
- response.headers["Content-Encoding"] = encoding
199
- vary = {x.strip() for x in response.headers.get("Vary", "").split(",")}
200
- vary.add("Accept-Encoding")
201
- vary.discard("")
202
- response.headers["Vary"] = ",".join(vary)
203
-
204
- if original_content_length != response.content_length:
205
- response.headers["Content-Length"] = response.content_length
206
- response.headers["X-Uncompressed-Content-Length"] = original_content_length
207
-
208
-
209
-
210
- @d_log(level=1)
211
- def run_for_dynamic_resource(self, response: Response, encoding: str) -> None:
212
- """
213
- Compress a dynamic resource.
214
- - No caching is done.
215
- """
216
-
217
- self.minify_if_html(response)
218
- self.minify_if_css(response)
219
- self.minify_if_js(response)
220
- was_compressed = self.compress_if_requested(response, encoding, "dynamic")
221
- # Protect against BREACH attack
222
- if was_compressed:
223
- tx = 2 if int(time.time() ** 3.141592) % 2 else 1
224
- rand_str: str = secrets.token_urlsafe(random.randint(32 * tx, 128 * tx))
225
- response.headers["X-Breach-Exploit-Protection-Padding"] = rand_str
226
-
227
-
228
-
229
- @d_log(level=1)
230
- def run_for_static_resource(self, response: Response, encoding: str) -> None:
231
- """
232
- Compress a static resource.
233
- """
234
-
235
- m_css = is_css(response.mimetype) and self.app.config["COMPRESS_MINIFY_CSS"]
236
- m_js = is_js(response.mimetype) and self.app.config["COMPRESS_MINIFY_JS"]
237
- minify = m_css or m_js
238
-
239
- if (from_cache := self.get_from_cache(request.path, encoding, minify)) is not None:
240
- log(1, "Found in cache. RETURN")
241
- response.direct_passthrough = False
242
- response.set_data(from_cache)
243
- response.headers["X-Flask-Squeeze-Cache"] = "HIT"
244
- return
245
-
246
- # Assert: not in cache
247
-
248
- css_was_minified = self.minify_if_css(response)
249
- js_was_minified = self.minify_if_js(response)
250
- html_was_minified = self.minify_if_html(response)
251
- minified = css_was_minified or js_was_minified or html_was_minified
252
- was_compressed = self.compress_if_requested(response, encoding, "static")
253
-
254
- if was_compressed or minified:
255
- response.headers["X-Flask-Squeeze-Cache"] = "MISS"
256
- data = response.get_data(as_text=False)
257
- self.insert_to_cache(request.path, encoding, minified, data)
258
-
259
-
260
- @d_log(level=0, with_args=[1])
261
- @add_debug_header("X-Flask-Squeeze-Total-Duration")
262
- def after_request(self, response: Response) -> Response:
263
- log(0, f"Enter after_request({response})")
264
-
265
- if response.status_code < 200 or response.status_code >= 300:
266
- log(1, "Response status code is not ok. RETURN")
267
- return response
268
-
269
- if response.content_length < self.app.config["COMPRESS_MIN_SIZE"]:
270
- log(1, "Response size is smaller than the defined minimum. RETURN")
271
- return response
272
-
273
- if "Content-Encoding" in response.headers:
274
- log(1, "Response already encoded. RETURN")
275
- return response
276
-
277
- # Assert: The response is ok, the size is above threshold, and the response is
278
- # not already encoded.
279
-
280
- encoding = get_requested_encoding(request)
281
- original_content_length = response.content_length
282
-
283
- if "/static/" not in request.path:
284
- log(1, "Dynamic resource. Compress and return.")
285
- self.run_for_dynamic_resource(response, encoding)
286
- else:
287
- log(1, "Static resource. Return from cache if already cached")
288
- self.run_for_static_resource(response, encoding)
289
-
290
- self.recompute_headers(response, encoding, original_content_length)
291
-
292
- log(0, f"cache keys: {self.cache.keys()}")
293
- return response
@@ -1,28 +0,0 @@
1
- from flask import Request
2
-
3
-
4
-
5
- def get_requested_encoding(request: Request) -> str:
6
- accepted_encodings = request.headers.get("Accept-Encoding", "").lower()
7
- if "br" in accepted_encodings:
8
- return "br"
9
- if "deflate" in accepted_encodings:
10
- return "deflate"
11
- if "gzip" in accepted_encodings:
12
- return "gzip"
13
- return "none"
14
-
15
-
16
-
17
- def is_js(mimetype: str) -> bool:
18
- return mimetype.endswith("javascript") or mimetype.endswith("json")
19
-
20
-
21
-
22
- def is_css(mimetype: str) -> bool:
23
- return mimetype.endswith("css")
24
-
25
-
26
-
27
- def is_html(mimetype: str) -> bool:
28
- return mimetype.endswith("html")
File without changes