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

Fix database

This commit is contained in:
MoonTestUse1
2025-01-07 06:46:37 +06:00
parent ee0217cfbb
commit 21e4194909
10 changed files with 53 additions and 401 deletions

View File

@@ -5,10 +5,10 @@ from typing import Generator
from .core.config import settings
# Создаем базовый класс для моделей
# Create base class for models
Base = declarative_base()
# Создаем движок базы данных
# Create database engine
engine = create_engine(
settings.get_database_url(),
pool_pre_ping=True,
@@ -16,7 +16,7 @@ engine = create_engine(
max_overflow=10
)
# Создаем фабрику сессий
# Create session factory
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db() -> Generator:
@@ -27,8 +27,8 @@ def get_db() -> Generator:
finally:
db.close()
def init_db():
def init_db() -> None:
"""Initialize database"""
# Импортируем модели здесь, чтобы избежать циклических зависимостей
# Import models here to avoid circular imports
from .db.base import Base # noqa: F811
Base.metadata.create_all(bind=engine)

View File

@@ -4,5 +4,5 @@ from app.models.employee import Employee # noqa
from app.models.request import Request # noqa
from app.models.token import Token # noqa
# Импортируем все модели, чтобы Alembic мог их обнаружить
# Import all models for Alembic autogenerate support
__all__ = ["Base", "Employee", "Request", "Token"]

View File

@@ -1,17 +1,17 @@
"""Dependencies module"""
from typing import Generator, Any
from typing import Generator, Annotated
from sqlalchemy.orm import Session
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from .database import SessionLocal
from .core.config import settings
from .utils.jwt import verify_token, verify_token_in_db
from .utils.jwt import verify_token_in_db
from .models.employee import Employee
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/auth/login")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_STR}/auth/login")
def get_db() -> Generator[Session, Any, None]:
def get_db() -> Generator[Session, None, None]:
"""Get database session"""
db = SessionLocal()
try:
@@ -20,8 +20,8 @@ def get_db() -> Generator[Session, Any, None]:
db.close()
async def get_current_employee(
db: Session = Depends(get_db),
token: str = Depends(oauth2_scheme)
db: Annotated[Session, Depends(get_db)],
token: Annotated[str, Depends(oauth2_scheme)]
) -> Employee:
"""Get current employee"""
credentials_exception = HTTPException(
@@ -30,12 +30,12 @@ async def get_current_employee(
headers={"WWW-Authenticate": "Bearer"},
)
# Проверяем токен
# Verify token
token_data = verify_token_in_db(token, db)
if not token_data:
raise credentials_exception
# Получаем сотрудника
# Get employee
employee = db.query(Employee).filter(Employee.id == token_data.employee_id).first()
if not employee:
raise credentials_exception
@@ -43,7 +43,7 @@ async def get_current_employee(
return employee
async def get_current_active_employee(
current_employee: Employee = Depends(get_current_employee),
current_employee: Annotated[Employee, Depends(get_current_employee)]
) -> Employee:
"""Get current active employee"""
if not current_employee.is_active:
@@ -54,7 +54,7 @@ async def get_current_active_employee(
return current_employee
async def get_current_admin(
current_employee: Employee = Depends(get_current_employee),
current_employee: Annotated[Employee, Depends(get_current_employee)]
) -> Employee:
"""Get current admin"""
if not current_employee.is_admin:

View File

@@ -21,6 +21,12 @@ app.add_middleware(
allow_headers=["*"],
)
# Health check endpoint
@app.get("/api/health")
async def health_check():
"""Health check endpoint"""
return {"status": "ok"}
# Подключаем роутеры
app.include_router(auth.router, prefix=settings.API_V1_STR, tags=["auth"])
app.include_router(employees.router, prefix=settings.API_V1_STR, tags=["employees"])