Refactor database connection and add item management endpoints

This commit is contained in:
Felix Zett 2025-08-05 22:23:00 +02:00
parent 4b2d280741
commit 708dc0e96d
3 changed files with 67 additions and 8 deletions

View file

@ -1,8 +1,14 @@
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import sessionmaker, declarative_base
import os
DATABASE_URL = os.environ.get("DATABASE_URL") DATABASE_URL = "postgresql+asyncpg://postgres:postgres@db:5432/packlist"
engine = create_async_engine(DATABASE_URL, echo=True) engine = create_async_engine(DATABASE_URL)
SessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) SessionLocal = sessionmaker(
bind=engine, class_=AsyncSession, expire_on_commit=False
)
Base = declarative_base()
async def get_db():
async with SessionLocal() as db:
yield db

View file

@ -1,9 +1,18 @@
from fastapi import FastAPI from datetime import date
from models import Base from typing import List
from database import engine from uuid import UUID, uuid4
from fastapi import Depends, FastAPI
from pydantic import BaseModel
from sqlalchemy import select
from models import Base, Item, Tag
from database import engine, get_db
from sqlalchemy.ext.asyncio import AsyncSession
app = FastAPI() app = FastAPI()
FIXED_USER_ID = UUID("00000000-0000-0000-0000-000000000001")
@app.on_event("startup") @app.on_event("startup")
async def startup(): async def startup():
@ -14,3 +23,46 @@ async def startup():
@app.get("/") @app.get("/")
def read_root(): def read_root():
return {"status": "running"} return {"status": "running"}
class TagCreate(BaseModel):
name: str
class ItemCreate(BaseModel):
name: str
tag_names: List[str]
class TripCreate(BaseModel):
name: str
start_date: date
end_date: date
selected_tags: List[str]
marked_tags: List[str]
@app.post("/items/")
async def create_item(item: ItemCreate, db: AsyncSession = Depends(get_db)):
user_id = FIXED_USER_ID
db_item = Item(id=uuid4(), name=item.name, user_id=user_id)
tags = []
for tag_name in item.tag_names:
result = await db.execute(select(Tag).where(Tag.name == tag_name, Tag.user_id == user_id))
tag = result.scalar_one_or_none()
if not tag:
tag = Tag(id=uuid4(), name=tag_name, user_id=user_id)
db.add(tag)
tags.append(tag)
db_item.tags = tags
db.add(db_item)
await db.commit()
return {"status": "item created", "item_id": str(db_item.id)}
@app.get("/items/")
async def read_items(db: AsyncSession = Depends(get_db)):
user_id = FIXED_USER_ID
result = await db.execute(select(Item).where(Item.user_id == user_id))
items = result.scalars().all()
return {"items" : [item.name for item in items]}

View file

@ -2,6 +2,7 @@ fastapi
uvicorn[standard] uvicorn[standard]
sqlalchemy sqlalchemy
asyncpg asyncpg
psycopg2-binary
pydantic pydantic
python-dotenv python-dotenv