python - SSEClient 无法使用 SSE 协议检索长流
问题描述
我正在尝试使用 Python 从服务器使用 SSE(服务器发送事件)流。为此,我正在尝试使用sseclient
package.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 编写的客户端成功使用(使用WebClient
from spring-webflux
)。
可能是什么原因?
解决方案
原来有一个错误sseclient
:https ://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,将它放在我的脚本所在的同一目录中,现在一切正常。
推荐阅读
- c - 如何将用逗号分隔的浮点值字符串存储到浮点数组中?
- java - 当我单击 android studio 中的抽屉选项时,没有任何反应
- flutter - 使用 BottomNavigationBar 后“body”不可见:BottomAppBar
- c# - 不能做迁移
- java - 我如何滥用 Java 的 MappedByteBuffer
- xaml - XAML DataTrigger 未更新
- node.js - LernaJS TypeScript Monorepo 问题从包中导出文件
- c++ - 如何让一个类的向量从其他两个类的向量中推回数据?
- javascript - 更新打字稿对象
- python - 如何删除成束的重复元素但保留一个