57 lines
1.7 KiB
Python
57 lines
1.7 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.plant import Plant
|
|
|
|
router = APIRouter(tags=["plantes"])
|
|
|
|
|
|
@router.get("/plants", response_model=List[Plant])
|
|
def list_plants(
|
|
categorie: Optional[str] = Query(None),
|
|
session: Session = Depends(get_session),
|
|
):
|
|
q = select(Plant)
|
|
if categorie:
|
|
q = q.where(Plant.categorie == categorie)
|
|
return session.exec(q).all()
|
|
|
|
|
|
@router.post("/plants", response_model=Plant, status_code=status.HTTP_201_CREATED)
|
|
def create_plant(p: Plant, session: Session = Depends(get_session)):
|
|
session.add(p)
|
|
session.commit()
|
|
session.refresh(p)
|
|
return p
|
|
|
|
|
|
@router.get("/plants/{id}", response_model=Plant)
|
|
def get_plant(id: int, session: Session = Depends(get_session)):
|
|
p = session.get(Plant, id)
|
|
if not p:
|
|
raise HTTPException(404, "Plante introuvable")
|
|
return p
|
|
|
|
|
|
@router.put("/plants/{id}", response_model=Plant)
|
|
def update_plant(id: int, data: Plant, session: Session = Depends(get_session)):
|
|
p = session.get(Plant, id)
|
|
if not p:
|
|
raise HTTPException(404, "Plante introuvable")
|
|
for k, v in data.model_dump(exclude_unset=True, exclude={"id", "created_at"}).items():
|
|
setattr(p, k, v)
|
|
session.add(p)
|
|
session.commit()
|
|
session.refresh(p)
|
|
return p
|
|
|
|
|
|
@router.delete("/plants/{id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
def delete_plant(id: int, session: Session = Depends(get_session)):
|
|
p = session.get(Plant, id)
|
|
if not p:
|
|
raise HTTPException(404, "Plante introuvable")
|
|
session.delete(p)
|
|
session.commit()
|