Created
June 24, 2021 16:03
-
-
Save BeastImran/84dd22e5146b71e6296fb6b546201a28 to your computer and use it in GitHub Desktop.
gzip response
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
import gzip | |
from io import BytesIO as IO | |
def send_response(request, response): | |
accept_encoding = request.headers.get("Accept-Encoding", "") or request.headers.get("accept-encoding", "") | |
if ("gzip" not in accept_encoding.lower()) or (response.status < 200 or response.status >= 300 or "Content-Encoding" in response.headers): | |
return response | |
gzip_buffer = IO() | |
gzip_file = gzip.GzipFile(mode="wb", fileobj=gzip_buffer) | |
gzip_file.write(response.body) | |
gzip_file.close() | |
response.body = gzip_buffer.getvalue() | |
response.headers["content-encoding"] = "gzip" | |
response.headers["vary"] = "accept-encoding" | |
response.headers["content-length"] = len(response.body) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment