Created
March 18, 2019 03:45
-
-
Save RainJayTsai/a1c1568be582f1e17b12d01d2a63aa59 to your computer and use it in GitHub Desktop.
python sanic compress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
### fork from https://github.com/subyraman/sanic_compress | |
import gzip | |
DEFAULT_MIME_TYPES = frozenset([ | |
'text/html', 'text/css', 'text/xml', | |
'application/json', | |
'application/javascript']) | |
class Compress(object): | |
def __init__(self, app=None): | |
self.app = app | |
if app is not None: | |
self.init_app(app) | |
def init_app(self, app): | |
defaults = [ | |
('COMPRESS_MIMETYPES', DEFAULT_MIME_TYPES), | |
('COMPRESS_LEVEL', 6), | |
('COMPRESS_MIN_SIZE', 500), | |
] | |
for k, v in defaults: | |
app.config.setdefault(k, v) | |
@app.middleware('response') | |
async def compress_response(request, response): | |
return (await self._compress_response(request, response)) | |
async def _compress_response(self, request, response): | |
accept_encoding = request.headers.get('Accept-Encoding', '') | |
try: | |
content_length = len(response.body) | |
except: | |
return None | |
content_type = response.content_type | |
if ';' in response.content_type: | |
content_type = content_type.split(';')[0] | |
if (content_type not in self.app.config['COMPRESS_MIMETYPES'] or | |
'gzip' not in accept_encoding.lower() or | |
not 200 <= response.status < 300 or | |
(content_length is not None and | |
content_length < self.app.config['COMPRESS_MIN_SIZE']) or | |
'Content-Encoding' in response.headers): | |
return None | |
gzip_content = self.compress(response) | |
response.body = gzip_content | |
response.headers['Content-Encoding'] = 'gzip' | |
response.headers['Content-Length'] = len(response.body) | |
vary = response.headers.get('Vary') | |
if vary: | |
if 'accept-encoding' not in vary.lower(): | |
response.headers['Vary'] = '{}, Accept-Encoding'.format(vary) | |
else: | |
response.headers['Vary'] = 'Accept-Encoding' | |
return None | |
def compress(self, response): | |
out = gzip.compress( | |
response.body, | |
compresslevel=self.app.config['COMPRESS_LEVEL']) | |
return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment