国际财经实时快讯
正在加载实时快讯...
FastAPI 实时更新脚本 (main.js)
javascript
// 使用 FastAPI 进行实时更新
const fastapiURL = "http://localhost:8000";// 定期从 FastAPI 获取实时快讯
setInterval(() => {fetch(fastapiURL).then((response) => response.json())
.then((data) => {// 更新页面内容const updateContainer = document.getElementById("update-container");updateContainer.innerHTML = data.message;});
}, 1000);FastAPI 应用程序 (app.py)
python
from fastapi import FastAPI, BackgroundTasks
from time import sleepapp = FastAPI()@app.get("/")
async def get_updates():模拟从某个数据源获取实时快讯await BackgroundTasks().add_task(simulate_updates)return {"message": "正在加载实时快讯..."}模拟实时更新
async def simulate_updates():while True:模拟每 2 秒发送一条实时快讯sleep(2)yield {"message": f"实时更新:当前时间为 {time.strftime('%H:%M:%S')}"}