通过 Socket 推送实时更新
Push live updates through 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 将数据从我的服务器传输到客户端。
我需要将实时数据从 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 将数据从我的服务器传输到客户端。