test ferst
This commit is contained in:
44
api/bd/database.py
Normal file
44
api/bd/database.py
Normal file
@@ -0,0 +1,44 @@
|
||||
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
|
||||
Reference in New Issue
Block a user