Pipelinen parannuksia building blockeilla
This commit is contained in:
56
zipit/todo_new/main.py
Normal file
56
zipit/todo_new/main.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from fastapi import FastAPI, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from models import Base, engine, SessionLocal, Task
|
||||
from schemas import TaskCreate, TaskResponse
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
app = FastAPI()
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@app.post("/tasks/", response_model=TaskResponse, status_code=201)
|
||||
def create_task(task: TaskCreate, db: Session = Depends(get_db)):
|
||||
db_task = Task(**task.model_dump())
|
||||
db.add(db_task)
|
||||
db.commit()
|
||||
db.refresh(db_task)
|
||||
return db_task
|
||||
|
||||
@app.get("/tasks/", response_model=list[TaskResponse])
|
||||
def list_tasks(status: str | None = Query(None), db: Session = Depends(get_db)):
|
||||
if status:
|
||||
tasks = db.query(Task).filter(Task.status == status).all()
|
||||
else:
|
||||
tasks = db.query(Task).all()
|
||||
return tasks
|
||||
|
||||
@app.get("/tasks/{task_id}", response_model=TaskResponse)
|
||||
def get_task(task_id: int, db: Session = Depends(get_db)):
|
||||
task = db.query(Task).filter(Task.id == task_id).first()
|
||||
if not task:
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
return task
|
||||
|
||||
@app.put("/tasks/{task_id}", response_model=TaskResponse)
|
||||
def update_task(task_id: int, task: TaskCreate, db: Session = Depends(get_db)):
|
||||
db_task = db.query(Task).filter(Task.id == task_id).first()
|
||||
if not db_task:
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
for key, value in task.model_dump().items():
|
||||
setattr(db_task, key, value)
|
||||
db.commit()
|
||||
db.refresh(db_task)
|
||||
return db_task
|
||||
|
||||
@app.delete("/tasks/{task_id}", status_code=204)
|
||||
def delete_task(task_id: int, db: Session = Depends(get_db)):
|
||||
db_task = db.query(Task).filter(Task.id == task_id).first()
|
||||
if not db_task:
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
db.delete(db_task)
|
||||
db.commit()
|
||||
Reference in New Issue
Block a user