# Copyright (c) 2005 Allan Saddi # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # $Id$ """WSGI response gzipper middleware. This gzip middleware component differentiates itself from others in that it (hopefully) follows the spec more closely. Namely with regard to the application iterator and buffering. (It doesn't buffer.) See `Middleware Handling of Block Boundaries`_. Of course this all comes with a price... just LOOK at this mess! :) The inner workings of gzip and the gzip file format were gleaned from gzip.py. .. _Middleware Handling of Block Boundaries: http://www.python.org/dev/peps/pep-0333/#middleware-handling-of-block-boundaries """ __author__ = 'Allan Saddi ' __version__ = '$Revision$' import struct import time import zlib import re __all__ = ['GzipMiddleware'] def _gzip_header(): """Returns a gzip header (with no filename).""" # See GzipFile._write_gzip_header in gzip.py return '\037\213' \ '\010' \ '\0' + \ struct.pack(' 0: self._size += length self._crc = zlib.crc32(data, self._crc) out += self._compress.compress(data) return out def gzip_trailer(self): """Returns the gzip trailer.""" # See GzipFile.close in gzip.py return self._compress.flush() + \ struct.pack('