Skip to content

Instantly share code, notes, and snippets.

@sebastibe
Created May 31, 2013 11:35
Show Gist options
  • Save sebastibe/5684422 to your computer and use it in GitHub Desktop.
Save sebastibe/5684422 to your computer and use it in GitHub Desktop.
A simple WSGI middleware to unzip HTTP requests when the Content-Encoding header is set to 'gzip'
import logging
from StringIO import StringIO
import zlib
class UnzipRequestMiddleware(object):
"""A middleware that unzips POSTed data.
For this middleware to kick in, the client must provide a value
for the ``Content-Encoding`` header. The only accepted value is
``gzip``. Any other value is ignored.
"""
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
encoding = environ.get('HTTP_CONTENT_ENCODING')
if encoding == 'gzip':
data = environ['wsgi.input'].read(int(environ.get('CONTENT_LENGTH', '0')))
try:
uncompressed = zlib.decompress(data)
environ['wsgi.input'] = StringIO(uncompressed)
environ['CONTENT_LENGTH'] = len(uncompressed)
except zlib.error:
logging.warning(u"Could not decompress request data.", exc_info=True)
environ['wsgi.input'] = StringIO(data)
return self.app(environ, start_response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment