Update app/db.py
Browse files
app/db.py
CHANGED
@@ -1,3 +1,4 @@
|
|
|
|
1 |
from typing import AsyncGenerator
|
2 |
from app import app
|
3 |
from fastapi import Depends
|
@@ -54,25 +55,49 @@ async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
|
|
54 |
async def get_user_db(session: AsyncSession = Depends(get_async_session)):
|
55 |
yield SQLAlchemyUserDatabase(session, User)
|
56 |
|
57 |
-
|
58 |
-
async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
|
59 |
-
async with async_session() as session:
|
60 |
-
assert isinstance(session, AsyncSession)
|
61 |
-
yield session
|
62 |
-
|
63 |
-
|
64 |
async def connect() -> None:
|
65 |
async with engine.begin() as conn:
|
66 |
await conn.run_sync(Base.metadata.create_all, checkfirst=True)
|
67 |
|
68 |
|
|
|
|
|
|
|
69 |
"""
|
70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
async with engine.begin() as conn:
|
72 |
-
await conn.run_sync(Base.metadata.create_all
|
73 |
|
74 |
|
75 |
-
async def
|
76 |
-
|
77 |
-
|
78 |
-
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
from typing import AsyncGenerator
|
3 |
from app import app
|
4 |
from fastapi import Depends
|
|
|
55 |
async def get_user_db(session: AsyncSession = Depends(get_async_session)):
|
56 |
yield SQLAlchemyUserDatabase(session, User)
|
57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
async def connect() -> None:
|
59 |
async with engine.begin() as conn:
|
60 |
await conn.run_sync(Base.metadata.create_all, checkfirst=True)
|
61 |
|
62 |
|
63 |
+
async def disconnect() -> None:
|
64 |
+
if engine:
|
65 |
+
await engine.dispose()
|
66 |
"""
|
67 |
+
|
68 |
+
|
69 |
+
|
70 |
+
from typing import AsyncGenerator
|
71 |
+
|
72 |
+
from fastapi import Depends
|
73 |
+
from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
|
74 |
+
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
75 |
+
from sqlalchemy.orm import DeclarativeBase
|
76 |
+
|
77 |
+
DATABASE_URL = "sqlite+aiosqlite:///./test.db"
|
78 |
+
|
79 |
+
|
80 |
+
class Base(DeclarativeBase):
|
81 |
+
pass
|
82 |
+
|
83 |
+
|
84 |
+
class User(SQLAlchemyBaseUserTableUUID, Base):
|
85 |
+
pass
|
86 |
+
|
87 |
+
|
88 |
+
engine = create_async_engine(DATABASE_URL)
|
89 |
+
async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
|
90 |
+
|
91 |
+
|
92 |
+
async def create_db_and_tables():
|
93 |
async with engine.begin() as conn:
|
94 |
+
await conn.run_sync(Base.metadata.create_all)
|
95 |
|
96 |
|
97 |
+
async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
|
98 |
+
async with async_session_maker() as session:
|
99 |
+
yield session
|
100 |
+
|
101 |
+
|
102 |
+
async def get_user_db(session: AsyncSession = Depends(get_async_session)):
|
103 |
+
yield SQLAlchemyUserDatabase(session, User)
|