首页 > 解决方案 > 通过 Socket 推送实时更新

问题描述

我需要将实时数据从 python 脚本传递到我的服务器(使用 FastApi 制作),并且我需要从该服务器将它们全部传递给客户端(使用 Angular 制作)。

目前我正在从我的脚本中执行 Http PUT 请求,然后我正在使用 Websocket 将更新传递给客户端。

问题是每当我的服务器套接字连接时,我都无法从我的脚本接收任何 http 请求。

如果这个解决方案不可行,其他的可能是什么?为什么?

我分享我的虚拟代码:

脚本.py

import requests
import time

if __name__ == "__main__":
    while True:
        headers = {"Content-Type": "application/json"}
        url = "http://localhost:8000/dummy"
        requests.put(url, data={"dummy": "OK"}, headers=headers)
        
        time.sleep(1)

我的服务器.py

from queue import Queue
from fastapi import FastAPI, WebSocket
from starlette.middleware.cors import CORSMiddleware
import uvicorn

queue = Queue()
app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], expose_headers=["*"])


@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()

    while True:
        msg = queue.get()
        await websocket.send_json(data=msg)


@app.put("/dummy")
async def update(dummy):
    queue.put(dummy)

if __name__ == "__main__":
  uvicorn.run("myserver:app", host='0.0.0.0', port=8000)

客户端实现无关紧要。

标签: pythonsocketswebsocketfastapi

解决方案


我使用 Socket 将数据从脚本传输到服务器,使用 WebSocket 将数据从服务器传输到客户端。


推荐阅读