在python中读取SSE数据

时间:2015-10-08 17:11:53

标签: python server-sent-events

我有一个SSE服务器(例如:http://www.howopensource.com/2014/12/introduction-to-server-sent-events/),它发送输出如下所示。每个数据部分用两个新行分隔(\ n \ n)。我想写下一个简单的python程序来连续显示SSE输出。

...

id: 5
data: Got ID: 5 and the data will be like this.

id: 6
data: Got ID: 6 and the data will be like this.

id: 7
data: Got ID: 7 and the data will be like this.

...

我尝试了以下python代码。

from __future__ import print_function
import httplib

conn = httplib.HTTPConnection("localhost")
conn.request("GET", "/sse.php")
response = conn.getresponse()

while True:
    data = response.read(1)
    print(data, end='')

以上代码对我来说非常合适。但它会对每个角色进行迭代。我想知道每次迭代都有任何方法可以打印每个数据部分。

1 个答案:

答案 0 :(得分:1)

您可以使用response.fp.readline逐行读取数据

from __future__ import print_function
import httplib
conn = httplib.HTTPConnection("localhost")
conn.request("GET", "/sse.php")
response = conn.getresponse()

while True:
    data = response.fp.readline()
    print(data)