您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

定期更新和渲染Flask中的值

定期更新和渲染Flask中的值

使用Ajax请求

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

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+" %")
                });
        }

使用Websockets

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

# -*- 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

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

#!/bin/sh

gunicorn -k flask_sockets.worker app:app

请注意,我没有使用socket.io之类的东西,这就是代码很长的原因。此代码还尝试定期重新连接到服务器,并且可以停止尝试通过用户操作重新连接。我使用Messenger库来通知用户出现问题。当然,这比使用socket.io要复杂一些,但是我非常喜欢对客户端进行编码。

Python 2022/1/1 18:22:02 有541人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶