我想动态显示我的CPU使用情况。我不想重新加载页面以查看新值。我知道如何在Python中获得CPU使用率。现在我用值渲染一个模板。如何使用Flask中的值不断更新页面?
@app.route('/show_cpu')
def show_cpu():
cpu = getCpuLoad()
return render_template('show_cpu.html', cpu=cpu)
答案 0 :(得分:26)
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+" %")
});
}
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
最后,这是客户代码:
custom.js
The code is a bit too long, so here it is.
请注意,我没有使用socket.io之类的东西,这就是代码很长的原因。此代码还会尝试定期重新连接到服务器,并且可以停止尝试重新连接用户操作。我使用Messenger lib来通知用户出错了。当然,它比使用socket.io更复杂,但我真的很喜欢编写客户端。