summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHelmut Grohne <helmut@subdivi.de>2007-04-16 00:16:54 +0200
committerHelmut Grohne <helmut@subdivi.de>2007-04-16 00:16:54 +0200
commit1e92fd7f7d83fb3b73fa813e6caf7c02bb079020 (patch)
tree8802504cb262ecd1ba07162f61b2e80bf613b55c
parent0b08dacfcfced7fef1b4818a73c3f43a97fe8c8f (diff)
downloadwsgitools-1e92fd7f7d83fb3b73fa813e6caf7c02bb079020.tar.gz
added GzipWSGIFilter
-rw-r--r--wsgitools/filters.py43
1 files changed, 43 insertions, 0 deletions
diff --git a/wsgitools/filters.py b/wsgitools/filters.py
index fa42550..32d8092 100644
--- a/wsgitools/filters.py
+++ b/wsgitools/filters.py
@@ -2,6 +2,11 @@ __all__ = []
import sys
import time
+import gzip
+try:
+ import cStringIO as StringIO
+except ImportError:
+ import StringIO
__all__.append("CloseableIterator")
class CloseableIterator:
@@ -229,3 +234,41 @@ class EncodeWSGIFilter(BaseWSGIFilter):
if header.lower() != "content-type":
return (header, value)
return (header, "%s; charset=%s" % (value, self.charset))
+
+class GzipWSGIFilter(BaseWSGIFilter):
+ """Compresses content using gzip."""
+ def __init__(self):
+ self.compress = False
+ self.sio = None
+ self.gzip = None
+ def filter_environ(self, environ):
+ """BaseWSGIFilter interface"""
+ if "HTTP_ACCEPT_ENCODING" in environ:
+ acceptenc = environ["HTTP_ACCEPT_ENCODING"].split(',')
+ acceptenc = map(str.strip, acceptenc)
+ if "gzip" in acceptenc:
+ self.compress = True
+ self.sio = StringIO.StringIO()
+ self.gzip = gzip.GzipFile(fileobj=self.sio, mode="w")
+ return environ
+ def filter_headers(self, headers):
+ """BaseWSGIFilter interface"""
+ if self.compress:
+ headers.append(("Content-encoding", "gzip"))
+ return headers
+ def filter_data(self, data):
+ """BaseWSGIFilter interface"""
+ if not self.compress:
+ return data
+ self.gzip.write(data)
+ self.gzip.flush()
+ data = self.sio.getvalue()
+ self.sio.truncate(0)
+ return data
+ def append_data(self):
+ """BaseWSGIFilter interface"""
+ if not self.compress:
+ return []
+ self.gzip.close()
+ data = self.sio.getvalue()
+ return [data]