You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask长轮询API开发问题:实现网页自动同步API端点更新数据

问题描述

我希望实现网页在API端点更新时自动获取并展示最新内容,目前网页仅能通过刷新显示API的最新数据。我编写了一段Flask代码,尝试通过遍历API的next链接找到updates接口以发起长轮询,但将代码放入while循环后无法正常重启运行。本质上,初始API页面可能没有updates链接,因此我必须跟随next链接直到找到update href,再请求该链接来启动长轮询。以下是我的代码:

import json
import requests
from flask import Flask, render_template


app = Flask(__name__)
s = requests.session()

# API Key
s.headers.update({'Authorization': 'apikeygoeshere'})


@app.route("/")
def index():
    alarms = s.get('https://site/api/alarms')
    alarmData = json.loads(alarms.text)

    if next in alarmData:
        while alarmData['next']:
            nextUrl = alarmData['next']['href']
            print(nextUrl)
            nextUrlGet = s.get(nextUrl)
            nextData = json.loads(nextUrlGet.text)
            alarmData = nextData

            if not alarmData['next']:
                break
    else:
            print('No Next -> Update Ready')
            alarmUpdateUrl = alarmData['updates']['href']
            update = s.get(alarmUpdateUrl)
            updateData = json.loads(update.text)

            if not updateData['updates']:
                updateName = "Nothing"

            else:
                updateName = updateData['updates'][0]['source']['name']
                alarmUpdateUrl = updateData['next']['href']
                print(alarmUpdateUrl)
                s.get(alarmUpdateUrl)
                
            return render_template('index.html', data=updateName, url=alarmUpdateUrl)



if __name__ == '__main__':
    app.run(debug=True, threaded=True)

内容的提问来源于stack exchange,提问作者cmrussell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:40:48