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 7
7
engine = create_async_engine (DATABASE_URL , echo = False )
8
8
Base = declarative_base ()
9
9
async_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 5
5
from fastapi import Depends , FastAPI
6
6
from sqlalchemy import select
7
7
8
- from db import Base , async_session , engine
8
+ from db import get_db , init_models
9
9
from models import User
10
10
11
11
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
-
22
12
@asynccontextmanager
23
13
async def lifespan (app : FastAPI ):
24
14
"""Run tasks before and after the server starts."""
@@ -29,16 +19,6 @@ async def lifespan(app: FastAPI):
29
19
app = FastAPI (lifespan = lifespan )
30
20
31
21
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
-
42
22
@app .get ("/" )
43
23
async def root ():
44
24
"""Root endpoint."""
You can’t perform that action at this time.
0 commit comments