Python 定期更新和渲染来自 Flask 的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15721679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:47:03  来源:igfitidea点击:

Update and render a value from Flask periodically

javascriptpythonflaskjinja2

提问by Depado

I want to display my CPU usage dynamically. I don't want to reload the page to see a new value. I know how to get the CPU usage in Python. Right now I render a template with the value. How can I continually update a page with a value from Flask?

我想动态显示我的 CPU 使用率。我不想重新加载页面以查看新值。我知道如何在 Python 中获取 CPU 使用率。现在我用这个值渲染一个模板。如何使用 Flask 中的值不断更新页面?

@app.route('/show_cpu')
def show_cpu():
    cpu = getCpuLoad()
    return render_template('show_cpu.html', cpu=cpu)

采纳答案by Depado

Using an Ajax request

使用 Ajax 请求

Python

Python

@app.route('/_stuff', methods= ['GET'])
def stuff():
    cpu=round(getCpuLoad())
    ram=round(getVmem())
    disk=round(getDisk())
    return jsonify(cpu=cpu, ram=ram, disk=disk)

Javascript

Javascript

function update_values() {
            $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
            $.getJSON($SCRIPT_ROOT+"/_stuff",
                function(data) {
                    $("#cpuload").text(data.cpu+" %")
                    $("#ram").text(data.ram+" %")
                    $("#disk").text(data.disk+" %")
                });
        }

Using Websockets

使用 Websocket

project/app/views/request/websockets.py

project/app/views/request/websockets.py

# -*- coding: utf-8 -*-

# OS Imports
import json

# Local Imports
from app import sockets
from app.functions import get_cpu_load, get_disk_usage, get_vmem

@sockets.route('/_socket_system')
def socket_system(ws):
    """
    Returns the system informations, JSON Format
    CPU, RAM, and Disk Usage
    """
    while True:
        message = ws.receive()
        if message == "update":
            cpu = round(get_cpu_load())
            ram = round(get_vmem())
            disk = round(get_disk_usage())
            ws.send(json.dumps(dict(received=message, cpu=cpu, ram=ram, disk=disk)))
        else:
            ws.send(json.dumps(dict(received=message)))

project/app/__init__.py

project/app/__init__.py

# -*- coding: utf-8 -*-
from flask import Flask
from flask_sockets import Sockets


app = Flask(__name__)
sockets = Sockets(app)
app.config.from_object('config')
from app import views

Using Flask-Websockets made my life a lot easier. Here is the launcher : launchwithsockets.sh

使用 Flask-Websockets 让我的生活更轻松。这是启动器: launchwithsockets.sh

#!/bin/sh

gunicorn -k flask_sockets.worker app:app

Finally, here is the client code :
custom.js
The code is a bit too long, so here it is.
Note that I'm NOT using things like socket.io, that's why the code is long. This code also tries to reconnect to the server periodically, and can stop trying to reconnect on a user action. I use the Messenger lib to notify the user that something went wrong. Of course it's a bit more complicated than using socket.io but I really enjoyed coding the client side.

最后,这里是客户端代码:
custom.js
代码有点长,所以在这里。
请注意,我没有使用 socket.io 之类的东西,这就是代码很长的原因。此代码还尝试定期重新连接到服务器,并且可以停止尝试重新连接用户操作。我使用 Messenger 库通知用户出现问题。当然,它比使用 socket.io 复杂一些,但我真的很喜欢在客户端编写代码。