Đây là một câu hỏi cũ, nhưng nó vẫn đứng thứ 1 trong Google đối với tôi, vì vậy tôi cho rằng câu trả lời thích hợp có thể được sử dụng cho người bên cạnh tôi.
Giải pháp hóa ra rất đơn giản. trong do_GET(), do_POST, vv, bạn chỉ cần thêm dòng sau:
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 là nội dung thực tế của bạn (như trong HTML, javascript hoặc nguồn HTML khác) và 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()
Xem có cách dưới đây – SoloPilot