Debian Codegraph @

flask_compress/flask_compress.py

raw
1 # Authors: William Fagan
2 # Copyright (c) 2013-2017 William Fagan
3 # License: The MIT License (MIT)
4
5 from __future__ import annotations
6
7 import functools
8 from collections import defaultdict
9 from collections.abc import Callable, Iterator
10 from functools import lru_cache
11 from typing import Any, Protocol
12
13 try:
14 import brotlicffi as brotli
15 except ImportError:
16 import brotli
17
18 from flask import (
19 Flask,
20 after_this_request,
21 current_app,
22 make_response,
23 request,
24 stream_with_context,
25 )
26 from flask.wrappers import Response
27
28 from .compat import compression
29
30
31 class CacheBackend(Protocol):
32 def get(self, key: str) -> bytes | None: ...
33 def set(self, key: str, value: bytes) -> bool | None: ...
34
35
36 class DictCache:
37 def __init__(self) -> None:
38 self.data: dict[str, bytes] = {}
39
40 def get(self, key: str) -> bytes | None:
41 return self.data.get(key)
42
43 def set(self, key: str, value: bytes) -> None:
44 self.data[key] = value
45
46
47 @lru_cache(maxsize=128)
48 def _choose_algorithm(algorithms: tuple[str, ...], accept_encoding: str) -> str | None:
49 """
50 Determine which compression algorithm we're going to use based on the
51 client request. The `Accept-Encoding` header may list one or more desired
52 algorithms, together with a "quality factor" for each one (higher quality
53 means the client prefers that algorithm more).
54
55 :param algorithms: Tuple of supported compression algorithms
56 :param accept_encoding: Content of the `Accept-Encoding` header
57 :return: name of a compression algorithm (`gzip`, `deflate`, `br`, 'zstd')
58 or `None` if the client and server don't agree on any.
59 """
60 # A flag denoting that client requested using any (`*`) algorithm,
61 # in case a specific one is not supported by the server
62 fallback_to_any = False
63
64 # Map quality factors to requested algorithm names.
65 algos_by_quality: defaultdict[float, set[str | None]] = defaultdict(set)
66
67 # Set of supported algorithms
68 server_algos_set = set(algorithms)
69
70 for part in accept_encoding.lower().split(","):
71 part = part.strip()
72 if ";q=" in part:
73 # If the client associated a quality factor with an algorithm,
74 # try to parse it. We could do the matching using a regex, but
75 # the format is so simple that it would be overkill.
76 algo = part.split(";")[0].strip()
77 try:
78 quality = float(part.split("=")[1].strip())
79 except ValueError:
80 quality = 1.0
81 else:
82 # Otherwise, use the default quality
83 algo = part
84 quality = 1.0
85
86 if algo == "*":
87 if quality > 0:
88 fallback_to_any = True
89 elif algo == "identity": # identity means 'no compression asked'
90 algos_by_quality[quality].add(None)
91 elif algo in server_algos_set:
92 algos_by_quality[quality].add(algo)
93
94 # Choose the algorithm with the highest quality factor that the server supports.
95 #
96 # If there are multiple equally good options,
97 # choose the first supported algorithm from server configuration.
98 #
99 # If the server doesn't support any algorithm that the client requested but
100 # there's a special wildcard algorithm request (`*`), choose the first supported
101 # algorithm.
102 for _, viable_algos in sorted(algos_by_quality.items(), reverse=True):
103 if len(viable_algos) == 1:
104 return viable_algos.pop()
105 elif len(viable_algos) > 1:
106 for server_algo in algorithms:
107 if server_algo in viable_algos:
108 return server_algo
109
110 if fallback_to_any:
111 return algorithms[0]
112 return None
113
114
115 def _format(algo: str | list[str]) -> tuple[str, ...]:
116 """Format the algorithm configuration into a tuple of strings.
117
118 >>> _format("gzip, deflate, br")
119 ('gzip', 'deflate', 'br')
120 >>> _format(["gzip", "deflate", "br"])
121 ('gzip', 'deflate', 'br')
122 """
123 if isinstance(algo, str):
124 return tuple(i.strip() for i in algo.split(","))
125 else:
126 return tuple(algo)
127
128
129 class Compress:
130 """
131 The Compress object allows your application to use Flask-Compress.
132
133 When initialising a Compress object you may optionally provide your
134 :class:`flask.Flask` application object if it is ready. Otherwise,
135 you may provide it later by using the :meth:`init_app` method.
136
137 :param app: optional :class:`flask.Flask` application object
138 :type app: :class:`flask.Flask` or None
139 """
140
141 cache: CacheBackend | None
142 cache_key: Callable[..., str] | None
143 compress_mimetypes_set: set[str]
144 enabled_algorithms: tuple[str, ...]
145 streaming_algorithms: tuple[str, ...]
146 streaming_endpoint_with_conditional: set[str]
147
148 def __init__(self, app: Flask | None = None) -> None:
149 """
150 An alternative way to pass your :class:`flask.Flask` application
151 object to Flask-Compress. :meth:`init_app` also takes care of some
152 default `settings`_.
153
154 :param app: the :class:`flask.Flask` application object.
155 """
156 self.app = app
157 if app is not None:
158 self.init_app(app)
159
160 def init_app(self, app: Flask) -> None:
161 defaults = [
162 (
163 "COMPRESS_MIMETYPES",
164 [
165 "text/html",
166 "text/css",
167 "text/plain",
168 "text/xml",
169 "text/x-component",
170 "text/javascript", # Obsolete (RFC 9239)
171 "application/x-javascript",
172 "application/javascript",
173 "application/json",
174 "application/manifest+json",
175 "application/vnd.api+json",
176 "application/xml",
177 "application/xhtml+xml",
178 "application/rss+xml",
179 "application/atom+xml",
180 "application/vnd.ms-fontobject",
181 "application/x-font-ttf",
182 "application/x-font-opentype",
183 "application/x-font-truetype",
184 "image/svg+xml",
185 "image/x-icon",
186 "image/vnd.microsoft.icon",
187 "font/ttf",
188 "font/eot",
189 "font/otf",
190 "font/opentype",
191 ],
192 ),
193 ("COMPRESS_LEVEL", 6),
194 ("COMPRESS_BR_LEVEL", 4),
195 ("COMPRESS_BR_MODE", 0),
196 ("COMPRESS_BR_WINDOW", 22),
197 ("COMPRESS_BR_BLOCK", 0),
198 ("COMPRESS_ZSTD_LEVEL", 3),
199 ("COMPRESS_DEFLATE_LEVEL", -1),
200 ("COMPRESS_MIN_SIZE", 500),
201 ("COMPRESS_CACHE_KEY", None),
202 ("COMPRESS_CACHE_BACKEND", None),
203 ("COMPRESS_REGISTER", True),
204 ("COMPRESS_STREAMS", True),
205 ("COMPRESS_EVALUATE_CONDITIONAL_REQUEST", True),
206 ("COMPRESS_STREAMING_ENDPOINT_CONDITIONAL", ["static"]),
207 ("COMPRESS_ALGORITHM", ["zstd", "br", "gzip", "deflate"]),
208 ("COMPRESS_ALGORITHM_STREAMING", ["zstd", "br", "deflate"]), # no gzip
209 ]
210
211 for k, v in defaults:
212 app.config.setdefault(k, v)
213
214 backend = app.config["COMPRESS_CACHE_BACKEND"]
215 self.cache = backend() if backend else None
216 self.cache_key = app.config["COMPRESS_CACHE_KEY"]
217
218 self.compress_mimetypes_set = set(app.config["COMPRESS_MIMETYPES"])
219 self.enabled_algorithms = _format(app.config["COMPRESS_ALGORITHM"])
220 self.streaming_algorithms = _format(app.config["COMPRESS_ALGORITHM_STREAMING"])
221 self.streaming_endpoint_with_conditional = set(
222 app.config["COMPRESS_STREAMING_ENDPOINT_CONDITIONAL"]
223 )
224
225 if app.config["COMPRESS_REGISTER"] and app.config["COMPRESS_MIMETYPES"]:
226 app.after_request(self.after_request)
227
228 def after_request(self, response: Response | None) -> Response:
229 if not response:
230 return make_response("", 204)
231
232 app = self.app or current_app
233 vary = response.headers.get("Vary")
234 if not vary:
235 response.headers["Vary"] = "Accept-Encoding"
236 elif "accept-encoding" not in vary.lower():
237 response.headers["Vary"] = f"{vary}, Accept-Encoding"
238
239 accept_encoding = request.headers.get("Accept-Encoding", "")
240 streaming_compressed = response.is_streamed and app.config["COMPRESS_STREAMS"]
241 streaming_conditional = response.is_streamed and (
242 request.endpoint in self.streaming_endpoint_with_conditional
243 )
244 algorithms = (
245 self.streaming_algorithms
246 if streaming_compressed
247 else self.enabled_algorithms
248 )
249 chosen_algorithm = _choose_algorithm(algorithms, accept_encoding)
250
251 if (
252 chosen_algorithm is None
253 or response.mimetype not in self.compress_mimetypes_set
254 or response.status_code < 200
255 or response.status_code >= 300
256 or (response.is_streamed and not app.config["COMPRESS_STREAMS"])
257 or "Content-Encoding" in response.headers
258 or (
259 response.content_length is not None
260 and response.content_length < app.config["COMPRESS_MIN_SIZE"]
261 )
262 ):
263 return response
264
265 response.direct_passthrough = False
266 response.headers["Content-Encoding"] = chosen_algorithm
267
268 if streaming_compressed:
269 chunks = response.iter_encoded()
270 _gen_compressed_content = _compress_chunks(app, chunks, chosen_algorithm)
271 response.response = stream_with_context(_gen_compressed_content)
272 response.headers.pop("Content-Length", None)
273 else:
274 if self.cache is not None:
275 assert self.cache_key is not None
276 key = f"{chosen_algorithm};{self.cache_key(request)}"
277 compressed_content = self.cache.get(key)
278 if compressed_content is None:
279 data = response.get_data()
280 compressed_content = _compress_data(app, data, chosen_algorithm)
281 self.cache.set(key, compressed_content)
282 else:
283 data = response.get_data()
284 compressed_content = _compress_data(app, data, chosen_algorithm)
285
286 response.set_data(compressed_content)
287 response.headers["Content-Length"] = response.content_length
288
289 # "123456789" => "123456789:gzip" - A strong ETag validator
290 # W/"123456789" => W/"123456789:gzip" - A weak ETag validator
291 etag, is_weak = response.get_etag()
292
293 if etag and not is_weak:
294 response.set_etag(f"{etag}:{chosen_algorithm}", weak=False)
295
296 if (
297 app.config["COMPRESS_EVALUATE_CONDITIONAL_REQUEST"]
298 and request.method in ("GET", "HEAD")
299 and (not response.is_streamed or streaming_conditional)
300 ):
301 response.make_conditional(request)
302
303 return response
304
305 def compressed(self) -> Callable[..., Callable[..., Any]]:
306 def decorator(f: Callable[..., Any]) -> Callable[..., Any]:
307 @functools.wraps(f)
308 def decorated_function(*args: Any, **kwargs: Any) -> Any:
309 @after_this_request
310 def compressor(response: Response) -> Response:
311 return self.after_request(response)
312
313 return f(*args, **kwargs)
314
315 return decorated_function
316
317 return decorator
318
319
320 def _compress_data(app: Flask, data: bytes, algorithm: str) -> bytes:
321 if algorithm == "zstd":
322 return compression.zstd.compress( # type: ignore[no-any-return]
323 data, app.config["COMPRESS_ZSTD_LEVEL"]
324 )
325
326 if algorithm == "gzip":
327 return compression.gzip.compress( # type: ignore[no-any-return]
328 data, app.config["COMPRESS_LEVEL"]
329 )
330
331 if algorithm == "deflate":
332 return compression.zlib.compress( # type: ignore[no-any-return]
333 data, app.config["COMPRESS_DEFLATE_LEVEL"]
334 )
335
336 if algorithm == "br":
337 return brotli.compress( # type: ignore[no-any-return]
338 data,
339 mode=app.config["COMPRESS_BR_MODE"],
340 quality=app.config["COMPRESS_BR_LEVEL"],
341 lgwin=app.config["COMPRESS_BR_WINDOW"],
342 lgblock=app.config["COMPRESS_BR_BLOCK"],
343 )
344
345 raise ValueError(f"Unknown compression algorithm: {algorithm}")
346
347
348 def _uncompress_data(data: bytes, algorithm: str) -> bytes:
349 # This is used for tests purposes only.
350 if algorithm == "zstd":
351 return compression.zstd.decompress(data) # type: ignore[no-any-return]
352 if algorithm == "gzip":
353 return compression.gzip.decompress(data) # type: ignore[no-any-return]
354 if algorithm == "deflate":
355 return compression.zlib.decompress(data) # type: ignore[no-any-return]
356 if algorithm == "br":
357 return brotli.decompress(data) # type: ignore[no-any-return]
358
359 raise ValueError(f"Unknown compression algorithm: {algorithm}")
360
361
362 def _compress_chunks(
363 app: Flask, chunks: Iterator[bytes], algorithm: str
364 ) -> Iterator[bytes]:
365 if algorithm == "zstd":
366 level = app.config["COMPRESS_ZSTD_LEVEL"]
367 compressor = compression.zstd.ZstdCompressor(level=level)
368 for data in chunks:
369 out = compressor.compress(data)
370 if out:
371 yield out
372 out = compressor.flush()
373 if out:
374 yield out
375
376 elif algorithm == "gzip":
377 level = app.config["COMPRESS_LEVEL"]
378 compressor = compression.zlib.compressobj(
379 level,
380 compression.zlib.DEFLATED,
381 compression.zlib.MAX_WBITS + 16,
382 )
383 for data in chunks:
384 out = compressor.compress(data)
385 if out:
386 yield out
387 out = compressor.flush()
388 if out:
389 yield out
390
391 elif algorithm == "deflate":
392 level = app.config["COMPRESS_DEFLATE_LEVEL"]
393 compressor = compression.zlib.compressobj(level=level)
394 for data in chunks:
395 out = compressor.compress(data)
396 if out:
397 yield out
398 out = compressor.flush()
399 if out:
400 yield out
401
402 elif algorithm == "br":
403 compressor = brotli.Compressor(
404 mode=app.config["COMPRESS_BR_MODE"],
405 quality=app.config["COMPRESS_BR_LEVEL"],
406 lgwin=app.config["COMPRESS_BR_WINDOW"],
407 lgblock=app.config["COMPRESS_BR_BLOCK"],
408 )
409 for data in chunks:
410 out = compressor.process(data)
411 if out:
412 yield out
413 out = compressor.finish()
414 if out:
415 yield out
416 else:
417 raise ValueError(f"Unsupported streaming algorithm: {algorithm}")