如何基于Flask cache或POST请求变更实现页面内容实时更新
解决方案
以下提供两种可直接落地的实现方式,可根据你的业务场景选择:
方案1:前端短轮询(改动最小,快速实现)
适合并发量不高、对实时性要求在秒级的场景,无需额外依赖。
后端修改
- 保留原有webhook逻辑、cache存储、/index路由的核心业务逻辑,新增一个返回最新价格的轻量接口:
@app.route("/get-latest-price", methods=["GET"]) def get_latest_price(): price = cache.get("price_data", default="暂无数据") return {"price": price}
- 调整index页面模板,加入JS自动更新逻辑,无需刷新整个页面即可同步最新价格:
<div> the price of apple is: <span id="price-display"></span><span id="some_other_stuff"></span> </div> <script> // 间隔2秒拉取一次最新数据,可根据业务需求调整时间间隔 setInterval(() => { fetch("/get-latest-price") .then(res => res.json()) .then(data => { document.getElementById("price-display").textContent = data.price; // 其他需要同步更新的业务逻辑可写在这里 }) }, 2000) </script>
方案2:Server-Sent Events(SSE,主动推送,实时性更高)
符合你要求的「webhook触发后主动ping页面更新」的效果,webhook收到新请求后服务端主动推送最新数据给所有打开页面的客户端,实时性可达毫秒级。
依赖安装
pip install flask-sse redis
后端修改
- 初始化SSE配置:
from flask_sse import sse import redis # 按你实际的redis配置调整连接地址 app.config["REDIS_URL"] = "redis://localhost:6379" app.register_blueprint(sse, url_prefix="/stream")
- 修改webhook路由,更新缓存后主动推送更新事件:
@app.route('/webhook', methods = ['POST']) def webhook(): data = json.loads(request.data) item_name = data["item"] price_of_item = get_item_price(df, item_name) cache.set("price_data", price_of_item) # 向所有在线客户端推送价格更新事件 sse.publish({"price": price_of_item}, type="price_update") return data
- 调整index页面模板,监听服务端推送事件自动更新内容:
<div> the price of apple is: <span id="price-display"></span><span id="some_other_stuff"></span> </div> <script> const source = new EventSource("/stream"); source.addEventListener("price_update", (event) => { const data = JSON.parse(event.data); document.getElementById("price-display").textContent = data.price; // 其他需要同步更新的业务逻辑可写在这里 }); </script>
内容的提问来源于stack exchange,提问作者SamAct
相关产品推荐
相关产品推荐

