我想知道是否可以启用gzip压缩
对于服务器发送的事件(SSE;内容类型:文本/事件流).
但是我找不到任何带有gzip压缩的SSE的例子.我试过了
使用响应头字段发送gzipped消息
Content-Encoding设置为“gzip”但没有成功.
为了试验SSE,我正在测试一个小型的Web应用程序
用Python框架gevent制作的Python;我正在跑步
瓶子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
内容编码标题字段就像一个魅力.
@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)