feat: add app factory with lifespan setup
This commit is contained in:
parent
94dd4a752e
commit
892ca515bb
63
src/proxy_pool/app.py
Normal file
63
src/proxy_pool/app.py
Normal file
@ -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
|
||||||
Loading…
x
Reference in New Issue
Block a user