Skip to content

Instantly share code, notes, and snippets.

@hackaugusto
Created March 17, 2012 19:44
Show Gist options
  • Select an option

  • Save hackaugusto/2064711 to your computer and use it in GitHub Desktop.

Select an option

Save hackaugusto/2064711 to your computer and use it in GitHub Desktop.
django gzip middleware with streaming support
Index: gzip.py
===================================================================
--- gzip.py (revision 17761)
+++ gzip.py (working copy)
@@ -1,4 +1,5 @@
import re
+from zlib import compressobj
from django.utils.text import compress_string
from django.utils.cache import patch_vary_headers
@@ -32,15 +33,12 @@
if not re_accepts_gzip.search(ae):
return response
- # Return the compressed content only if it's actually shorter.
- compressed_content = compress_string(response.content)
- if len(compressed_content) >= len(response.content):
- return response
+ compressor = compressobj()
+ content = iter(response.content):
+ response.content = ( compressor.compress(data) for data in content )
if response.has_header('ETag'):
response['ETag'] = re.sub('"$', ';gzip"', response['ETag'])
+ response['Content-Encoding'] = 'gzip'
- response.content = compressed_content
- response['Content-Encoding'] = 'gzip'
- response['Content-Length'] = str(len(response.content))
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment