我正在使用python -m SimpleHTTPServer
在 Web 浏览器中为本地测试提供目录。一些内容包括大型数据文件。我希望能够对它们进行 gzip 压缩,并让 SimpleHTTPServer 使用 Content-Encoding: gzip 为它们提供服务。
是否有捷径可寻?
我正在使用python -m SimpleHTTPServer
在 Web 浏览器中为本地测试提供目录。一些内容包括大型数据文件。我希望能够对它们进行 gzip 压缩,并让 SimpleHTTPServer 使用 Content-Encoding: gzip 为它们提供服务。
是否有捷径可寻?
这是一个老问题,但对我来说它仍然在谷歌中排名第一,所以我想一个正确的答案可能对我身边的人有用。
解决方案非常简单。在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()
由于这是谷歌的最高结果,我想我会将我的简单修改发布到让 gzip 工作的脚本。
和许多其他人一样,我也一直在使用python -m SimpleHTTPServer
本地测试。这仍然是谷歌上的最佳结果,虽然https://github.com/ksmith97/GzipSimpleHTTPServer是一个不错的解决方案,但即使没有请求,它也会强制执行 gzip,并且没有启用/禁用它的标志。
我决定编写一个支持此功能的小型 cli 工具。好了,所以常规的安装过程很简单:
go get github.com/rhardih/serve
如果您已经$GOPATH
添加到$PATH
,这就是您所需要的。现在你有serve
一个命令。
这是一个功能请求,但由于想要保持简单的 http 服务器简单而被拒绝:https ://bugs.python.org/issue30576
问题作者最终发布了 Python 3 的独立版本:https ://github.com/PierreQuentel/httpcompressionserver
基于上面的@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)
从查看 SimpleHTTPServer 的文档来看,没有办法。但是,我建议使用带有 mod_compress 模块的 lighttpd。