File tree Expand file tree Collapse file tree 2 files changed +21
-21
lines changed
Expand file tree Collapse file tree 2 files changed +21
-21
lines changed Original file line number Diff line number Diff line change 77engine = create_async_engine (DATABASE_URL , echo = False )
88Base = declarative_base ()
99async_session = async_sessionmaker (engine , expire_on_commit = False )
10+
11+
12+ async def get_db ():
13+ """Get a database session.
14+
15+ To be used for dependency injection.
16+ """
17+ async with async_session () as session :
18+ async with session .begin ():
19+ yield session
20+
21+
22+ async def init_models ():
23+ """Create tables if they don't already exist.
24+
25+ In a real-life example we would use Alembic to manage migrations.
26+ """
27+ async with engine .begin () as conn :
28+ # await conn.run_sync(Base.metadata.drop_all)
29+ await conn .run_sync (Base .metadata .create_all )
Original file line number Diff line number Diff line change 55from fastapi import Depends , FastAPI
66from sqlalchemy import select
77
8- from db import Base , async_session , engine
8+ from db import get_db , init_models
99from models import User
1010
1111
12- async def init_models ():
13- """Create tables if they don't already exist.
14-
15- In a real-life example we would use Alembic to manage migrations.
16- """
17- async with engine .begin () as conn :
18- # await conn.run_sync(Base.metadata.drop_all)
19- await conn .run_sync (Base .metadata .create_all )
20-
21-
2212@asynccontextmanager
2313async def lifespan (app : FastAPI ):
2414 """Run tasks before and after the server starts."""
@@ -29,16 +19,6 @@ async def lifespan(app: FastAPI):
2919app = FastAPI (lifespan = lifespan )
3020
3121
32- async def get_db ():
33- """Get a database session.
34-
35- To be used for dependency injection.
36- """
37- async with async_session () as session :
38- async with session .begin ():
39- yield session
40-
41-
4222@app .get ("/" )
4323async def root ():
4424 """Root endpoint."""
You can’t perform that action at this time.
0 commit comments