File tree

4 files changed

+37
-2
lines changed

4 files changed

+37
-2
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
fastapi==0.115.12
22
uvicorn[standard]
3-
requests
3+
requests
4+
sqlmodel
5+
psycopg[binary]
Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import os
2+
3+
import sqlmodel
4+
from sqlmodel import Session, SQLModel
5+
6+
DATABASE_URL = os.environ.get("DATABASE_URL")
7+
8+
if DATABASE_URL == "":
9+
raise NotImplementedError("`DATABASE_URL` needs to be set.")
10+
11+
12+
engine = sqlmodel.create_engine(DATABASE_URL)
13+
14+
# database models
15+
def init_db():
16+
print("creating database tables...")
17+
SQLModel.metadata.create_all(engine)
18+
19+
20+
# api routes
21+
def get_session():
22+
with Session(engine) as session:
23+
yield session
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,17 @@
11
import os
2+
from contextlib import asynccontextmanager
23
from fastapi import FastAPI
34

4-
app = FastAPI()
5+
from api.db import init_db
6+
7+
@asynccontextmanager
8+
async def lifespan(app: FastAPI):
9+
# before app startup
10+
init_db()
11+
yield
12+
# after app startup
13+
14+
app = FastAPI(lifespan=lifespan)
515

616
MY_PROJECT = os.environ.get("MY_PROJECT") or "This is my project"
717
API_KEY = os.environ.get("API_KEY")

0 commit comments

Comments
 (0)