Created
February 17, 2017 13:55
-
-
Save lukestanley/a6cb1daffd2f0ed9829b6b96e067d8cf to your computer and use it in GitHub Desktop.
How to use compression with Sanic responses and requests using gzip
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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use like this:
from compress_middleware import compress_requests_and_responses
compress_requests_and_responses(app)