From 892ca515bb2da91cda38a95139d99f0e0ecf2023 Mon Sep 17 00:00:00 2001 From: agatha Date: Sat, 14 Mar 2026 15:48:53 -0400 Subject: [PATCH] feat: add app factory with lifespan setup --- src/proxy_pool/app.py | 63 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/proxy_pool/app.py diff --git a/src/proxy_pool/app.py b/src/proxy_pool/app.py new file mode 100644 index 0000000..0cb3233 --- /dev/null +++ b/src/proxy_pool/app.py @@ -0,0 +1,63 @@ +import logging +from contextlib import asynccontextmanager + +from fastapi import FastAPI +from redis.asyncio import from_url as redis_from_url + +from proxy_pool.config import get_settings +from proxy_pool.db.session import create_session_factory +from proxy_pool.plugins.discovery import discover_plugins +from proxy_pool.plugins.registry import PluginRegistry + +logger = logging.getLogger(__name__) + + +@asynccontextmanager +async def lifespan(app: FastAPI): + settings = get_settings() + + # Database + session_factory = create_session_factory(settings) + app.state.session_factory = session_factory + app.state.engine = session_factory.kw["bind"] + + # Redis + redis = redis_from_url( + settings.redis.url, + decode_responses=True, + ) + app.state.redis = redis + + # Plugin registry + registry = PluginRegistry() + discover_plugins("proxy_pool.plugins.builtin.parsers", registry, settings) + discover_plugins("proxy_pool.plugins.builtin.checkers", registry, settings) + discover_plugins("proxy_pool.plugins.builtin.notifiers", registry, settings) + app.state.registry = registry + + logger.info( + "Started with %d parsers, %d checkers, %d notifiers", + len(registry.parsers), + len(registry.checkers), + len(registry.notifiers), + ) + + yield + + # Cleanup + await redis.close() + await app.state.engine.dispose() + + +def create_app() -> FastAPI: + settings = get_settings() + + app = FastAPI( + title=settings.app_name, + lifespan=lifespan, + ) + + # Register routers here as we build them + # app.include_router(...) + + return app