File tree
Expand file treeCollapse file tree4 files changed
+37
-2
lines changed Expand file treeCollapse file tree4 files changed
+37
-2
lines changed Original file line number | Diff line number | Diff line change |
---|
|
1 | 1 | fastapi==0.115.12
|
2 | 2 | uvicorn[standard]
|
3 |
| -requests |
| 3 | +requests |
| 4 | +sqlmodel |
| 5 | +psycopg[binary] |
Original file line number | Diff line number | Diff line change |
---|
|
| 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 number | Diff line number | Diff line change |
---|
|
1 | 1 | import os
|
| 2 | +from contextlib import asynccontextmanager |
2 | 3 | from fastapi import FastAPI
|
3 | 4 |
|
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) |
5 | 15 |
|
6 | 16 | MY_PROJECT = os.environ.get("MY_PROJECT") or "This is my project"
|
7 | 17 | API_KEY = os.environ.get("API_KEY")
|
|
You can’t perform that action at this time.
0 commit comments