【发布时间】:2019-01-18 01:55:22
【问题描述】:
你好,stackoverflow 社区
我正在烧瓶中执行一个函数,该函数通过发布请求更新变量,然后处理该变量并将其显示到网站中,就像那些体育比分网站所做的那样。
网站按预期工作,但我计划有一些用户,我认为一旦变量 var_g 发生变化,它会比网站更新要好得多,而不是像现在那样每 2 秒执行一次,这将是令人难以置信的所有用户同时获得更新,希望你们能帮助我
任何建议都会很有帮助,我没有太多经验,也许我做错了。
烧瓶侧
from flask import Flask, jsonify, render_template, request
# Global variable to keep everything updated
var_g = 0
app = Flask(__name__)
# Getting the post resquest
@app.route('/read', methods=['GET', 'POST'])
def read():
if request.method == 'POST':
# Getting the data to update from headers of post request
info = int(request.headers.get('info'))
# Trying to keep the changes with a global variable
global var_g
var_g = info
print(var_g)
# Procesing data
if var_g == 0:
color = "No color"
elif ( var_g > 0 and var_g < 100 ):
color = "red"
elif ( var_g >= 100 ):
color = "blue"
else:
color = "Unknow"
print(color)
return jsonify(color = color)
# Index
@app.route('/', methods=['GET'])
def index():
if request.method == 'GET':
return render_template('index.html')
HTML端
<html>
<head>
<title> State of colors </title>
</head>
<body>
<p> The color state is </p>
<!--Conecting the results from function /read -->
<p> <span id=results> --- </span> </p>
<!-- json jquery - AJAX -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type=text/javascript>
function colors() {
$.getJSON('/read',
// Getting the updated color
function(data) {
// conecting results to jsonify
$("#results").text(data.color);
});
// Updating every 2 secons
setTimeout(function() {
colors();
}, 2000);
}
// Starting on load
window.onload = colors;
</script>
</body>
</html>
【问题讨论】:
-
对您所描述的内容使用 websockets
-
我正在使用Flask socket.io 执行此类任务。它使用起来超级简单,甚至比 AJAX 还要简单。
-
非常感谢 charlietfl 和 @Roman,我将更深入地了解 socket.io
标签: javascript ajax asynchronous flask