cit-is-bot-backend/api/main.py

102 строки
2.1 KiB
Python
Исходник Обычный вид История

import asyncio
from fastapi import FastAPI, Body
from fastapi.websockets import WebSocket, WebSocketDisconnect
import config
class ConnectionManager:
connections: list[WebSocket]
class StateError(Exception):
pass
def __init__(
self,
):
self.connections = []
async def connect(
self,
websocket: WebSocket,
):
await websocket.accept()
self.connections.append(websocket)
def disconnect(
self,
websocket: WebSocket,
):
self.connections.remove(websocket)
async def broadcast(
self,
data: any,
):
for connection in self.connections:
asyncio.ensure_future(connection.send_json(data))
api = FastAPI(
title=config.Main.app_name,
)
scripts = [
{
'id': 1,
'name': 'Текущее состояние сотрудников',
'time': '0 11 * * 1-5',
'messageNumber': '1 вопрос',
'isEnabled': True,
},
{
'id': 2,
'name': 'Планы на обед',
'time': '45 11 * * 1-5',
'messageNumber': '2 вопроса',
'isEnabled': False,
},
]
scripts_cm = ConnectionManager()
@api.post(
path='/api/scripts',
)
async def _(
script_id: int = Body(
validation_alias='id',
),
name: str = Body(),
time: str = Body(),
message_number: str = Body(
validation_alias='messageNumber',
),
is_enabled: bool = Body(
validation_alias='isEnabled',
),
):
i = script_id - 1
scripts[i]['name'] = name
scripts[i]['time'] = time
scripts[i]['messageNumber'] = message_number
scripts[i]['isEnabled'] = is_enabled
@api.websocket(
path='/ws/scripts',
)
async def _(
websocket: WebSocket,
):
await scripts_cm.connect(websocket)
try:
await scripts_cm.broadcast(scripts)
while True:
await websocket.receive_json()
except WebSocketDisconnect:
scripts_cm.disconnect(websocket)