python - 通过 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)
客户端实现无关紧要。
解决方案
我使用 Socket 将数据从脚本传输到服务器,使用 WebSocket 将数据从服务器传输到客户端。
推荐阅读
- javascript - 反应:道具对象是自动传递给子组件还是总是存在一些默认道具?
- vb.net - 如何将字符串变量作为类型参数参数传递,例如 VB.NET 中的 List(Of T)
- node.js - 如何在 Joi.errors() 中获取模式中其他 ref 的值?
- python - 程序在 while 循环的一帧后关闭
- php - 在特定子数组中仅保留前 10 条记录
- r - R - 如何扩展列表中的每个项目以包括最早日期和今天之间的所有天
- javascript - 实时聊天用户的 JQuery UI 对话框
- r - 在多列上合并数据框
- c++ - 带有约束的可变参数模板的“需要”表达式的语法是什么?
- html - CSS中的“显示更多/更少”有问题