欢迎访问宙启技术站
智能推送

如何在Python中用gzip压缩HTML响应

发布时间:2023-12-17 15:46:06

在Python中使用gzip压缩HTML响应可以通过使用gzip模块和cStringIO模块来实现。下面是一个简单的使用例子。

首先,导入gzip和cStringIO模块:

import gzip
import cStringIO

接下来,创建一个简单的HTML响应:

html_content = """
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<h1>Example HTML</h1>
<p>This is an example HTML page.</p>
</body>
</html>
"""

然后,使用cStringIO模块将HTML内容存储到一个临时的内存缓冲区中:

output = cStringIO.StringIO()
gzip_file = gzip.GzipFile(fileobj=output, mode='w')
gzip_file.write(html_content)
gzip_file.close()
compressed_html = output.getvalue()
output.close()

最后,将压缩后的HTML响应作为HTTP响应发送给客户端。这可以通过设置HTTP响应头中的"Content-Encoding"为"gzip"来实现:

import sys
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class MyRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-Encoding', 'gzip')
        self.send_header('Content-Length', str(len(compressed_html)))
        self.send_header('Content-Type', 'text/html')
        self.end_headers()
        self.wfile.write(compressed_html)

def run(server_class=HTTPServer, handler_class=MyRequestHandler, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print('Starting server on port %d...' % port)
    httpd.serve_forever()

run()

现在,执行上述Python代码后,将会在本地8000端口创建一个简单的HTTP服务器,该服务器会发送压缩后的HTML响应。你可以在浏览器中访问http://localhost:8000来查看压缩后的HTML页面。