Javascript 仅当网络中的变量发生变化时更新网站
你好,这里是我们的社区 我在flask中执行一个函数,通过post请求更新变量,然后处理该变量并将其显示到网站中,就像那些sports livescore网站一样 该网站按预期运行,但我计划有一些用户,我认为一旦变量变量改变,它将比网站更新要好得多,而不是像现在这样每2秒更新一次,并且难以置信的是,所有用户同时获得更新,希望你们能帮我 任何建议都会很有帮助,我没有太多的经验,也许我做错了每件事 烧瓶侧Javascript 仅当网络中的变量发生变化时更新网站,javascript,ajax,asynchronous,flask,Javascript,Ajax,Asynchronous,Flask,你好,这里是我们的社区 我在flask中执行一个函数,通过post请求更新变量,然后处理该变量并将其显示到网站中,就像那些sports livescore网站一样 该网站按预期运行,但我计划有一些用户,我认为一旦变量变量改变,它将比网站更新要好得多,而不是像现在这样每2秒更新一次,并且难以置信的是,所有用户同时获得更新,希望你们能帮我 任何建议都会很有帮助,我没有太多的经验,也许我做错了每件事 烧瓶侧 from flask import Flask, jsonify, render_templa
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')
从flask导入flask,jsonify,呈现模板,请求
#全局变量以保持所有内容的更新
var_g=0
app=烧瓶(名称)
#获取后重新请求
@app.route('/read',方法=['GET',POST'])
def read():
如果request.method==“POST”:
#从post请求的标头获取要更新的数据
info=int(request.headers.get('info'))
#尝试使用全局变量保留更改
全局变量
var_g=info
打印(变量)
#处理数据
如果var_g==0:
color=“无颜色”
elif(var_g>0和var_g<100):
color=“红色”
elif(变量>=100):
color=“蓝色”
其他:
color=“未知”
印刷品(彩色)
返回jsonify(颜色=颜色)
#索引
@app.route('/',方法=['GET'])
def index():
如果request.method==“GET”:
返回渲染模板('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>
色彩状态
颜色状态为
--
函数颜色(){
$.getJSON(“/read”,
//获取更新的颜色
功能(数据){
//将结果合并到jsonify
$(“#结果”).text(data.color);
});
//每2秒更新一次
setTimeout(函数(){
颜色();
}, 2000);
}
//带负荷起动
window.onload=颜色;
正如@charlietfl所说,您需要使用发送服务器到客户端的状态更新通知。不幸的是,flask
then不是最好的选择,因为它通常需要每个请求一个线程。每个websocket连接都是一种长时间运行的请求,因此在使用flask建立了一定数量的连接之后,您可能会耗尽线程(工作线程)。一种可能的克服方法是将flask作为您的框架切换到。已经有一个很好的库支持HTTP和websockets服务器的开箱即用
下面是一个快速示例,说明代码当时的样子(虽然没有运行,但可能需要进行一些调整):
导入异步IO
导入aiohttp.web
您的_状态_here={'counter':0}
活动_客户端=[]
异步定义索引(请求):
返回aiohttp.web.Response(文本=“”)
异步def do_更新(请求):
#你的逻辑在这里
你的状态在这里['counter']+=1
对于活动_客户端中的ws:
ws.send_str('更新了%s'%1!''您的_状态\u此处['counter']))
返回aiohttp.web.Response(text='Ok')
异步def on_状态_更新(请求):
ws=aiohttp.web.WebSocketResponse()
等待ws.prepare(请求)
活动\u客户端。附加(ws)
ws中消息的异步:
如果msg.type==aiohttp.WSMsgType.TEXT:
如果msg.data==“关闭”:
活动客户端。删除(ws)
等待ws.close()
返回ws
def main():
loop=asyncio.get\u event\u loop()
app=aiohttp.web.Application(loop=loop)
app.router.add_route('GET','/',index)
app.router.add_route('POST','/do_update',do_update)
app.router.add_route('GET','/updates',on_state_update)
aiohttp.web.run\u应用程序(应用程序,端口=3000)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
main()
将WebSocket用于您所描述的内容,我将用于此类任务。它的使用非常简单,甚至比AJAX更简单。非常感谢charlietfl和@Roman,我将更深入地了解socket。ioThanks非常感谢您的时间@IvanVelichko,我肯定会四处看看asyncio和WebSocket。
import asyncio
import aiohttp.web
your_state_here = {'counter': 0}
active_clients = []
async def index(request):
return aiohttp.web.Response(text='<your template here>')
async def do_update(request):
# your logic here
your_state_here['counter'] += 1
for ws in active_clients:
ws.send_str('updated %s' % your_state_here['counter'])
return aiohttp.web.Response(text='Ok')
async def on_state_update(request):
ws = aiohttp.web.WebSocketResponse()
await ws.prepare(request)
active_clients.append(ws)
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
if msg.data == 'close':
active_clients.remove(ws)
await ws.close()
return ws
def main():
loop = asyncio.get_event_loop()
app = aiohttp.web.Application(loop=loop)
app.router.add_route('GET', '/', index)
app.router.add_route('POST', '/do_update', do_update)
app.router.add_route('GET', '/updates', on_state_update)
aiohttp.web.run_app(app, port=3000)
if __name__ == '__main__':
main()