How to use Content-Encoding: gzip with Python SimpleHTTPServer

Jason Sundram picture Jason Sundram · Mar 8, 2012 · Viewed 15.5k times · Source

I'm using python -m SimpleHTTPServer to serve up a directory for local testing in a web browser. Some of the content includes large data files. I would like to be able to gzip them and have SimpleHTTPServer serve them with Content-Encoding: gzip.

Is there an easy way to do this?

Answer

velis picture velis · Jun 12, 2013

This is an old question, but it still ranks #1 in Google for me, so I suppose a proper answer might be of use to someone beside me.

The solution turns out to be very simple. in the do_GET(), do_POST, etc, you only need to add the following:

content = self.gzipencode(strcontent)
...your other headers, etc...
self.send_header("Content-length", str(len(str(content))))
self.send_header("Content-Encoding", "gzip")
self.end_headers()
self.wfile.write(content)
self.wfile.flush()

strcontent being your actual content (as in HTML, javascript or other HTML resources) and the gzipencode:

def gzipencode(self, content):
    import StringIO
    import gzip
    out = StringIO.StringIO()
    f = gzip.GzipFile(fileobj=out, mode='w', compresslevel=5)
    f.write(content)
    f.close()
    return out.getvalue()