6432210a36
Extract identical get_async_session() and cleanup_engine() functions from downloads.py and maintenance.py into a shared db.py module. This eliminates code duplication and improves maintainability. db.py imports only from app.config and SQLAlchemy to avoid circular dependencies with the task modules that import from it. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
28 lines
918 B
Python
28 lines
918 B
Python
"""Shared async database helpers for Celery tasks.
|
|
|
|
Provides get_async_session() and cleanup_engine() used by both
|
|
downloads.py and maintenance.py. This module must not import from
|
|
either of those files to avoid circular imports.
|
|
"""
|
|
|
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
|
|
|
|
from app.config import get_settings
|
|
|
|
|
|
def get_async_session():
|
|
"""Get async session factory for Celery tasks.
|
|
|
|
Creates a fresh engine and session factory each time to avoid
|
|
event loop issues when asyncio.run() creates new loops.
|
|
"""
|
|
settings = get_settings()
|
|
engine = create_async_engine(settings.async_database_url, echo=False)
|
|
session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
|
return session_factory, engine
|
|
|
|
|
|
async def cleanup_engine(engine):
|
|
"""Properly dispose of the async engine."""
|
|
await engine.dispose()
|