diff options
-rw-r--r-- | wsgitools/filters.py | 43 |
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] |