aboutsummaryrefslogtreecommitdiffhomepage
path: root/custom_libs/flask_compress/flask_compress.py
blob: 0bebff0a8f7a9960ecad42d4b054eb1876db3fd1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244

# Authors: William Fagan
# Copyright (c) 2013-2017 William Fagan
# License: The MIT License (MIT)

import sys
import functools
from gzip import GzipFile
import zlib
from io import BytesIO

from collections import defaultdict

from flask import request, after_this_request, current_app


if sys.version_info[:2] == (2, 6):
    class GzipFile(GzipFile):
        """ Backport of context manager support for python 2.6"""
        def __enter__(self):
            if self.fileobj is None:
                raise ValueError("I/O operation on closed GzipFile object")
            return self

        def __exit__(self, *args):
            self.close()


class DictCache(object):

    def __init__(self):
        self.data = {}

    def get(self, key):
        return self.data.get(key)

    def set(self, key, value):
        self.data[key] = value


class Compress(object):
    """
    The Compress object allows your application to use Flask-Compress.

    When initialising a Compress object you may optionally provide your
    :class:`flask.Flask` application object if it is ready. Otherwise,
    you may provide it later by using the :meth:`init_app` method.

    :param app: optional :class:`flask.Flask` application object
    :type app: :class:`flask.Flask` or None
    """
    def __init__(self, app=None):
        """
        An alternative way to pass your :class:`flask.Flask` application
        object to Flask-Compress. :meth:`init_app` also takes care of some
        default `settings`_.

        :param app: the :class:`flask.Flask` application object.
        """
        self.app = app
        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        defaults = [
            ('COMPRESS_MIMETYPES', [
                'application/javascript',  # Obsolete (RFC 9239)
                'application/json',
                'text/css',
                'text/html',
                'text/javascript',
                'text/xml',
            ]),
            ('COMPRESS_LEVEL', 6),
            ('COMPRESS_BR_LEVEL', 4),
            ('COMPRESS_BR_MODE', 0),
            ('COMPRESS_BR_WINDOW', 22),
            ('COMPRESS_BR_BLOCK', 0),
            ('COMPRESS_DEFLATE_LEVEL', -1),
            ('COMPRESS_MIN_SIZE', 500),
            ('COMPRESS_CACHE_KEY', None),
            ('COMPRESS_CACHE_BACKEND', None),
            ('COMPRESS_REGISTER', True),
            ('COMPRESS_STREAMS', True),
            ('COMPRESS_ALGORITHM', ['br', 'gzip', 'deflate']),
        ]

        for k, v in defaults:
            app.config.setdefault(k, v)

        backend = app.config['COMPRESS_CACHE_BACKEND']
        self.cache = backend() if backend else None
        self.cache_key = app.config['COMPRESS_CACHE_KEY']

        algo = app.config['COMPRESS_ALGORITHM']
        if isinstance(algo, str):
            self.enabled_algorithms = [i.strip() for i in algo.split(',')]
        else:
            self.enabled_algorithms = list(algo)

        if (app.config['COMPRESS_REGISTER'] and
                app.config['COMPRESS_MIMETYPES']):
            app.after_request(self.after_request)

    def _choose_compress_algorithm(self, accept_encoding_header):
        """
        Determine which compression algorithm we're going to use based on the
        client request. The `Accept-Encoding` header may list one or more desired
        algorithms, together with a "quality factor" for each one (higher quality
        means the client prefers that algorithm more).

        :param accept_encoding_header: Content of the `Accept-Encoding` header
        :return: name of a compression algorithm (`gzip`, `deflate`, `br`) or `None` if
            the client and server don't agree on any.
        """
        # A flag denoting that client requested using any (`*`) algorithm,
        # in case a specific one is not supported by the server
        fallback_to_any = False

        # Map quality factors to requested algorithm names.
        algos_by_quality = defaultdict(set)

        # Set of supported algorithms
        server_algos_set = set(self.enabled_algorithms)

        for part in accept_encoding_header.lower().split(','):
            part = part.strip()
            if ';q=' in part:
                # If the client associated a quality factor with an algorithm,
                # try to parse it. We could do the matching using a regex, but
                # the format is so simple that it would be overkill.
                algo = part.split(';')[0].strip()
                try:
                    quality = float(part.split('=')[1].strip())
                except ValueError:
                    quality = 1.0
            else:
                # Otherwise, use the default quality
                algo = part
                quality = 1.0

            if algo == '*':
                if quality > 0:
                    fallback_to_any = True
            elif algo == 'identity':  # identity means 'no compression asked'
                algos_by_quality[quality].add(None)
            elif algo in server_algos_set:
                algos_by_quality[quality].add(algo)

        # Choose the algorithm with the highest quality factor that the server supports.
        #
        # If there are multiple equally good options, choose the first supported algorithm
        # from server configuration.
        #
        # If the server doesn't support any algorithm that the client requested but
        # there's a special wildcard algorithm request (`*`), choose the first supported
        # algorithm.
        for _, viable_algos in sorted(algos_by_quality.items(), reverse=True):
            if len(viable_algos) == 1:
                return viable_algos.pop()
            elif len(viable_algos) > 1:
                for server_algo in self.enabled_algorithms:
                    if server_algo in viable_algos:
                        return server_algo

        if fallback_to_any:
            return self.enabled_algorithms[0]
        return None

    def after_request(self, response):
        app = self.app or current_app

        vary = response.headers.get('Vary')
        if not vary:
            response.headers['Vary'] = 'Accept-Encoding'
        elif 'accept-encoding' not in vary.lower():
            response.headers['Vary'] = '{}, Accept-Encoding'.format(vary)

        accept_encoding = request.headers.get('Accept-Encoding', '')
        chosen_algorithm = self._choose_compress_algorithm(accept_encoding)

        if (chosen_algorithm is None or
            response.mimetype not in app.config["COMPRESS_MIMETYPES"] or
            response.status_code < 200 or
            response.status_code >= 300 or
            (response.is_streamed and app.config["COMPRESS_STREAMS"] is False)or
            "Content-Encoding" in response.headers or
            (response.content_length is not None and
             response.content_length < app.config["COMPRESS_MIN_SIZE"])):
            return response

        response.direct_passthrough = False

        if self.cache is not None:
            key = self.cache_key(request)
            compressed_content = self.cache.get(key)
            if compressed_content is None:
                compressed_content = self.compress(app, response, chosen_algorithm)
            self.cache.set(key, compressed_content)
        else:
            compressed_content = self.compress(app, response, chosen_algorithm)

        response.set_data(compressed_content)

        response.headers['Content-Encoding'] = chosen_algorithm
        response.headers['Content-Length'] = response.content_length

        # "123456789"   => "123456789:gzip"   - A strong ETag validator
        # W/"123456789" => W/"123456789:gzip" - A weak ETag validator
        etag = response.headers.get('ETag')
        if etag:
            response.headers['ETag'] = '{0}:{1}"'.format(etag[:-1], chosen_algorithm)

        return response

    def compressed(self):
        def decorator(f):
            @functools.wraps(f)
            def decorated_function(*args, **kwargs):
                @after_this_request
                def compressor(response):
                    return self.after_request(response)
                return f(*args, **kwargs)
            return decorated_function
        return decorator

    def compress(self, app, response, algorithm):
        if algorithm == 'gzip':
            gzip_buffer = BytesIO()
            with GzipFile(mode='wb',
                          compresslevel=app.config['COMPRESS_LEVEL'],
                          fileobj=gzip_buffer) as gzip_file:
                gzip_file.write(response.get_data())
            return gzip_buffer.getvalue()
        elif algorithm == 'deflate':
            return zlib.compress(response.get_data(),
                                 app.config['COMPRESS_DEFLATE_LEVEL'])
        elif algorithm == 'br':
            import brotli
            return brotli.compress(response.get_data(),
                                   mode=app.config['COMPRESS_BR_MODE'],
                                   quality=app.config['COMPRESS_BR_LEVEL'],
                                   lgwin=app.config['COMPRESS_BR_WINDOW'],
                                   lgblock=app.config['COMPRESS_BR_BLOCK'])