Skip to content

Instantly share code, notes, and snippets.

@BeastImran
Created June 24, 2021 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BeastImran/84dd22e5146b71e6296fb6b546201a28 to your computer and use it in GitHub Desktop.
Save BeastImran/84dd22e5146b71e6296fb6b546201a28 to your computer and use it in GitHub Desktop.
gzip response
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