我想知道是否可以为服务器发送事件(SSE;Content-Type: text/event-stream)启用gzip压缩。
根据这本书,似乎是可能的: http://chimera.labs.oreilly.com/books/1230000000545/ch16.html
但我找不到任何使用gzip压缩的SSE示例。我尝试发送带有响应头字段 Content-Encoding设置为"gzip"的压缩消息,但没有成功。
为了测试SSE,我正在使用Python编写的小型Web应用程序进行实验,使用瓶装框架+bottle WSGI服务器。
@bottle.get('/data_stream')
def stream_data():
bottle.response.content_type = "text/event-stream"
bottle.response.add_header("Connection", "keep-alive")
bottle.response.add_header("Cache-Control", "no-cache")
bottle.response.add_header("Content-Encoding", "gzip")
while True:
# new_data is a gevent AsyncResult object,
# .get() just returns a data string when new
# data is available
data = new_data.get()
yield zlib.compress("data: %s\n\n" % data)
#yield "data: %s\n\n" % data
没有压缩的代码(最后一行已注释)而且没有gzip content-encoding头字段,工作得非常好。
编辑:感谢回复和这个问题:Python: Creating a streaming gzip'd file-like?,我成功解决了问题:
@bottle.route("/stream")
def stream_data():
compressed_stream = zlib.compressobj()
bottle.response.content_type = "text/event-stream"
bottle.response.add_header("Connection", "keep-alive")
bottle.response.add_header("Cache-Control", "no-cache, must-revalidate")
bottle.response.add_header("Content-Encoding", "deflate")
bottle.response.add_header("Transfer-Encoding", "chunked")
while True:
data = new_data.get()
yield compressed_stream.compress("data: %s\n\n" % data)
yield compressed_stream.flush(zlib.Z_SYNC_FLUSH)