Files
bot-telegram/api/main.py
2025-09-14 22:09:39 +05:00

95 lines
3.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
FastAPI приложение для взаимодействия с Telegram ботом
"""
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from contextlib import asynccontextmanager
import logging
import sys
import os
# Добавляем путь к корневой директории проекта
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from database.database import db, get_db_session, init_database, test_db_connection
from database.models import User, Message, BotSettings
from api.routers import users_router, messages_router, settings_router
from api.schemas import HealthCheckResponse, RootResponse
from api.config import config
# Настройка логирования
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Управление жизненным циклом приложения"""
# Инициализация при запуске
logger.info("Запуск FastAPI приложения...")
# Проверка подключения к БД
if not test_db_connection():
logger.error("Не удалось подключиться к базе данных!")
raise Exception("Database connection failed")
# Создание таблиц если они не существуют
try:
init_database()
logger.info("База данных инициализирована")
except Exception as e:
logger.error(f"Ошибка инициализации базы данных: {e}")
raise
yield
# Очистка при завершении
logger.info("Завершение работы FastAPI приложения...")
db.close()
# Создание FastAPI приложения
app = FastAPI(
title=config.TITLE,
description=config.DESCRIPTION,
version=config.VERSION,
lifespan=lifespan
)
# Настройка CORS
app.add_middleware(
CORSMiddleware,
allow_origins=config.CORS_ORIGINS,
allow_credentials=config.CORS_CREDENTIALS,
allow_methods=config.CORS_METHODS,
allow_headers=config.CORS_HEADERS,
)
# Подключение роутеров
app.include_router(users_router, prefix=config.API_V1_PREFIX)
app.include_router(messages_router, prefix=config.API_V1_PREFIX)
app.include_router(settings_router, prefix=config.API_V1_PREFIX)
@app.get("/", response_model=RootResponse)
async def root():
"""Корневой эндпоинт"""
return RootResponse(
message=config.TITLE,
version=config.VERSION,
status="running"
)
@app.get("/health", response_model=HealthCheckResponse)
async def health_check():
"""Проверка состояния приложения"""
db_status = test_db_connection()
return HealthCheckResponse(
status="healthy" if db_status else "unhealthy",
database="connected" if db_status else "disconnected"
)
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host=config.HOST, port=config.PORT, reload=config.RELOAD)