Pipelinen parannuksia building blockeilla
This commit is contained in:
56
zipit/projekti_clean/main.py
Normal file
56
zipit/projekti_clean/main.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from fastapi import FastAPI, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from models import Base, engine, SessionLocal, Todo
|
||||
from schemas import TodoCreate, TodoResponse
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
app = FastAPI()
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@app.post("/todos/", response_model=TodoResponse, status_code=201)
|
||||
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
|
||||
db_todo = Todo(**todo.model_dump())
|
||||
db.add(db_todo)
|
||||
db.commit()
|
||||
db.refresh(db_todo)
|
||||
return db_todo
|
||||
|
||||
@app.get("/todos/", response_model=list[TodoResponse])
|
||||
def list_todos(status: str | None = None, db: Session = Depends(get_db)):
|
||||
if status:
|
||||
query = db.query(Todo).filter_by(status=status)
|
||||
else:
|
||||
query = db.query(Todo)
|
||||
return query.all()
|
||||
|
||||
@app.get("/todos/{todo_id}", response_model=TodoResponse)
|
||||
def get_todo(todo_id: int, db: Session = Depends(get_db)):
|
||||
todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
||||
if not todo:
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
return todo
|
||||
|
||||
@app.put("/todos/{todo_id}", response_model=TodoResponse)
|
||||
def update_todo(todo_id: int, todo: TodoCreate, db: Session = Depends(get_db)):
|
||||
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
||||
if not db_todo:
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
for key, value in todo.model_dump().items():
|
||||
setattr(db_todo, key, value)
|
||||
db.commit()
|
||||
db.refresh(db_todo)
|
||||
return db_todo
|
||||
|
||||
@app.delete("/todos/{todo_id}", status_code=204)
|
||||
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
|
||||
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
||||
if not db_todo:
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
db.delete(db_todo)
|
||||
db.commit()
|
||||
Reference in New Issue
Block a user