在 python 中读取 SSE 数据

Reading SSE data in python

我有一个 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='')

上面的代码非常适合我。但它会为每个角色进行迭代。我想知道有什么方法可以在每次迭代时打印每个数据部分。

你可以使用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)