🎨 run black
This commit is contained in:
parent
f1d1aebc96
commit
b14db9a0ae
1 changed files with 19 additions and 19 deletions
|
@ -1,14 +1,11 @@
|
||||||
|
|
||||||
"""
|
"""
|
||||||
Source code inspiration :https://github.com/colour-science/flask-compress/blob/master/flask_compress/flask_compress.py
|
Source code inspiration: https://github.com/colour-science/flask-compress/blob/master/flask_compress/flask_compress.py
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
from spiderweb.middleware import SpiderwebMiddleware
|
from spiderweb.middleware import SpiderwebMiddleware
|
||||||
from spiderweb.request import Request
|
from spiderweb.request import Request
|
||||||
from spiderweb.response import HttpResponse
|
from spiderweb.response import HttpResponse
|
||||||
|
|
||||||
|
|
||||||
import gzip
|
import gzip
|
||||||
|
|
||||||
|
|
||||||
|
@ -17,20 +14,23 @@ class GzipMiddleware(SpiderwebMiddleware):
|
||||||
algorithm = "gzip"
|
algorithm = "gzip"
|
||||||
minimum_length = 500
|
minimum_length = 500
|
||||||
|
|
||||||
def post_process(self, request: Request, response: HttpResponse, rendered_response: str) -> str:
|
def post_process(
|
||||||
|
self, request: Request, response: HttpResponse, rendered_response: str
|
||||||
|
) -> str:
|
||||||
|
|
||||||
#right status, length > 500, instance string (because FileResponse returns list of bytes ,
|
# right status, length > 500, instance string (because FileResponse returns list of bytes,
|
||||||
# not already compressed, and client accepts gzip
|
# not already compressed, and client accepts gzip
|
||||||
if not (200 <= response.status_code < 300) or \
|
if (
|
||||||
len(rendered_response) < self.minimum_length or \
|
not (200 <= response.status_code < 300)
|
||||||
not isinstance(rendered_response, str) or \
|
or len(rendered_response) < self.minimum_length
|
||||||
self.algorithm in response.headers.get("Content-Encoding", "") or \
|
or not isinstance(rendered_response, str)
|
||||||
self.algorithm not in request.headers.get("Accept-Encoding", ""):
|
or self.algorithm in response.headers.get("Content-Encoding", "")
|
||||||
return rendered_response
|
or self.algorithm not in request.headers.get("Accept-Encoding", "")
|
||||||
|
):
|
||||||
|
return rendered_response
|
||||||
|
|
||||||
zipped = gzip.compress(rendered_response.encode('UTF-8'))
|
zipped = gzip.compress(rendered_response.encode("UTF-8"), compresslevel=6)
|
||||||
response.headers["Content-Encoding"] = self.algorithm
|
response.headers["Content-Encoding"] = self.algorithm
|
||||||
response.headers["Content-Length"] = str(len(zipped))
|
response.headers["Content-Length"] = str(len(zipped))
|
||||||
|
|
||||||
return zipped
|
return zipped.decode("UTF-8")
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue