1
0
mirror of https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git synced 2025-08-14 00:25:46 +02:00

add websockets suppor3

This commit is contained in:
MoonTestUse1
2025-01-05 01:54:17 +06:00
parent a81310d0e7
commit 65d9eddb53
5 changed files with 75 additions and 14 deletions

View File

@@ -1,8 +1,13 @@
"""Main application module"""
from fastapi import FastAPI
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from . import models
from .routers import admin, employees, requests, auth, statistics
import logging
# Настройка логирования
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI(
# Включаем автоматическое перенаправление со слэшем
@@ -37,4 +42,10 @@ app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
app.include_router(employees.router, prefix="/api/employees", tags=["employees"])
app.include_router(requests.router, prefix="/api/requests", tags=["requests"])
app.include_router(admin.router, prefix="/api/admin", tags=["admin"])
app.include_router(statistics.router, prefix="/api/statistics", tags=["statistics"])
app.include_router(statistics.router, prefix="/api/statistics", tags=["statistics"])
@app.middleware("http")
async def log_requests(request: Request, call_next):
logger.info(f"Request: {request.method} {request.url}")
response = await call_next(request)
return response

View File

@@ -21,21 +21,35 @@ async def websocket_admin_endpoint(websocket: WebSocket):
await notification_manager.connect(websocket, "admin")
try:
while True:
data = await websocket.receive_text()
data = await websocket.receive_json()
logger.info(f"Received message from admin: {data}")
if data.get("type") == "ping":
await notification_manager.handle_ping(websocket)
except WebSocketDisconnect:
logger.info("Admin WebSocket disconnected")
notification_manager.disconnect(websocket, "admin")
except Exception as e:
logger.error(f"Error in admin websocket: {e}")
notification_manager.disconnect(websocket, "admin")
@router.websocket("/ws/employee/{employee_id}")
async def websocket_employee_endpoint(websocket: WebSocket, employee_id: int):
"""WebSocket endpoint для сотрудников"""
logger.info(f"Employee {employee_id} WebSocket connection attempt")
await notification_manager.connect(websocket, "employee")
try:
while True:
data = await websocket.receive_text()
# Здесь можно добавить обработку сообщений от сотрудника
data = await websocket.receive_json()
logger.info(f"Received message from employee {employee_id}: {data}")
if data.get("type") == "ping":
await notification_manager.handle_ping(websocket)
except WebSocketDisconnect:
logger.info(f"Employee {employee_id} WebSocket disconnected")
notification_manager.disconnect(websocket, "employee")
except Exception as e:
logger.error(f"Error in employee websocket: {e}")
notification_manager.disconnect(websocket, "employee")
@router.post("/", response_model=Request)

View File

@@ -2,6 +2,7 @@ from fastapi import WebSocket
from typing import Dict, List
import json
import logging
import asyncio
logger = logging.getLogger(__name__)
@@ -58,4 +59,12 @@ class NotificationManager:
for connection in disconnected:
self.disconnect(connection, "employee")
async def handle_ping(self, websocket: WebSocket):
"""Обработка ping сообщений"""
try:
await websocket.send_json({"type": "pong"})
logger.debug("Sent pong response")
except Exception as e:
logger.error(f"Error sending pong: {e}")
notification_manager = NotificationManager()