From 8da012772935d9174be56451d2d6d37bbdb6bedb Mon Sep 17 00:00:00 2001 From: zy7y <13271962515@163.com> Date: Sat, 17 Sep 2022 01:11:21 +0800 Subject: [PATCH] feat: webscoket --- backend/controller/ws.py | 14 ++++++++++++++ backend/core/utils.py | 16 ++++++++++++++++ backend/main.py | 3 +++ backend/mini.db-shm | Bin 0 -> 32768 bytes backend/mini.db-wal | 0 5 files changed, 33 insertions(+) create mode 100644 backend/controller/ws.py create mode 100644 backend/mini.db-shm create mode 100644 backend/mini.db-wal diff --git a/backend/controller/ws.py b/backend/controller/ws.py new file mode 100644 index 0000000..07c5aae --- /dev/null +++ b/backend/controller/ws.py @@ -0,0 +1,14 @@ +from fastapi import FastAPI +from fastapi.websockets import WebSocket + +from core.utils import get_system_info + +# websocket app +ws_app = FastAPI() + + +@ws_app.websocket("/ws") +async def ws_func(ws: WebSocket): + await ws.accept() + while True: + await ws.send_json(get_system_info()) diff --git a/backend/core/utils.py b/backend/core/utils.py index 697c282..b774c1f 100644 --- a/backend/core/utils.py +++ b/backend/core/utils.py @@ -1,3 +1,7 @@ +import random +import time + + def list_to_tree( menus, parent_flag: str = "pid", children_key: str = "children" ) -> list: @@ -24,3 +28,15 @@ def list_to_tree( else: arr.append(menu) return arr + + +def get_system_info(): + """获取系统信息""" + time.sleep(1) + return { + "usage": { + "cpu": f"{random.random() * 100: .2}", + "memory": f"{random.random() * 100: .2}", + "disk": f"{random.random() * 100: .2}", + } + } diff --git a/backend/main.py b/backend/main.py index 889a69d..6fd9d01 100644 --- a/backend/main.py +++ b/backend/main.py @@ -1,5 +1,6 @@ from fastapi import FastAPI +from controller.ws import ws_app from core.events import close_orm, init_orm from core.exceptions import exception_handlers from core.log import logger @@ -14,6 +15,8 @@ app = FastAPI( exception_handlers=exception_handlers, ) +app.mount("/", ws_app) + if __name__ == "__main__": import uvicorn diff --git a/backend/mini.db-shm b/backend/mini.db-shm new file mode 100644 index 0000000000000000000000000000000000000000..fe9ac2845eca6fe6da8a63cd096d9cf9e24ece10 GIT binary patch literal 32768 zcmeIuAr62r3