python gzip压缩后传给前端_python – 是否可以将gzip压缩与服务器发送事件(SSE)一起使用?...

本文介绍了尝试在Python的gevent框架下启用gzip压缩进行服务器发送事件(SSE)的尝试。作者遇到问题,即设置Content-Encoding为"gzip"并未成功。文中展示了未压缩和压缩的代码示例,并讨论了可能的解决方案,包括使用zlib库进行压缩和设置"deflate"编码。实验中还涉及到了bottle框架和chunked传输编码。
摘要由CSDN通过智能技术生成

我想知道是否可以启用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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值