Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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