Use sync SQLAlchemy in Celery worker - fixes asyncpg connection issues
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import DeclarativeBase, sessionmaker
|
||||
from app.core.config import settings
|
||||
|
||||
# Async engine for FastAPI
|
||||
engine = create_async_engine(
|
||||
settings.database_url,
|
||||
echo=settings.environment == "development",
|
||||
@@ -15,6 +17,19 @@ AsyncSessionLocal = async_sessionmaker(
|
||||
expire_on_commit=False,
|
||||
)
|
||||
|
||||
# Sync engine for Celery workers (Celery + asyncio don't mix well)
|
||||
# Convert async URL to sync: postgresql+asyncpg:// → postgresql+psycopg2://
|
||||
sync_url = settings.database_url.replace("postgresql+asyncpg://", "postgresql+psycopg2://")
|
||||
sync_engine = create_engine(
|
||||
sync_url,
|
||||
echo=False,
|
||||
pool_size=5,
|
||||
max_overflow=10,
|
||||
pool_pre_ping=True,
|
||||
)
|
||||
|
||||
SyncSessionLocal = sessionmaker(sync_engine, expire_on_commit=False)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
@@ -29,4 +44,4 @@ async def get_db():
|
||||
await session.rollback()
|
||||
raise
|
||||
finally:
|
||||
await session.close()
|
||||
await session.close()
|
||||
Reference in New Issue
Block a user