gpt4 book ai didi

javascript - 仅当 flask 中的变量发生变化时才更新网站

转载 作者:行者123 更新时间:2023-11-30 06:23:30 25 4
gpt4 key购买 nike

你好,stackoverflow 社区

我在 flask 中做了一个函数,它通过 post 请求更新一个变量,然后处理这个变量并将其显示到一个网站上,就像那些体育实时比分网站所做的那样。

该网站按预期工作,但我计划有一些用户,我认为一旦变量 var_g 发生变化,这将比网站更新要好得多,而不是像现在那样每 2 秒执行一次,这将是令人难以置信的所有用户同时获得更新,希望大家能帮帮我

任何建议都会很有帮助,我没有太多经验,也许我做错了。

flask 侧面

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>

最佳答案

正如@charlietfl 所说,您需要使用 WebSocket服务器发送状态更新通知。不幸的是,flask 并不是最好的选择,因为它通常需要一个线程来满足每个请求的经典方法。每个 websocket 连接都是一种长时间运行的请求,因此在使用 flask 建立一定数量的连接后,您可能会用完线程(worker)。一种可能的克服方法是从 flask 作为框架切换到 asyncio .有个不错的aiohttp库已经支持开箱即用的 HTTP 和 websockets 服务器。

这是一个简单的例子,代码可能看起来像这样(虽然没有运行它,可能需要一些调整):

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()

关于javascript - 仅当 flask 中的变量发生变化时才更新网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51786689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com