如何使用Content-Encoding:使用Python SimpleHTTPServer的gzip

时间:2012-03-08 18:41:27

标签: python gzip simplehttpserver

我正在使用python -m SimpleHTTPServer在Web浏览器中提供本地测试的目录。一些内容包括大数据文件。我希望能够对它们进行gzip,并让SimpleHTTPServer使用Content-Encoding:gzip为它们提供服务。

有一种简单的方法吗?

6 个答案:

答案 0 :(得分:7)

由于这是google的最高结果,我想我会将简单的修改发布到让gzip工作的脚本上。

https://github.com/ksmith97/GzipSimpleHTTPServer

答案 1 :(得分:4)

这是一个老问题,但它仍然在Google中排名第一,所以我认为一个正确的答案可能会对我旁边的人有用。

解决方案结果非常简单。在do_GET(),do_POST等中,您只需要添加以下内容:

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是您的实际内容(如HTML,javascript或其他HTML资源) 和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()

答案 2 :(得分:2)

和其他许多人一样,我也一直在使用python -m SimpleHTTPServer进行本地测试。这仍然是谷歌的最佳结果,虽然https://github.com/ksmith97/GzipSimpleHTTPServer是一个不错的解决方案,但即使没有请求也会强制执行gzip,并且没有启用/禁用它的标志。

我决定写一个支持这个的小cli工具。它已经开始了,所以常规安装程序就是:

go get github.com/rhardih/serve

如果您已将$GOPATH添加到$PATH,那就是您所需要的一切。现在你有serve作为命令。

https://github.com/rhardih/serve

答案 3 :(得分:0)

从SimpleHTTPServer的documentation开始,没有办法。不过,我建议lighttpd with the mod_compress module

答案 4 :(得分:0)

在上面的@velis回答的基础上,我就是这样做的。 gZipping小数据不值得花时间,可以增加它的大小。经过Dalvik客户测试。

def do_GET(self):
    ... get content
    self.send_response(returnCode)       # 200, 401, etc
    ...your other headers, etc...
    if len(content) > 100:                       # don't bother compressing small data
        if 'accept-encoding' in self.headers:    # case insensitive
            if 'gzip' in self.headers['accept-encoding']:
                content = gzipencode(content)    # gzipencode defined above in @velis answer
                self.send_header('content-encoding', 'gzip')
    self.send_header('content-length', len(content))
    self.end_headers()          # send a blank line
    self.wfile.write(content)

答案 5 :(得分:0)

这是一个功能请求,但由于想让简单的 http 服务器保持简单而被拒绝:https://bugs.python.org/issue30576

问题作者最终发布了 Python 3 的独立版本:https://github.com/PierreQuentel/httpcompressionserver