在python中读取SSE数据 [英] Reading SSE data in python
问题描述
我有一个 SSE 服务器(例如:http://www.howopensource.com/2014/12/introduction-to-server-sent-events/) 发送输出如下.每个数据部分用两个新行分隔 (\n\n).我想写一个简单的python程序来连续显示SSE输出.
I have a SSE server(eg: http://www.howopensource.com/2014/12/introduction-to-server-sent-events/) that sends output as given below. Each data section is separated with two new lines(\n\n). I want to write down a simple python program to display the SSE output continuously.
...
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 代码.
I tried following python code.
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='')
上面的代码对我来说很完美.但它对每个字符进行迭代.我想知道有什么方法可以在每次迭代中打印每个数据部分.
The above code works perfectly to me. But it do iteration for each character. I wonder there is any way to print each data-section per iteration.
推荐答案
可以使用response.fp.readline逐行读取数据
you can use response.fp.readline to read data line by line
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)
这篇关于在python中读取SSE数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!