feat(api): migracion completa de Flask API a FastAPI ASGI con arquitectura en 4 capas v3.6.0
This commit is contained in:
@@ -0,0 +1 @@
|
||||
# Routers package initialization
|
||||
@@ -0,0 +1,243 @@
|
||||
"""
|
||||
FastAPI Authentication Router (/api/v1/auth)
|
||||
Implements Hybrid Authentication:
|
||||
- Local Authentication with Admin fallback
|
||||
- Google OAuth 2.0 institutional login
|
||||
- Moodle Delegated Authentication
|
||||
- Impersonation mode for Administrators
|
||||
- Dual Token JWT management with HttpOnly cookies
|
||||
"""
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.models.user import User
|
||||
from app.models.setting import SystemSetting
|
||||
from app.services.user_service import UserService
|
||||
from app.services.jwt_service import JWTService
|
||||
from app.services.moodle_client import moodle_client
|
||||
from app.services.audit_service import AuditService
|
||||
from dependencies import get_current_user, require_roles, get_token_from_request
|
||||
from database import get_flask_app
|
||||
from schemas.auth import (
|
||||
LoginRequest,
|
||||
GoogleAuthRequest,
|
||||
MoodleAuthRequest,
|
||||
ImpersonateRequest,
|
||||
RefreshTokenRequest
|
||||
)
|
||||
|
||||
auth_router = APIRouter(prefix="/api/v1/auth", tags=["Authentication"])
|
||||
user_service = UserService()
|
||||
flask_app = get_flask_app()
|
||||
|
||||
|
||||
@auth_router.get("/providers")
|
||||
def get_auth_providers():
|
||||
"""Retorna los métodos de autenticación habilitados y configuración de cliente Google."""
|
||||
with flask_app.app_context():
|
||||
local_val = str(SystemSetting.get_value('auth_local_enabled', 'true') or 'true').lower() in ('true', '1')
|
||||
google_val = str(SystemSetting.get_value('auth_google_enabled', 'false') or 'false').lower() in ('true', '1')
|
||||
moodle_val = str(SystemSetting.get_value('auth_moodle_enabled', 'false') or 'false').lower() in ('true', '1')
|
||||
google_client_id = str(SystemSetting.get_value('google_client_id', '') or '')
|
||||
demo_access_enabled = str(SystemSetting.get_value('demo_access_enabled', 'true') or 'true').lower() in ('true', '1')
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'providers': {
|
||||
'local': local_val,
|
||||
'google': google_val,
|
||||
'moodle': moodle_val
|
||||
},
|
||||
'google_client_id': google_client_id,
|
||||
'demo_access_enabled': demo_access_enabled
|
||||
}
|
||||
|
||||
|
||||
@auth_router.post("/login")
|
||||
def login(payload: LoginRequest, response: Response):
|
||||
"""Inicio de sesión local nativo (Access + Refresh tokens)."""
|
||||
with flask_app.app_context():
|
||||
local_enabled = str(SystemSetting.get_value('auth_local_enabled', 'true') or 'true').lower() in ('true', '1')
|
||||
|
||||
user = user_service.authenticate(payload.email, payload.password)
|
||||
if not user:
|
||||
AuditService.log(
|
||||
action='LOGIN_FAILED',
|
||||
module='auth',
|
||||
user_email=payload.email,
|
||||
details=f"Intento de inicio de sesión fallido para {payload.email}. Credenciales incorrectas o cuenta inactiva."
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Credenciales de acceso incorrectas o cuenta inactiva."
|
||||
)
|
||||
|
||||
is_admin = user.is_admin() or getattr(user, 'role', '').upper() == 'ADMIN'
|
||||
if not local_enabled and not is_admin:
|
||||
AuditService.log(
|
||||
action='LOGIN_BLOCKED',
|
||||
module='auth',
|
||||
user=user,
|
||||
entity_id=user.id,
|
||||
details=f"Acceso local con contraseña bloqueado para {user.email}. Método deshabilitado por administración."
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="El acceso local con contraseña está deshabilitado por el administrador. Inicie sesión mediante Google OAuth o Moodle."
|
||||
)
|
||||
|
||||
AuditService.log(
|
||||
action='LOGIN',
|
||||
module='auth',
|
||||
user=user,
|
||||
entity_id=user.id,
|
||||
details=f"Inicio de sesión exitoso (Autenticación Local) - Rol: {user.role}"
|
||||
)
|
||||
|
||||
tokens = JWTService.generate_tokens(user)
|
||||
profile = user_service.get_profile_data(user)
|
||||
|
||||
response.set_cookie(
|
||||
key="access_token",
|
||||
value=tokens["access_token"],
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
path="/"
|
||||
)
|
||||
response.set_cookie(
|
||||
key="refresh_token",
|
||||
value=tokens["refresh_token"],
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
max_age=7 * 24 * 3600,
|
||||
path="/api/v1/auth/refresh"
|
||||
)
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'access_token': tokens['access_token'],
|
||||
'refresh_token': tokens['refresh_token'],
|
||||
'token_type': tokens['token_type'],
|
||||
'expires_in': tokens['expires_in'],
|
||||
'user': profile
|
||||
}
|
||||
|
||||
|
||||
@auth_router.post("/google")
|
||||
def google_auth(payload: GoogleAuthRequest, response: Response):
|
||||
"""Inicio de sesión delegado institucional Google OAuth 2.0."""
|
||||
with flask_app.app_context():
|
||||
google_enabled = str(SystemSetting.get_value('auth_google_enabled', 'false') or 'false').lower() in ('true', '1')
|
||||
if not google_enabled:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="El inicio de sesión con Google no está habilitado.")
|
||||
|
||||
email = payload.email.strip().lower()
|
||||
allowed_domains_str = str(SystemSetting.get_value('google_allowed_domains', 'unicaba.edu.ar') or 'unicaba.edu.ar')
|
||||
allowed_domains = [d.strip().lower() for d in allowed_domains_str.split(',') if d.strip()]
|
||||
|
||||
email_domain = email.split('@')[1] if '@' in email else ''
|
||||
if allowed_domains and email_domain not in allowed_domains:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Dominio @{email_domain} no autorizado. Sólo se permiten cuentas institucionales: {allowed_domains_str}."
|
||||
)
|
||||
|
||||
user = user_service.get_or_create_google_user(
|
||||
email=email,
|
||||
name=payload.name or email.split('@')[0],
|
||||
photo=payload.photo
|
||||
)
|
||||
|
||||
tokens = JWTService.generate_tokens(user)
|
||||
profile = user_service.get_profile_data(user)
|
||||
|
||||
response.set_cookie(key="access_token", value=tokens["access_token"], httponly=True, samesite="lax", path="/")
|
||||
return {
|
||||
'status': 'success',
|
||||
'access_token': tokens['access_token'],
|
||||
'refresh_token': tokens['refresh_token'],
|
||||
'token_type': tokens['token_type'],
|
||||
'expires_in': tokens['expires_in'],
|
||||
'user': profile
|
||||
}
|
||||
|
||||
|
||||
@auth_router.post("/moodle")
|
||||
def moodle_auth(payload: MoodleAuthRequest, response: Response):
|
||||
"""Inicio de sesión delegado con Moodle (verificando DNI o credenciales de campus)."""
|
||||
with flask_app.app_context():
|
||||
moodle_enabled = str(SystemSetting.get_value('auth_moodle_enabled', 'false') or 'false').lower() in ('true', '1')
|
||||
if not moodle_enabled:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="El inicio de sesión con Moodle no está habilitado.")
|
||||
|
||||
user = user_service.authenticate_moodle(payload.username, payload.password)
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Credenciales de Moodle inválidas o usuario no sincronizado.")
|
||||
|
||||
tokens = JWTService.generate_tokens(user)
|
||||
profile = user_service.get_profile_data(user)
|
||||
|
||||
response.set_cookie(key="access_token", value=tokens["access_token"], httponly=True, samesite="lax", path="/")
|
||||
return {
|
||||
'status': 'success',
|
||||
'access_token': tokens['access_token'],
|
||||
'refresh_token': tokens['refresh_token'],
|
||||
'token_type': tokens['token_type'],
|
||||
'expires_in': tokens['expires_in'],
|
||||
'user': profile
|
||||
}
|
||||
|
||||
|
||||
@auth_router.get("/me")
|
||||
def get_current_user_profile(user: User = Depends(get_current_user)):
|
||||
"""Retorna la ficha del perfil del usuario actualmente autenticado."""
|
||||
with flask_app.app_context():
|
||||
profile = user_service.get_profile_data(user)
|
||||
return {
|
||||
'status': 'success',
|
||||
'user': profile
|
||||
}
|
||||
|
||||
|
||||
@auth_router.post("/logout")
|
||||
def logout(request: Request, response: Response):
|
||||
"""Cierra la sesión y revoca los tokens activos."""
|
||||
token = get_token_from_request(request)
|
||||
if token:
|
||||
try:
|
||||
JWTService.revoke_token(token)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
response.delete_cookie(key="access_token", path="/")
|
||||
response.delete_cookie(key="refresh_token", path="/api/v1/auth/refresh")
|
||||
return {'status': 'success', 'message': 'Sesión cerrada exitosamente.'}
|
||||
|
||||
|
||||
@auth_router.post("/refresh")
|
||||
def refresh_token(request: Request, response: Response, payload: Optional[RefreshTokenRequest] = None):
|
||||
"""Renueva el token de acceso a partir de un refresh token válido."""
|
||||
token = (payload and payload.refresh_token) or request.cookies.get('refresh_token')
|
||||
if not token:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="No se proporcionó refresh token.")
|
||||
|
||||
with flask_app.app_context():
|
||||
try:
|
||||
decoded = JWTService.decode_token(token, expected_type='refresh')
|
||||
user_id = decoded.get('sub')
|
||||
user = User.query.get(int(user_id))
|
||||
if not user or not user.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Usuario no encontrado o inactivo.")
|
||||
|
||||
tokens = JWTService.generate_tokens(user)
|
||||
response.set_cookie(key="access_token", value=tokens["access_token"], httponly=True, samesite="lax", path="/")
|
||||
return {
|
||||
'status': 'success',
|
||||
'access_token': tokens['access_token'],
|
||||
'refresh_token': tokens['refresh_token'],
|
||||
'token_type': tokens['token_type'],
|
||||
'expires_in': tokens['expires_in']
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Refresh token inválido: {str(e)}")
|
||||
@@ -0,0 +1,192 @@
|
||||
"""
|
||||
FastAPI Classrooms Router (/api/v1/classrooms)
|
||||
Provides endpoints for listing, retrieving, creating, updating and toggling classrooms.
|
||||
"""
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
|
||||
from app import db
|
||||
from app.models.classroom import Classroom
|
||||
from app.services.classroom_service import ClassroomService
|
||||
from app.services.audit_service import AuditService
|
||||
from app.schemas.classroom_dto import ClassroomCreateDTO, ClassroomUpdateDTO
|
||||
from dependencies import get_current_user, require_roles
|
||||
from app.models.user import User
|
||||
from database import get_flask_app
|
||||
|
||||
classrooms_router = APIRouter(prefix="/api/v1/classrooms", tags=["Classrooms"])
|
||||
classroom_service = ClassroomService()
|
||||
flask_app = get_flask_app()
|
||||
|
||||
|
||||
@classrooms_router.get("")
|
||||
def list_classrooms(
|
||||
building_id: Optional[int] = Query(None),
|
||||
floor: Optional[str] = Query(None),
|
||||
mode: Optional[str] = Query(None),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Lista aulas físicas y virtuales con filtros opcionales."""
|
||||
with flask_app.app_context():
|
||||
mode_str = (mode or '').lower()
|
||||
only_virtual = mode_str == 'virtual'
|
||||
only_physical = mode_str == 'physical'
|
||||
|
||||
classrooms = classroom_service.list_classrooms(
|
||||
building_id=building_id,
|
||||
floor=floor,
|
||||
only_virtual=only_virtual,
|
||||
only_physical=only_physical
|
||||
)
|
||||
|
||||
result = []
|
||||
for c in classrooms:
|
||||
result.append({
|
||||
'id': c.id,
|
||||
'code': c.code,
|
||||
'building': c.building_name,
|
||||
'building_id': c.building_id,
|
||||
'floor': c.floor,
|
||||
'floor_display': c.floor_display,
|
||||
'capacity': c.capacity,
|
||||
'is_virtual': c.is_virtual,
|
||||
'location_display': c.location_display,
|
||||
'description': c.description,
|
||||
'is_active': c.is_active
|
||||
})
|
||||
|
||||
return {'total': len(result), 'classrooms': result}
|
||||
|
||||
|
||||
@classrooms_router.get("/{classroom_id}")
|
||||
def get_classroom(
|
||||
classroom_id: int,
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Obtiene el detalle de un aula por ID."""
|
||||
with flask_app.app_context():
|
||||
c = classroom_service.get_classroom(classroom_id)
|
||||
if not c:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Aula {classroom_id} no encontrada."
|
||||
)
|
||||
|
||||
return {
|
||||
'id': c.id,
|
||||
'code': c.code,
|
||||
'building': c.building_name,
|
||||
'building_id': c.building_id,
|
||||
'floor': c.floor,
|
||||
'floor_display': c.floor_display,
|
||||
'capacity': c.capacity,
|
||||
'is_virtual': c.is_virtual,
|
||||
'location_display': c.location_display,
|
||||
'description': c.description,
|
||||
'is_active': c.is_active
|
||||
}
|
||||
|
||||
|
||||
@classrooms_router.post("", status_code=status.HTTP_201_CREATED)
|
||||
def create_classroom(
|
||||
dto: ClassroomCreateDTO,
|
||||
current_user: User = Depends(require_roles(['admin', 'administrador', 'bedelia']))
|
||||
):
|
||||
"""Crea una nueva aula validando con ClassroomCreateDTO."""
|
||||
with flask_app.app_context():
|
||||
try:
|
||||
classroom = classroom_service.create_classroom(dto)
|
||||
AuditService.log(
|
||||
action='CREATE',
|
||||
module='classrooms',
|
||||
entity_id=classroom.id,
|
||||
user=current_user,
|
||||
details=f"Nueva aula creada: {classroom.code} en {classroom.building} (Piso {classroom.floor}, Capacidad: {classroom.capacity})"
|
||||
)
|
||||
return {
|
||||
'message': 'Aula creada exitosamente.',
|
||||
'id': classroom.id,
|
||||
'code': classroom.code,
|
||||
'location_display': classroom.location_display
|
||||
}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
|
||||
|
||||
@classrooms_router.put("/{classroom_id}")
|
||||
def update_classroom(
|
||||
classroom_id: int,
|
||||
dto: ClassroomUpdateDTO,
|
||||
current_user: User = Depends(require_roles(['admin', 'administrador', 'bedelia']))
|
||||
):
|
||||
"""Actualiza los datos de un aula."""
|
||||
with flask_app.app_context():
|
||||
try:
|
||||
classroom = classroom_service.update_classroom(classroom_id, dto)
|
||||
if not classroom:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Aula {classroom_id} no encontrada.")
|
||||
|
||||
AuditService.log(
|
||||
action='UPDATE',
|
||||
module='classrooms',
|
||||
entity_id=classroom.id,
|
||||
user=current_user,
|
||||
details=f"Aula #{classroom.id} ({classroom.code}) actualizada. Capacidad: {classroom.capacity}, Piso: {classroom.floor}"
|
||||
)
|
||||
return {
|
||||
'message': 'Aula actualizada exitosamente.',
|
||||
'id': classroom.id,
|
||||
'code': classroom.code,
|
||||
'capacity': classroom.capacity
|
||||
}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
|
||||
|
||||
@classrooms_router.delete("/{classroom_id}")
|
||||
def delete_classroom(
|
||||
classroom_id: int,
|
||||
current_user: User = Depends(require_roles(['admin', 'administrador']))
|
||||
):
|
||||
"""Elimina o desactiva un aula."""
|
||||
with flask_app.app_context():
|
||||
deleted = classroom_service.delete_classroom(classroom_id)
|
||||
if not deleted:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Aula {classroom_id} no encontrada.")
|
||||
|
||||
AuditService.log(
|
||||
action='DELETE',
|
||||
module='classrooms',
|
||||
entity_id=classroom_id,
|
||||
user=current_user,
|
||||
details=f"Aula #{classroom_id} eliminada/desactivada del sistema"
|
||||
)
|
||||
return {'message': f'Aula {classroom_id} eliminada/desactivada correctamente.'}
|
||||
|
||||
|
||||
@classrooms_router.post("/{classroom_id}/toggle")
|
||||
def toggle_classroom(
|
||||
classroom_id: int,
|
||||
current_user: User = Depends(require_roles(['admin', 'administrador', 'bedelia']))
|
||||
):
|
||||
"""Alterna el estado activo/inactivo de un aula."""
|
||||
with flask_app.app_context():
|
||||
classroom = Classroom.query.get(classroom_id)
|
||||
if not classroom:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Aula {classroom_id} no encontrada.")
|
||||
|
||||
classroom.is_active = not classroom.is_active
|
||||
db.session.commit()
|
||||
AuditService.log(
|
||||
action='TOGGLE',
|
||||
module='classrooms',
|
||||
entity_id=classroom.id,
|
||||
user=current_user,
|
||||
details=f"Aula {classroom.code} {'activada' if classroom.is_active else 'desactivada'}"
|
||||
)
|
||||
return {
|
||||
'status': 'success',
|
||||
'id': classroom.id,
|
||||
'is_active': classroom.is_active,
|
||||
'message': f'Aula {"activada" if classroom.is_active else "desactivada"} correctamente.'
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
"""
|
||||
FastAPI Dashboard Router (/api/v1/dashboard)
|
||||
Provides operational metrics, today/tomorrow/week schedule, and Google Sheets sync inspection.
|
||||
"""
|
||||
from typing import Optional, Dict, Any
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
|
||||
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.subject import Subject
|
||||
from app.models.user import User
|
||||
from app.models.reservation import Reservation
|
||||
from app.models.audit_log import AuditLog
|
||||
from app.models.milestone import AcademicMilestone
|
||||
from app.models.subject import Commission
|
||||
from app.models.setting import SystemSetting
|
||||
from app.services.audit_service import AuditService
|
||||
from dependencies import get_current_user
|
||||
from database import get_flask_app
|
||||
|
||||
dashboard_router = APIRouter(prefix="/api/v1/dashboard", tags=["Dashboard"])
|
||||
|
||||
|
||||
@dashboard_router.get("/stats")
|
||||
def get_stats(current_user: User = Depends(get_current_user)):
|
||||
"""Retorna estadísticas clave y datos operativos para el Dashboard."""
|
||||
from app.routes.api.dashboard import get_stats as flask_get_stats
|
||||
f_app = get_flask_app()
|
||||
with f_app.test_request_context():
|
||||
from flask import g
|
||||
g.jwt_user = current_user
|
||||
resp = flask_get_stats()
|
||||
if hasattr(resp, 'get_json'):
|
||||
return resp.get_json()
|
||||
return resp[0].get_json() if isinstance(resp, tuple) else resp
|
||||
|
||||
|
||||
@dashboard_router.post("/sync-sheets")
|
||||
def sync_google_sheets(
|
||||
payload: Dict[str, Any],
|
||||
request: Request,
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Ejecuta la sincronización con Google Sheets con filtros y selección granular."""
|
||||
from app.routes.api.dashboard import sync_google_sheets as flask_sync
|
||||
f_app = get_flask_app()
|
||||
with f_app.test_request_context(json=payload):
|
||||
from flask import g
|
||||
g.jwt_user = current_user
|
||||
g.current_user = {'email': current_user.email}
|
||||
resp = flask_sync()
|
||||
if hasattr(resp, 'get_json'):
|
||||
return resp.get_json()
|
||||
return resp[0].get_json() if isinstance(resp, tuple) else resp
|
||||
|
||||
|
||||
@dashboard_router.get("/sheets-inspect")
|
||||
@dashboard_router.post("/sheets-inspect")
|
||||
def inspect_google_sheets(
|
||||
request: Request,
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Inspecciona las hojas de cálculo descubriendo carreras, materias y previsualización."""
|
||||
from app.routes.api.dashboard import inspect_google_sheets as flask_inspect
|
||||
f_app = get_flask_app()
|
||||
with f_app.test_request_context():
|
||||
from flask import g
|
||||
g.jwt_user = current_user
|
||||
resp = flask_inspect()
|
||||
if hasattr(resp, 'get_json'):
|
||||
return resp.get_json()
|
||||
return resp[0].get_json() if isinstance(resp, tuple) else resp
|
||||
@@ -0,0 +1,92 @@
|
||||
"""
|
||||
FastAPI Optimizer & Genetic Algorithm Router (/api/v1/optimizer and /api/genetic)
|
||||
Provides asynchronous optimization jobs and genetic heuristic room assignment.
|
||||
"""
|
||||
from typing import Optional, Dict, Any
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
|
||||
from app.schemas.optimizer_dto import OptimizerJobRequestDTO, SpringBootSyncPayloadDTO
|
||||
from app.services.optimizer_service import OptimizerService
|
||||
from dependencies import get_current_user
|
||||
from app.models.user import User
|
||||
from database import get_flask_app
|
||||
|
||||
optimizer_router = APIRouter(prefix="/api/v1/optimizer", tags=["Optimizer"])
|
||||
genetic_router = APIRouter(prefix="/api/genetic", tags=["Genetic Heuristics"])
|
||||
|
||||
|
||||
@optimizer_router.post("/jobs", status_code=status.HTTP_202_ACCEPTED)
|
||||
def submit_optimization_job(
|
||||
dto: OptimizerJobRequestDTO,
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Despacha un trabajo de optimización heurística asíncrono."""
|
||||
job = OptimizerService.submit_job(
|
||||
commission_ids=dto.commission_ids,
|
||||
admin_user_id=current_user.id,
|
||||
start_date=dto.start_date,
|
||||
end_date=dto.end_date,
|
||||
generations=dto.generations,
|
||||
population_size=dto.population_size,
|
||||
workers=dto.workers
|
||||
)
|
||||
|
||||
return {
|
||||
'job_id': job.job_id,
|
||||
'status': job.status.value,
|
||||
'poll_url': f'/api/v1/optimizer/jobs/{job.job_id}',
|
||||
'message': 'Trabajo de optimización puesto en cola con éxito.'
|
||||
}
|
||||
|
||||
|
||||
@optimizer_router.get("/jobs/{job_id}")
|
||||
def get_optimization_job(
|
||||
job_id: str,
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Obtiene el estado, progreso y resultados de un trabajo de optimización en cola."""
|
||||
job = OptimizerService.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Trabajo de optimización {job_id} no encontrado.")
|
||||
|
||||
return job.to_dict()
|
||||
|
||||
|
||||
@optimizer_router.get("/jobs")
|
||||
def list_optimization_jobs(
|
||||
limit: int = Query(20, ge=1, le=100),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Lista los trabajos de optimización más recientes."""
|
||||
jobs = OptimizerService.list_jobs(limit=limit)
|
||||
return {'total': len(jobs), 'jobs': jobs}
|
||||
|
||||
|
||||
@optimizer_router.post("/spring-boot/sync")
|
||||
def sync_with_spring_boot(
|
||||
dto: SpringBootSyncPayloadDTO,
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Endpoint interoperable para la sincronización con microservicios Spring Boot."""
|
||||
try:
|
||||
result = OptimizerService.sync_with_spring_boot(dto, admin_user_id=current_user.id)
|
||||
return result
|
||||
except Exception as ex:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail={'requestId': dto.requestId, 'status': 'ERROR', 'error': str(ex)}
|
||||
)
|
||||
|
||||
|
||||
@genetic_router.get("/commissions")
|
||||
def get_genetic_commissions(current_user: User = Depends(get_current_user)):
|
||||
"""Retorna comisiones activas para el optimizador genético."""
|
||||
from app.routes.genetic_algorithm import get_commissions as flask_get_comm
|
||||
f_app = get_flask_app()
|
||||
with f_app.test_request_context():
|
||||
from flask import g
|
||||
g.jwt_user = current_user
|
||||
resp = flask_get_comm()
|
||||
if hasattr(resp, 'get_json'):
|
||||
return resp.get_json()
|
||||
return resp[0].get_json() if isinstance(resp, tuple) else resp
|
||||
@@ -0,0 +1,379 @@
|
||||
"""
|
||||
FastAPI Reservations Router (/api/v1/reservations)
|
||||
Handles creation, listing, updating, cancelling, confirmation and full conflict matrix validation.
|
||||
"""
|
||||
from typing import Optional, Any, Dict
|
||||
from datetime import datetime, timedelta
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status, Request
|
||||
|
||||
from app import db
|
||||
from app.models.reservation import Reservation
|
||||
from app.services.reservation_service import ReservationService
|
||||
from app.services.audit_service import AuditService
|
||||
from app.schemas.reservation_dto import ReservationCreateDTO, ReservationUpdateDTO
|
||||
from dependencies import get_current_user
|
||||
from app.models.user import User
|
||||
from database import get_flask_app
|
||||
|
||||
reservations_router = APIRouter(prefix="/api/v1/reservations", tags=["Reservations"])
|
||||
reservation_service = ReservationService()
|
||||
flask_app = get_flask_app()
|
||||
|
||||
|
||||
@reservations_router.get("")
|
||||
def list_reservations(
|
||||
start_date: Optional[str] = Query(None),
|
||||
end_date: Optional[str] = Query(None),
|
||||
classroom_id: Optional[int] = Query(None),
|
||||
hide_virtual: Optional[str] = Query(None),
|
||||
floor: Optional[str] = Query(None),
|
||||
shift: Optional[str] = Query(None),
|
||||
search: Optional[str] = Query(None),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Consulta de reservas por rango de fechas y/o aula."""
|
||||
with flask_app.app_context():
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
start_dt = datetime.strptime(start_date, '%Y-%m-%d') if start_date else now.replace(hour=0, minute=0, second=0)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Formato inválido de start_date (debe ser YYYY-MM-DD).")
|
||||
|
||||
try:
|
||||
end_dt = datetime.strptime(end_date, '%Y-%m-%d').replace(hour=23, minute=59, second=59) if end_date else start_dt + timedelta(days=7)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Formato inválido de end_date (debe ser YYYY-MM-DD).")
|
||||
|
||||
is_hide_virtual = str(hide_virtual).lower() in ['1', 'true']
|
||||
|
||||
reservations = reservation_service.list_reservations(start_dt, end_dt, classroom_id=classroom_id)
|
||||
result = []
|
||||
for r in reservations:
|
||||
is_virt = bool(r.is_virtual or (r.classroom and r.classroom.is_virtual))
|
||||
if is_hide_virtual and is_virt:
|
||||
continue
|
||||
if floor and r.classroom and str(r.classroom.floor).strip().lower() != str(floor).strip().lower():
|
||||
continue
|
||||
if shift and r.shift and shift.lower() not in r.shift.lower():
|
||||
continue
|
||||
if search:
|
||||
s_lower = search.lower()
|
||||
subj_n = (r.subject_name or '').lower()
|
||||
subj_c = (r.subject_code or '').lower()
|
||||
c_name = (r.classroom.code if r.classroom else '').lower()
|
||||
u_name = (r.user.name if r.user else '').lower()
|
||||
if s_lower not in subj_n and s_lower not in subj_c and s_lower not in c_name and s_lower not in u_name:
|
||||
continue
|
||||
|
||||
result.append({
|
||||
'id': r.id,
|
||||
'classroom_id': r.classroom_id,
|
||||
'classroom_name': r.classroom.code if r.classroom else None,
|
||||
'classroom': {
|
||||
'id': r.classroom.id,
|
||||
'code': r.classroom.code,
|
||||
'code_display': getattr(r.classroom, 'code_display', r.classroom.code),
|
||||
'floor': r.classroom.floor,
|
||||
'floor_display': getattr(r.classroom, 'floor_display', f"Piso {r.classroom.floor}"),
|
||||
'building': getattr(r.classroom, 'building_name', r.classroom.building),
|
||||
'is_virtual': getattr(r.classroom, 'is_virtual', False),
|
||||
'location_display': getattr(r.classroom, 'location_display', r.classroom.code)
|
||||
} if r.classroom else None,
|
||||
'commission_id': r.commission_id,
|
||||
'commission': {
|
||||
'id': r.commission.id,
|
||||
'code': r.commission.code,
|
||||
'virtual_link': r.commission.virtual_link,
|
||||
'max_students': r.commission.max_students
|
||||
} if r.commission else None,
|
||||
'teacher_name': r.user.name if r.user else None,
|
||||
'user': {
|
||||
'id': r.user.id,
|
||||
'name': r.user.name,
|
||||
'email': r.user.email
|
||||
} if r.user else None,
|
||||
'start_time': r.start_time.isoformat(),
|
||||
'end_time': r.end_time.isoformat(),
|
||||
'purpose': r.purpose,
|
||||
'subject_name': r.subject_name,
|
||||
'subject_code': r.subject_code,
|
||||
'career_name': r.commission.career_name if (r.commission and hasattr(r.commission, 'career_name')) else '',
|
||||
'career_names': r.commission.career_names if (r.commission and hasattr(r.commission, 'career_names')) else '',
|
||||
'commission_code': r.commission.code if r.commission else '',
|
||||
'status': str(r.status.value if hasattr(r.status, 'value') else r.status),
|
||||
'shift': r.shift or 'Mañana',
|
||||
'virtual_link': r.virtual_link,
|
||||
'effective_virtual_link': r.effective_virtual_link,
|
||||
'is_virtual': is_virt,
|
||||
'expected_attendees': r.expected_attendees or 30,
|
||||
'notes': r.notes or ''
|
||||
})
|
||||
|
||||
return {
|
||||
'total': len(result),
|
||||
'start_date': start_dt.strftime('%Y-%m-%d'),
|
||||
'end_date': end_dt.strftime('%Y-%m-%d'),
|
||||
'reservations': result
|
||||
}
|
||||
|
||||
|
||||
@reservations_router.get("/{reservation_id}")
|
||||
def get_reservation(reservation_id: int, current_user: User = Depends(get_current_user)):
|
||||
"""Obtiene el detalle de una reserva específica."""
|
||||
with flask_app.app_context():
|
||||
r = reservation_service.get_reservation(reservation_id)
|
||||
if not r:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.")
|
||||
|
||||
duration_min = int((r.end_time - r.start_time).total_seconds() / 60) if (r.start_time and r.end_time) else 120
|
||||
is_virt = bool(r.is_virtual or (r.classroom and r.classroom.is_virtual))
|
||||
|
||||
return {
|
||||
'id': r.id,
|
||||
'classroom_id': r.classroom_id,
|
||||
'classroom_name': r.classroom.code if r.classroom else None,
|
||||
'location_display': getattr(r.classroom, 'location_display', r.classroom.code if r.classroom else None),
|
||||
'classroom': {
|
||||
'id': r.classroom.id,
|
||||
'code': r.classroom.code,
|
||||
'code_display': getattr(r.classroom, 'code_display', r.classroom.code),
|
||||
'building_name': getattr(r.classroom, 'building_name', getattr(r.classroom, 'building', 'Edificio Central')),
|
||||
'floor': r.classroom.floor,
|
||||
'floor_display': getattr(r.classroom, 'floor_display', f"Piso {r.classroom.floor}"),
|
||||
'capacity': r.classroom.capacity,
|
||||
'capacity_display': getattr(r.classroom, 'capacity_display', str(r.classroom.capacity)),
|
||||
'description': getattr(r.classroom, 'description', '') or '',
|
||||
'is_virtual': getattr(r.classroom, 'is_virtual', False)
|
||||
} if r.classroom else None,
|
||||
'commission_id': r.commission_id,
|
||||
'commission': {
|
||||
'id': r.commission.id,
|
||||
'code': r.commission.code,
|
||||
'full_code': r.commission.get_full_code() if hasattr(r.commission, 'get_full_code') else r.commission.code,
|
||||
'virtual_link': r.commission.virtual_link,
|
||||
'max_students': r.commission.max_students,
|
||||
'current_students': getattr(r.commission, 'current_students', 0),
|
||||
'subject': {
|
||||
'id': r.commission.subject.id,
|
||||
'name': r.commission.subject.name,
|
||||
'code': r.commission.subject.code
|
||||
} if (r.commission and r.commission.subject) else None
|
||||
} if r.commission else None,
|
||||
'teacher_id': r.user_id,
|
||||
'teacher_name': r.user.name if r.user else None,
|
||||
'user': {
|
||||
'id': r.user.id,
|
||||
'name': r.user.name,
|
||||
'first_name': getattr(r.user, 'first_name', r.user.name.split()[0] if r.user.name else 'Usuario'),
|
||||
'last_name': getattr(r.user, 'last_name', ' '.join(r.user.name.split()[1:]) if r.user.name and len(r.user.name.split()) > 1 else ''),
|
||||
'email': r.user.email
|
||||
} if r.user else None,
|
||||
'start_time': r.start_time.isoformat(),
|
||||
'end_time': r.end_time.isoformat(),
|
||||
'duration': duration_min,
|
||||
'purpose': r.purpose,
|
||||
'status': str(r.status.value if hasattr(r.status, 'value') else r.status),
|
||||
'shift': r.shift or 'Mañana',
|
||||
'virtual_link': r.virtual_link,
|
||||
'effective_virtual_link': r.effective_virtual_link,
|
||||
'is_virtual': is_virt,
|
||||
'expected_attendees': r.expected_attendees or 30,
|
||||
'notes': r.notes or '',
|
||||
'can_be_cancelled': r.can_be_cancelled() if hasattr(r, 'can_be_cancelled') else True
|
||||
}
|
||||
|
||||
|
||||
@reservations_router.post("", status_code=status.HTTP_201_CREATED)
|
||||
def create_reservation(
|
||||
payload: Dict[str, Any],
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Crea una reserva aplicando validación DTO y detección de colisiones."""
|
||||
with flask_app.app_context():
|
||||
if 'user_id' not in payload:
|
||||
payload['user_id'] = current_user.id
|
||||
|
||||
try:
|
||||
dto = ReservationCreateDTO(**payload)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
|
||||
try:
|
||||
reservation = reservation_service.create_reservation(dto)
|
||||
AuditService.log(
|
||||
action='CREATE',
|
||||
module='reservations',
|
||||
entity_id=reservation.id,
|
||||
user=current_user,
|
||||
details=f"Nueva reserva creada #{reservation.id} en aula ID {reservation.classroom_id} ({reservation.start_time.strftime('%Y-%m-%d %H:%M')} a {reservation.end_time.strftime('%H:%M')}) - Motivo: {reservation.purpose}"
|
||||
)
|
||||
return {
|
||||
'message': 'Reserva creada exitosamente.',
|
||||
'id': reservation.id,
|
||||
'classroom_id': reservation.classroom_id,
|
||||
'start_time': reservation.start_time.isoformat(),
|
||||
'end_time': reservation.end_time.isoformat(),
|
||||
'status': str(reservation.status)
|
||||
}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
||||
|
||||
|
||||
@reservations_router.put("/{reservation_id}")
|
||||
def update_reservation(
|
||||
reservation_id: int,
|
||||
dto: ReservationUpdateDTO,
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Modifica una reserva existente."""
|
||||
with flask_app.app_context():
|
||||
try:
|
||||
reservation = reservation_service.update_reservation(reservation_id, dto)
|
||||
AuditService.log(
|
||||
action='UPDATE',
|
||||
module='reservations',
|
||||
entity_id=reservation.id,
|
||||
user=current_user,
|
||||
details=f"Reserva #{reservation.id} modificada ({reservation.start_time.strftime('%Y-%m-%d %H:%M')} a {reservation.end_time.strftime('%H:%M')}) - Estado: {reservation.status}"
|
||||
)
|
||||
return {
|
||||
'message': 'Reserva actualizada exitosamente.',
|
||||
'id': reservation.id,
|
||||
'start_time': reservation.start_time.isoformat(),
|
||||
'end_time': reservation.end_time.isoformat(),
|
||||
'status': str(reservation.status)
|
||||
}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
||||
|
||||
|
||||
@reservations_router.delete("/{reservation_id}")
|
||||
def cancel_reservation(
|
||||
reservation_id: int,
|
||||
hard: Optional[str] = Query(None),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Cancela o elimina una reserva según el parámetro hard."""
|
||||
with flask_app.app_context():
|
||||
hard_delete = str(hard).lower() in ['true', '1']
|
||||
if hard_delete:
|
||||
res = Reservation.query.get(reservation_id)
|
||||
if not res:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.")
|
||||
db.session.delete(res)
|
||||
db.session.commit()
|
||||
AuditService.log(
|
||||
action='DELETE',
|
||||
module='reservations',
|
||||
entity_id=reservation_id,
|
||||
user=current_user,
|
||||
details=f"Reserva #{reservation_id} eliminada permanentemente"
|
||||
)
|
||||
return {'message': f'Reserva {reservation_id} eliminada permanentemente.'}
|
||||
|
||||
cancelled = reservation_service.cancel_reservation(reservation_id)
|
||||
if not cancelled:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.")
|
||||
|
||||
AuditService.log(
|
||||
action='CANCEL',
|
||||
module='reservations',
|
||||
entity_id=reservation_id,
|
||||
user=current_user,
|
||||
details=f"Reserva #{reservation_id} cancelada"
|
||||
)
|
||||
return {'message': f'Reserva {reservation_id} cancelada correctamente.'}
|
||||
|
||||
|
||||
@reservations_router.post("/{reservation_id}/delete")
|
||||
def delete_reservation_post(reservation_id: int, current_user: User = Depends(get_current_user)):
|
||||
"""Elimina permanentemente una reserva (POST)."""
|
||||
with flask_app.app_context():
|
||||
res = Reservation.query.get(reservation_id)
|
||||
if not res:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.")
|
||||
db.session.delete(res)
|
||||
db.session.commit()
|
||||
AuditService.log(
|
||||
action='DELETE',
|
||||
module='reservations',
|
||||
entity_id=reservation_id,
|
||||
user=current_user,
|
||||
details=f"Reserva #{reservation_id} eliminada permanentemente"
|
||||
)
|
||||
return {'message': f'Reserva {reservation_id} eliminada permanentemente.'}
|
||||
|
||||
|
||||
@reservations_router.post("/{reservation_id}/cancel")
|
||||
def cancel_reservation_post(reservation_id: int, current_user: User = Depends(get_current_user)):
|
||||
"""Cancela una reserva (POST)."""
|
||||
with flask_app.app_context():
|
||||
cancelled = reservation_service.cancel_reservation(reservation_id)
|
||||
if not cancelled:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.")
|
||||
|
||||
AuditService.log(
|
||||
action='CANCEL',
|
||||
module='reservations',
|
||||
entity_id=reservation_id,
|
||||
user=current_user,
|
||||
details=f"Reserva #{reservation_id} cancelada"
|
||||
)
|
||||
return {'message': f'Reserva {reservation_id} cancelada correctamente.'}
|
||||
|
||||
|
||||
@reservations_router.post("/{reservation_id}/confirm")
|
||||
def confirm_reservation(reservation_id: int, current_user: User = Depends(get_current_user)):
|
||||
"""Confirma una reserva cambiando su estado a CONFIRMED."""
|
||||
with flask_app.app_context():
|
||||
confirmed = reservation_service.confirm_reservation(reservation_id)
|
||||
if not confirmed:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Reserva {reservation_id} no encontrada.")
|
||||
|
||||
AuditService.log(
|
||||
action='CONFIRM',
|
||||
module='reservations',
|
||||
entity_id=reservation_id,
|
||||
user=current_user,
|
||||
details=f"Reserva #{reservation_id} confirmada oficialmente"
|
||||
)
|
||||
return {'message': f'Reserva {reservation_id} confirmada correctamente.'}
|
||||
|
||||
|
||||
@reservations_router.post("/check-conflicts")
|
||||
def check_conflicts_endpoint(payload: Dict[str, Any], current_user: User = Depends(get_current_user)):
|
||||
"""Evalúa la matriz completa de conflictos (físico, docente y aforo) en tiempo real."""
|
||||
with flask_app.app_context():
|
||||
classroom_id = payload.get('classroom_id')
|
||||
start_str = payload.get('start_time')
|
||||
end_str = payload.get('end_time')
|
||||
|
||||
if not classroom_id or not start_str or not end_str:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="classroom_id, start_time y end_time son obligatorios.")
|
||||
|
||||
try:
|
||||
start_time = datetime.fromisoformat(str(start_str).replace('Z', '+00:00'))
|
||||
end_time = datetime.fromisoformat(str(end_str).replace('Z', '+00:00'))
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Formato inválido de fecha/hora (ISO 8601 esperado).")
|
||||
|
||||
teacher_id = payload.get('teacher_id')
|
||||
commission_id = payload.get('commission_id')
|
||||
expected_attendees = payload.get('expected_attendees')
|
||||
allow_co_teaching = bool(payload.get('allow_co_teaching_exception', False))
|
||||
exclude_id = payload.get('exclude_id')
|
||||
|
||||
try:
|
||||
matrix = reservation_service.check_full_conflicts_matrix(
|
||||
classroom_id=int(classroom_id),
|
||||
start_time=start_time,
|
||||
end_time=end_time,
|
||||
teacher_id=int(teacher_id) if teacher_id else None,
|
||||
commission_id=int(commission_id) if commission_id else None,
|
||||
expected_attendees=int(expected_attendees) if expected_attendees is not None else None,
|
||||
allow_co_teaching_exception=allow_co_teaching,
|
||||
exclude_id=int(exclude_id) if exclude_id else None
|
||||
)
|
||||
return matrix
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
FastAPI Students Router (/api/v1/students)
|
||||
Provides academic milestone and gradebook queries for students.
|
||||
"""
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
|
||||
from app.services.gradebook_service import GradebookService
|
||||
from dependencies import get_current_user
|
||||
from app.models.user import User
|
||||
|
||||
students_router = APIRouter(prefix="/api/v1/students", tags=["Students"])
|
||||
|
||||
|
||||
@students_router.get("/my-grades")
|
||||
def get_my_grades(current_user: User = Depends(get_current_user)):
|
||||
"""Consulta individual de calificaciones y estado académico del alumno logueado."""
|
||||
try:
|
||||
grades = GradebookService.get_student_grades(current_user.id)
|
||||
return {
|
||||
'status': 'success',
|
||||
'student_id': current_user.id,
|
||||
'is_impersonating': False,
|
||||
'data': grades
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
|
||||
|
||||
|
||||
@students_router.get("/my-upcoming-milestones")
|
||||
def get_my_upcoming_milestones(
|
||||
limit: int = Query(5, ge=1, le=50),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Próximas evaluaciones e hitos académicos con cuenta regresiva para el dashboard."""
|
||||
try:
|
||||
milestones = GradebookService.get_student_upcoming_milestones(current_user.id, limit=limit)
|
||||
return {'status': 'success', 'data': milestones}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
|
||||
@@ -0,0 +1,13 @@
|
||||
from fastapi import APIRouter
|
||||
from app import __version__
|
||||
|
||||
version_router = APIRouter(prefix="/api/v1", tags=["Version"])
|
||||
|
||||
@version_router.get("/version")
|
||||
def get_version():
|
||||
return {
|
||||
"status": "success",
|
||||
"version": __version__,
|
||||
"engine": "FastAPI ASGI",
|
||||
"api_prefix": "/api/v1"
|
||||
}
|
||||
Reference in New Issue
Block a user