60 lines
1.8 KiB
Python
60 lines
1.8 KiB
Python
from typing import List, Optional
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
from sqlmodel import Session, select
|
|
from app.database import get_session
|
|
from app.models.astuce import Astuce
|
|
|
|
router = APIRouter(tags=["astuces"])
|
|
|
|
|
|
@router.get("/astuces", response_model=List[Astuce])
|
|
def list_astuces(
|
|
entity_type: Optional[str] = Query(None),
|
|
entity_id: Optional[int] = Query(None),
|
|
session: Session = Depends(get_session),
|
|
):
|
|
q = select(Astuce)
|
|
if entity_type:
|
|
q = q.where(Astuce.entity_type == entity_type)
|
|
if entity_id is not None:
|
|
q = q.where(Astuce.entity_id == entity_id)
|
|
return session.exec(q).all()
|
|
|
|
|
|
@router.post("/astuces", response_model=Astuce, status_code=status.HTTP_201_CREATED)
|
|
def create_astuce(a: Astuce, session: Session = Depends(get_session)):
|
|
session.add(a)
|
|
session.commit()
|
|
session.refresh(a)
|
|
return a
|
|
|
|
|
|
@router.get("/astuces/{id}", response_model=Astuce)
|
|
def get_astuce(id: int, session: Session = Depends(get_session)):
|
|
a = session.get(Astuce, id)
|
|
if not a:
|
|
raise HTTPException(404, "Astuce introuvable")
|
|
return a
|
|
|
|
|
|
@router.put("/astuces/{id}", response_model=Astuce)
|
|
def update_astuce(id: int, data: Astuce, session: Session = Depends(get_session)):
|
|
a = session.get(Astuce, id)
|
|
if not a:
|
|
raise HTTPException(404, "Astuce introuvable")
|
|
for k, v in data.model_dump(exclude_unset=True, exclude={"id", "created_at"}).items():
|
|
setattr(a, k, v)
|
|
session.add(a)
|
|
session.commit()
|
|
session.refresh(a)
|
|
return a
|
|
|
|
|
|
@router.delete("/astuces/{id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
def delete_astuce(id: int, session: Session = Depends(get_session)):
|
|
a = session.get(Astuce, id)
|
|
if not a:
|
|
raise HTTPException(404, "Astuce introuvable")
|
|
session.delete(a)
|
|
session.commit()
|