通过Socket推送实时更新



我需要将python脚本中的实时数据传递到我的服务器(使用FastApi制作(,并从该服务器将所有数据传递到客户端(使用Angular制作(。

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

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

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

我分享我的伪代码:

script.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)

myserver.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)

客户端实现无关紧要。

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

最新更新