python - 是否可以将 gzip 压缩与服务器发送事件 (SSE) 一起使用?

标签 python html gzip bottle server-sent-events

我想知道是否可以启用 gzip 压缩 用于服务器发送的事件(SSE;内容类型:文本/事件流)。

根据这本书,这似乎是可能的: http://chimera.labs.oreilly.com/books/1230000000545/ch16.html

但我找不到任何使用 gzip 压缩的 SSE 示例。我尝试过了 发送带有响应 header 字段的压缩消息 Content-Encoding 设置为“gzip”但没有成功。

为了围绕 SSE 进行试验,我正在测试一个小型网络应用程序 用 Python 和 bottle framework + gevent 制作;我只是在运行 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 内容编码 header 字段就像一个魅力。

编辑:感谢回复和另一个问题: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)

最佳答案

TL;DR:如果请求未被缓存,您可能希望使用 zlib 并将 Content-Encoding 声明为“deflate”。仅此一项更改就可以使您的代码正常工作。


如果声明Content-Encoding为gzip,则需要实际使用gzip。它们基于相同的压缩算法,但 gzip 有一些额外的框架。这有效,例如:

import gzip
import StringIO
from bottle import response, route
@route('/')
def get_data():
    response.add_header("Content-Encoding", "gzip")
    s = StringIO.StringIO()
    with gzip.GzipFile(fileobj=s, mode='w') as f:
        f.write('Hello World')
    return s.getvalue()

不过,只有当您使用实际文件作为缓存时,这才真正有意义。

关于python - 是否可以将 gzip 压缩与服务器发送事件 (SSE) 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23769001/

相关文章:

c# - 在 C# 中解压字节数组

python - 如何按日期列表过滤日期和时间的数据框?

python - 测试 numpy 数组中的行是否与给定行相同或每个元素不同

python - 计算文件中的特定字符(Python)

iOS : Blocked a frame with origin "https://www.youtube.com" from accessing a frame with origin

json - gzip json 与高效二进制序列化的性能

python - 测试 IRC 机器人

javascript - jQuery + 安卓。将功能(Touchstart、touchmove)应用于实时加载的内容

javascript - 将 bootstrap 主题安装到 Rails 4 应用程序中 - javascript 文件问题

java - 使用 Apache Commons Compress 的压缩级别