mirror of
https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git
synced 2025-08-14 00:25:46 +02:00
add websockets suppor95
This commit is contained in:
18
backend/.env
18
backend/.env
@@ -1,3 +1,15 @@
|
||||
DATABASE_URL=postgresql://postgres:postgres123@postgres/support_db
|
||||
TELEGRAM_BOT_TOKEN=7677506032:AAHduD5EePz3bE23DKlo35KoOp2_9lZuS34
|
||||
TELEGRAM_CHAT_ID=5057752127
|
||||
# Database settings
|
||||
POSTGRES_USER=postgres
|
||||
POSTGRES_PASSWORD=postgres
|
||||
POSTGRES_DB=support
|
||||
POSTGRES_HOST=support-db
|
||||
POSTGRES_PORT=5432
|
||||
|
||||
# JWT settings
|
||||
JWT_SECRET=your-secret-key
|
||||
JWT_ALGORITHM=HS256
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=1440 # 24 hours
|
||||
|
||||
# Telegram settings (optional)
|
||||
TELEGRAM_BOT_TOKEN=
|
||||
TELEGRAM_CHAT_ID=
|
@@ -1,17 +1,34 @@
|
||||
"""Application configuration module"""
|
||||
"""Application configuration"""
|
||||
from pydantic_settings import BaseSettings
|
||||
from pydantic import Field
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""Application settings"""
|
||||
database_url: str = Field(..., alias="DATABASE_URL")
|
||||
bot_token: str = Field(..., alias="TELEGRAM_BOT_TOKEN")
|
||||
chat_id: str = Field(..., alias="TELEGRAM_CHAT_ID")
|
||||
# Database settings
|
||||
POSTGRES_USER: str
|
||||
POSTGRES_PASSWORD: str
|
||||
POSTGRES_DB: str
|
||||
POSTGRES_HOST: str
|
||||
POSTGRES_PORT: str
|
||||
|
||||
@property
|
||||
def DATABASE_URL(self) -> str:
|
||||
"""Get database URL"""
|
||||
return f"postgresql://{self.POSTGRES_USER}:{self.POSTGRES_PASSWORD}@{self.POSTGRES_HOST}:{self.POSTGRES_PORT}/{self.POSTGRES_DB}"
|
||||
|
||||
# JWT settings
|
||||
JWT_SECRET: str
|
||||
JWT_ALGORITHM: str = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 # 24 hours
|
||||
|
||||
# Telegram settings
|
||||
TELEGRAM_BOT_TOKEN: Optional[str] = None
|
||||
TELEGRAM_CHAT_ID: Optional[str] = None
|
||||
|
||||
class Config:
|
||||
"""Pydantic config"""
|
||||
env_file = ".env"
|
||||
env_file_encoding = "utf-8"
|
||||
case_sensitive = True
|
||||
extra = "ignore"
|
||||
|
||||
|
||||
settings = Settings()
|
@@ -7,14 +7,19 @@ from .config import settings
|
||||
# Создаем URL для подключения к базе данных
|
||||
SQLALCHEMY_DATABASE_URL = settings.DATABASE_URL
|
||||
|
||||
# Создаем движок SQLAlchemy
|
||||
engine = create_engine(SQLALCHEMY_DATABASE_URL)
|
||||
# Создаем движок SQLAlchemy с логированием SQL-запросов
|
||||
engine = create_engine(
|
||||
SQLALCHEMY_DATABASE_URL,
|
||||
echo=True, # Включаем логирование SQL-запросов
|
||||
pool_pre_ping=True # Проверяем соединение перед использованием
|
||||
)
|
||||
|
||||
# Создаем фабрику сессий
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# Функция для получения сессии базы данных
|
||||
def get_db():
|
||||
"""Get database session"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
|
@@ -1,15 +1,24 @@
|
||||
"""Main FastAPI application"""
|
||||
import logging
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from .db.base_class import Base
|
||||
from .db.base import Base
|
||||
from .database import engine
|
||||
from .routers import auth, requests, employees
|
||||
from .websockets.notifications import notification_manager
|
||||
|
||||
# Настраиваем логирование
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Создаем таблицы в базе данных
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
app = FastAPI(title="Support API")
|
||||
app = FastAPI(
|
||||
title="Support API",
|
||||
description="API для системы поддержки IT-отдела",
|
||||
version="1.0.0"
|
||||
)
|
||||
|
||||
# Настраиваем CORS
|
||||
app.add_middleware(
|
||||
@@ -27,4 +36,15 @@ app.include_router(employees.router, prefix="/api/employees", tags=["employees"]
|
||||
|
||||
# Добавляем WebSocket маршруты
|
||||
app.websocket("/api/ws/admin")(notification_manager.admin_endpoint)
|
||||
app.websocket("/api/ws/employee/{employee_id}")(notification_manager.employee_endpoint)
|
||||
app.websocket("/api/ws/employee/{employee_id}")(notification_manager.employee_endpoint)
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup_event():
|
||||
"""Действия при запуске приложения"""
|
||||
logger.info("Starting up application...")
|
||||
# Здесь можно добавить дополнительную инициализацию
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def shutdown_event():
|
||||
"""Действия при остановке приложения"""
|
||||
logger.info("Shutting down application...")
|
Reference in New Issue
Block a user