Skip to content

Instantly share code, notes, and snippets.

@lukestanley
Created February 17, 2017 13:55
Show Gist options
  • Save lukestanley/a6cb1daffd2f0ed9829b6b96e067d8cf to your computer and use it in GitHub Desktop.
Save lukestanley/a6cb1daffd2f0ed9829b6b96e067d8cf to your computer and use it in GitHub Desktop.
How to use compression with Sanic responses and requests using gzip
def compress_requests_and_responses(app):
import gzip
@app.middleware('response')
async def compress_response(request, response):
uncompressed_body_length = len(response.body)
wants_gzip = 'gzip' in request.headers['Accept-Encoding']
if (uncompressed_body_length > 0) and wants_gzip:
compressed_body = gzip.compress(response.body)
compressed_body_length = len(compressed_body)
if compressed_body_length < uncompressed_body_length:
response.body = compressed_body
response.headers["Content-Encoding"] = "gzip"
response.headers["Vary"] = "Accept-Encoding"
response.headers["Content-Length"] = compressed_body_length
@app.middleware('request')
async def compress_request(request):
if "Content-Encoding" in request.headers:
if request.headers["Content-Encoding"] == "gzip":
request.body = gzip.decompress(request.body)
@lukestanley
Copy link
Author

lukestanley commented Feb 17, 2017

Use like this:
from compress_middleware import compress_requests_and_responses
compress_requests_and_responses(app)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment