45 lines
1.2 KiB
Python
45 lines
1.2 KiB
Python
import os
|
|
import asyncio
|
|
import sqlalchemy
|
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
|
|
from sqlalchemy.orm import DeclarativeBase
|
|
|
|
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql+asyncpg://postgres:postgres@localhost:5432/news")
|
|
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")
|
|
|
|
engine = create_async_engine(DATABASE_URL, pool_size=10, max_overflow=20, echo=False)
|
|
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
|
|
|
|
|
|
class Base(DeclarativeBase):
|
|
pass
|
|
|
|
|
|
async def get_db():
|
|
async with AsyncSessionLocal() as session:
|
|
yield session
|
|
|
|
|
|
async def wait_for_db():
|
|
for attempt in range(30):
|
|
try:
|
|
async with engine.connect() as conn:
|
|
await conn.execute(sqlalchemy.text("SELECT 1"))
|
|
return
|
|
except Exception:
|
|
if attempt == 29:
|
|
raise
|
|
await asyncio.sleep(2)
|
|
|
|
|
|
import redis.asyncio as aioredis
|
|
|
|
_redis: aioredis.Redis | None = None
|
|
|
|
|
|
async def get_redis() -> aioredis.Redis:
|
|
global _redis
|
|
if _redis is None:
|
|
_redis = aioredis.from_url(REDIS_URL, encoding="utf-8", decode_responses=True)
|
|
return _redis
|