Reading SSE data in python

谁说我不能喝 提交于 2019-12-12 03:23:50

问题


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.

...

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.


回答1:


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)


来源:https://stackoverflow.com/questions/33022039/reading-sse-data-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!