首页 > 解决方案 > SSEClient 无法使用 SSE 协议检索长流

问题描述

我正在尝试使用 Python 从服务器使用 SSE(服务器发送事件)流。为此,我正在尝试使用sseclientpackage.json 。

pip install sseclient安装版本 0.0.27。

现在程序:

from sseclient import SSEClient
import json

url - # URL
token = # token

headers = {}
headers['Accept'] = 'text/event-stream'
headers['Authorization'] = 'Bearer ' + token

messages = SSEClient(url, headers=headers)

for message in messages:
    node = json.loads(message.data)
    # process the node

当我消费一个短流(只有几条消息)时,效果很好。

但是当我使用一个包含几千条消息的流时,它会中断:

Traceback (most recent call last):
  File "/Users/romanpuchkovskiy/scripts/./search.py", line 67, in <module>
    node = json.loads(message.data)
  File "/usr/local/Cellar/python@3.9/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python@3.9/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python@3.9/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 411 (char 410)

好吧,实际上是进一步的处理中断了,但这意味着sseclient破坏了数据(因此以后不能将其解析为JSON)。我使用相同的请求检查了带有 CURL 的流,并且响应正常。它也可以被用 Java 编写的客户端成功使用(使用WebClientfrom spring-webflux)。

可能是什么原因?

标签: pythonserver-sent-events

解决方案


原来有一个错误sseclienthttps ://github.com/btubbs/sseclient/issues/28

它仍然是开放的,但是有一个 PR 解决了这个问题https://github.com/btubbs/sseclient/pull/35

它还没有合并。sseclient.py我在这里修补了https://raw.githubusercontent.com/mutantmonkey/sseclient/disable_short_reads_when_chunked/sseclient.py,将它放在我的脚本所在的同一目录中,现在一切正常。


推荐阅读