javascript - 使用 python 和 Flask 进行有趣的时钟流文本

标签 javascript python flask streaming

请帮忙。使用 python 和 Flask 制作一个简单的文本时钟应用程序需要什么代码来演示如何 flask streaming作品?理想情况下,应用程序将显示文本时间,并在屏幕上覆盖每秒一次的更新流。

时钟流是实时文本流的简化情况。真正的潜在需求是服务器推出同步视频和文本流(无音频),例如 Miguel Grinberg's Video Streaming with Flask并在客户端屏幕上显示这两个更新。 Miguel 的视频流演示作品。但是我还不知道如何让同步文本流工作。

我尝试了下面的代码,但有一些怪癖:

  1. html p 元素只是文本的占位符。它可以更改为任何可能效果更好的内容。
  2. http://localhost:5000当我希望它显示/time_feed 的时间字符串内容时显示“/time_feed”。
  3. http://localhost:5000/time_feed当 Flask 服务器运行时,什么也不显示。当 Flask 服务器突然停止时,浏览器中会出现一堆更新,例如:

    2018.11.01|20:29:272018.11.01|20:29:282018.11.01|20:29:292018.11.01|20:29:302018.11.01|20:29:312018.11.01|20:29 :322018.11.01|20:29:33

我试过Streaming data with Python and Flask但不明白如何将 javascript 或 jinga 答案应用于我的时钟代码。我是新学习网络和 flask 开发。

应用程序.py:

#!python3 Flask 
# streaming clock per http://flask.pocoo.org/docs/1.0/patterns/streaming

from flask import Flask, Response, render_template, url_for
from datetime import datetime
import time

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/time_feed')
def time_feed():
    def generate():
        while True:
            yield datetime.now().strftime("%Y.%m.%d|%H:%M:%S")
            time.sleep(1)
    return Response(generate(), mimetype='text')

if __name__ == '__main__':
    app.run(debug=True, threaded=True)

./templates/index.html:

<title>Clock</title>
<h1>Clock</h1>
<p>{{ url_for('time_feed') }}</p>

最佳答案

在该示例中,您可以避免 whilesleep:

@app.route('/time_feed')
def time_feed():
    def generate():
        yield datetime.now().strftime("%Y.%m.%d|%H:%M:%S")  # return also will work
    return Response(generate(), mimetype='text') 

在模板中:

<p id="clock">Here will be date|time</p>

<script>
    var clock = document.getElementById("clock");

    setInterval(() => {
        fetch("{{ url_for('time_feed') }}")
        .then(response => {
                response.text().then(t => {clock.innerHTML = t})
            });
        }, 1000);  
</script>

在您的视频流示例中,这只是一个技巧,它不是真正视频流的解决方案,只是因为不提供音频。如果您需要真正的视频流,您需要使用 webRTC以 Kurento-media-server 为例。 对于 python,请查看 aiortc库。

关于javascript - 使用 python 和 Flask 进行有趣的时钟流文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53111362/

相关文章:

python - 移动 dask 数据框中的所有行

javascript - 单击链接时Rails 5空白页

javascript - 使用 servlet 响应中的 javascript 显示图像

python - 如果 "env"参数包含 unicode 对象,为什么 Popen 在 Windows 上会失败?

python - 在Python中循环运行多个数据帧的回归

Javascript 函数不适用于 html5 + Flask

javascript - JQGrid 空网格,没有导航或编辑图标

javascript - addEventListener 到 AngularJS 中的简单指令示例

python wtf AttributeError : 'ObjectIdField' object has no attribute 'help_text'

python - Flask peewee 无法在网络服务器上工作