Gzip response in Flask/Tornado Gzip response in Flask/Tornado flask flask

Gzip response in Flask/Tornado


The simplest way is to use Nginx, as Nikolay suggested. It won't add much overhead.

With tornado.web.Application, you can just pass compress_response=True when initializing the app. Since you're using a Flask, that won't work. You could look at the Tornado source and see what it's doing, but that won't be simple.


It just appears weird to set up an nginx only to have gzip compression.

Now I use this http://code.google.com/p/ibkon-wsgi-gzip-middleware/, it's good.


Assuming you want to reply to a post request then in your tornado.web.RequestHandler derived class, within the "def post(self):"

self.set_header("Content-type", 'text/plain') # or whatever you expectself.set_header("Content-Encoding", 'gzip')# don't forget to import zlibgzip_compress = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)# response is the string where your response iscontent = gzip_compress.compress(response) + gzip_compress.flush()compressed_content_length = len(content)self.set_header("Content-Length", compressed_content_length)self.write(content)