[英]How to stream data with Cherrypy
The following code should send 4 lines of text to the browser, 1 line per second. 以下代码应向浏览器发送4行文本,每秒1行。
Instead the browser (I tried with Chrome and IE) waits 4 seconds and shows the 4 lines at the same time. 相反,浏览器(我尝试使用Chrome和IE)等待4秒,同时显示4行。 The snippet shows two lines setting the header.
该代码段显示了两行设置标题。 I tried with both, but neither works.
我试过这两个,但都不起作用。
What am I doing wrong? 我究竟做错了什么?
import cherrypy
import time
class Root:
@cherrypy.expose
def index(self):
cherrypy.response.headers['Content-Type'] = 'text/event-stream' # see http://stackoverflow.com/questions/20837460/firefox-doesnt-restore-server-sent-events-connection
cherrypy.response.headers['Content-Type'] = 'text/plain' # see http://cherrypy.readthedocs.org/en/latest/advanced.html#how-streaming-output-works-with-cherrypy
def streamer():
for i in range(3):
time.sleep(1)
yield '{} {}\n'.format(time.asctime(), i+1)
print(i)
time.sleep(1)
yield '{} Done'.format(time.asctime())
return streamer()
index._cp_config = {'response.stream': True}
cherrypy.quickstart(Root())
You are not doing anything wrong. 你没有做错任何事。 It depends on the browser.
这取决于浏览器。 For this sort of debugging use something like
curl -v
or curl --trace-ascii -
. 对于这种调试,使用像
curl -v
或curl --trace-ascii -
。 It shows each line arriving with a timeout as you expect. 它显示每条线路按预期超时到达。 Should also work with firefox.
也应该与firefox一起工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.