Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Content-Encoding: gzip with Python SimpleHTTPServer

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?

like image 758
Jason Sundram Avatar asked Mar 08 '12 18:03

Jason Sundram


People also ask

What is content encoding gzip?

Gzip is a file format and software application used on Unix and Unix-like systems to compress HTTP content before it's served to a client.

What is gzip and deflate encoding?

The browser sends a header telling the server it accepts compressed content (gzip and deflate are two compression schemes): Accept-Encoding: gzip, deflate. The server sends a response if the content is actually compressed: Content-Encoding: gzip.


2 Answers

This was a feature request but rejected due to wanting to keep the simple http server simple: https://bugs.python.org/issue30576

The issue author eventually released a standalone version for Python 3: https://github.com/PierreQuentel/httpcompressionserver

like image 148
qwr Avatar answered Oct 31 '22 01:10

qwr


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()
like image 25
velis Avatar answered Oct 31 '22 00:10

velis