51 lines
1.7 KiB
Python
51 lines
1.7 KiB
Python
from typing import List
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlmodel import Session, select
|
|
from app.database import get_session
|
|
from app.models.plant import PlantVariety
|
|
|
|
router = APIRouter(tags=["variétés"])
|
|
|
|
|
|
@router.get("/varieties", response_model=List[PlantVariety])
|
|
def list_varieties(session: Session = Depends(get_session)):
|
|
return session.exec(select(PlantVariety)).all()
|
|
|
|
|
|
@router.post("/varieties", response_model=PlantVariety, status_code=status.HTTP_201_CREATED)
|
|
def create_variety(v: PlantVariety, session: Session = Depends(get_session)):
|
|
session.add(v)
|
|
session.commit()
|
|
session.refresh(v)
|
|
return v
|
|
|
|
|
|
@router.get("/varieties/{id}", response_model=PlantVariety)
|
|
def get_variety(id: int, session: Session = Depends(get_session)):
|
|
v = session.get(PlantVariety, id)
|
|
if not v:
|
|
raise HTTPException(status_code=404, detail="Variété introuvable")
|
|
return v
|
|
|
|
|
|
@router.put("/varieties/{id}", response_model=PlantVariety)
|
|
def update_variety(id: int, data: PlantVariety, session: Session = Depends(get_session)):
|
|
v = session.get(PlantVariety, id)
|
|
if not v:
|
|
raise HTTPException(status_code=404, detail="Variété introuvable")
|
|
for k, val in data.model_dump(exclude_unset=True, exclude={"id", "created_at"}).items():
|
|
setattr(v, k, val)
|
|
session.add(v)
|
|
session.commit()
|
|
session.refresh(v)
|
|
return v
|
|
|
|
|
|
@router.delete("/varieties/{id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
def delete_variety(id: int, session: Session = Depends(get_session)):
|
|
v = session.get(PlantVariety, id)
|
|
if not v:
|
|
raise HTTPException(status_code=404, detail="Variété introuvable")
|
|
session.delete(v)
|
|
session.commit()
|