File size: 1,625 Bytes
ba86161 b5eec84 ba86161 f00b651 e2f7936 ba86161 ab6f064 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
from typing import AsyncGenerator
from app import app
from fastapi import Depends
from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy import URL
db_url = URL.create(
"postgresql+asyncpg",
username="avnadmin",
password="AVNS_u12fHxoNLBbzD8TGpqN", # plain (unescaped) text
host="pg-opengenai-opengenai.b.aivencloud.com",
database="defaultdb",
port=14535,
)
DATABASE_URL = db_url
#DATABASE_URL = "sqlite+aiosqlite:///./test.db"
class Base(DeclarativeBase):
pass
class User(SQLAlchemyBaseUserTableUUID, Base):
pass
engine = create_async_engine(DATABASE_URL, echo=True)
async_session_maker = async_sessionmaker(engine,
#class_=AsyncSession,
autoflush=True,
autocommit=False,
expire_on_commit=False,
)
async def create_db_and_tables():
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
async with async_session_maker() as session:
yield session
async def get_user_db(session: AsyncSession = Depends(get_async_session)):
yield SQLAlchemyUserDatabase(session, User)
async def connect() -> None:
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all, checkfirst=True)
async def disconnect() -> None:
if engine:
await engine.dispose()
|