forked from mtusi2026/mtusi2026lab2
72 lines
2.0 KiB
Python
72 lines
2.0 KiB
Python
from collections.abc import AsyncIterator
|
|
from contextlib import asynccontextmanager
|
|
|
|
import uvicorn
|
|
from fastapi import FastAPI
|
|
|
|
from application import api_endpoints, health_endpoints
|
|
from application.api.handlers import register_exception_handlers
|
|
from application.api.middlewares import RequestContextMiddleware
|
|
from config import (
|
|
APP_ENV,
|
|
APP_HOST,
|
|
APP_PORT,
|
|
DB_STARTUP_TIMEOUT_SEC,
|
|
LOGGER,
|
|
PASSWORD_HASH_WORKERS,
|
|
SESSION_TTL_SECONDS,
|
|
SHUTDOWN_TIMEOUT_SEC,
|
|
)
|
|
from infrastructure import PasswordHasher, cache_manager, database_pool_manager
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
await database_pool_manager.create_pool(DB_STARTUP_TIMEOUT_SEC)
|
|
await database_pool_manager.apply_migrations()
|
|
cache_manager.create_client()
|
|
password_hasher = PasswordHasher(PASSWORD_HASH_WORKERS)
|
|
app.state.database = database_pool_manager
|
|
app.state.cache = cache_manager
|
|
app.state.password_hasher = password_hasher
|
|
app.state.is_ready = True
|
|
LOGGER.info(
|
|
f"Application started, env={APP_ENV}, session ttl={SESSION_TTL_SECONDS} s"
|
|
)
|
|
yield
|
|
app.state.is_ready = False
|
|
await cache_manager.close()
|
|
await database_pool_manager.close()
|
|
password_hasher.close()
|
|
LOGGER.info("Application stopped, connections closed")
|
|
|
|
|
|
app = FastAPI(
|
|
title="mtuci-labs-messanger",
|
|
description="мессенджер-конкурент-максу",
|
|
version="1.2.0",
|
|
lifespan=lifespan,
|
|
)
|
|
|
|
app.add_middleware(RequestContextMiddleware)
|
|
register_exception_handlers(app)
|
|
|
|
app.include_router(health_endpoints)
|
|
app.include_router(api_endpoints)
|
|
|
|
|
|
def main(host: str, port: int, shutdown_timeout: int) -> None:
|
|
"""Функция для запуска api"""
|
|
uvicorn.run(
|
|
app,
|
|
host=host,
|
|
port=port,
|
|
timeout_graceful_shutdown=shutdown_timeout,
|
|
access_log=False,
|
|
server_header=False,
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main(host=APP_HOST, port=APP_PORT, shutdown_timeout=SHUTDOWN_TIMEOUT_SEC)
|