57 lines
1.9 KiB
Python
57 lines
1.9 KiB
Python
"""Создание FastAPI-приложения админки."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import AsyncIterator
|
|
from contextlib import asynccontextmanager
|
|
from pathlib import Path
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.templating import Jinja2Templates
|
|
|
|
from admin.routes import health, messages, pages
|
|
from common import __version__
|
|
from common.config import AdminSettings, get_admin_settings
|
|
from common.db.pool import close_pool, init_pool
|
|
from common.logging_config import setup_logging
|
|
|
|
BASE_DIR = Path(__file__).resolve().parent
|
|
TEMPLATES_DIR = BASE_DIR / "templates"
|
|
|
|
|
|
def create_app(settings: AdminSettings | None = None, *, init_db: bool = True) -> FastAPI:
|
|
"""Собрать приложение: настройки, шаблоны, роутеры.
|
|
|
|
Настройки можно передать явно (тесты); по умолчанию читаются из окружения.
|
|
``init_db=False`` — не открывать пул Postgres (юнит-тесты без БД).
|
|
"""
|
|
setup_logging()
|
|
settings = settings or get_admin_settings()
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
if init_db:
|
|
await init_pool(app.state.settings)
|
|
try:
|
|
yield
|
|
finally:
|
|
if init_db:
|
|
await close_pool()
|
|
|
|
app = FastAPI(
|
|
title="DispelEvilBot Admin",
|
|
version=__version__,
|
|
# Swagger/OpenAPI наружу пока не нужны: админка закрыта логином (Блок 4.2).
|
|
docs_url=None,
|
|
redoc_url=None,
|
|
openapi_url=None,
|
|
lifespan=lifespan,
|
|
)
|
|
app.state.settings = settings
|
|
app.state.templates = Jinja2Templates(directory=str(TEMPLATES_DIR))
|
|
|
|
app.include_router(health.router)
|
|
app.include_router(pages.router)
|
|
app.include_router(messages.router)
|
|
return app
|