用于读取服务器发送事件流(Server Sent Event)的Python客户端库。
项目描述
这是一个Python客户端库,用于迭代http服务器发送事件(Server Sent Event)流(也称为EventSource,浏览器内部JavaScript接口的名称)。SSEClient类在初始化时接受一个URL,然后是来自服务器的消息迭代器。
安装
使用pip
pip install sseclient
使用方法
from sseclient import SSEClient messages = SSEClient('http://mysite.com/sse_stream/') for msg in messages: do_something_useful(msg)
每个消息对象都将有一个‘data’属性,以及可选的‘event’、‘id’和‘retry’属性。
可选的初始化参数
last_id:如果提供,此参数将被发送到服务器,告诉它只返回ID较新的消息。
retry:断开连接后尝试重新连接前等待的毫秒数。服务器可以通过在消息中包含一个‘retry’行来更改此值。重试由SSEClient对象自动处理。
您还可以提供由Requests库支持的任何其他关键字参数,例如‘headers’字典和用于‘auth’的(用户名,密码)元组。
开发
以可编辑模式安装库
pip install -e .
安装测试依赖项
pip install pytest backports.unittest_mock
使用py.test运行测试
(sseclient)vagrant sseclient $ py.test ===================== test session starts ====================== platform linux2 -- Python 2.7.6 -- py-1.4.30 -- pytest-2.7.2 rootdir: /vagrant/code/sseclient, inifile: plugins: backports.unittest-mock collected 11 items test_sseclient.py ........... ================== 11 passed in 0.19 seconds ===================
代码中有几个TODO项,用于使实现完全符合SSE规范的细微之处。