python - 使用webpy流式传输连续数据

标签 python web.py

我想使用 pythonweb.py 将连续传感器数据流式传输到小型 Web 套接字。但我无法更新数据。

最小工作示例如下所示:

#!/usr/bin/env python
import web
from time import sleep

# 1. Data part, create some csv-string
streamString = "x,y\n"
streamString = streamString + "123,123\n"

# 2. webpy part, create a minimum server
urls = ('/', 'index')
class index:
    def GET(self):
        return streamString

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()
    # simulate some sensor data that is read continuously
    i = 0 
    while True:
        newString = "{0},{1}\n".format(i, i+1)
        i = i + 2
        streamString = streamString + newString
        sleep(1)

这将创建显示第一个条目 (x,y\n123,123\n) 的应用程序,但它无法显示“实时”数据(我假设这是 app.run() 出现在循环之前)

知道如何才能完成这项工作吗?

最佳答案

首先,你是对的:你的 while True: 永远不会执行,因为它在 app.run() 之后。

基本策略是使用 yield 使 GET() 成为生成器,而不是返回字符串。例如:

class index:
    def GET(self):
      web.header('Transfer-Encoding', 'chunked')
      yield "Here we go!"
      i = 0
      while True:
          newString = "{0},{1}\n".format(i, i+1)
          i = i + 2
          sleep(1)
          yield newString
  1. 使用传输编码“分块”告诉浏览器并非所有数据都会同时传入。
  2. 仅生成新值(您的示例连接了字符串)。
  3. 因为您使用 yield,所以在 GET() 中,该 GET 返回的所有数据都必须使用 yield(因此我的 yield 'Here we go!' 示例。)

它工作正常,但您的浏览器将缓冲结果:它确实会“永远”以一秒的间隔接收数据,但浏览器不会在每次接收时更新。例如,Chrome 似乎会等到收到初始 1k 数据为止。然后它对浏览器进行第一次写入,然后将在每次新接收时更新窗口(因此它仅缓冲第一位)。

所以,尝试更新的代码并等待。

另请参阅http://webpy.org/cookbook/streaming_large_files

关于python - 使用webpy流式传输连续数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41421464/

相关文章:

python - 输入 [type=file] 返回空值

python - 重复的 SSLEOFError 处理

python - web.py 上的 SSL 证书链不完整

python - 如何在 python 中安排一个 Action ?

python - 在安装 Python 3.4 的同时为 Python 2.7 安装 numpy?

python - 对值递减的列表运行 for 循环

web.py - 获取刚刚插入到 web.py 中的记录

python - 获得 Windows 透明度 wxPython

python - 如何连接两个QTableview小部件?

python - 尝试运行 webpy 示例 : app isn't defined