96 lines
2.3 KiB
Python
96 lines
2.3 KiB
Python
from typing import Any, List
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app import schemas
|
|
from app.db.session import get_db
|
|
from app.models.item import Item
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("", response_model=List[schemas.Item])
|
|
def read_items(
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
db: Session = Depends(get_db)
|
|
) -> Any:
|
|
"""
|
|
Retrieve items.
|
|
"""
|
|
items = db.query(Item).offset(skip).limit(limit).all()
|
|
return items
|
|
|
|
|
|
@router.post("", response_model=schemas.Item, status_code=status.HTTP_201_CREATED)
|
|
def create_item(
|
|
*, db: Session = Depends(get_db), item_in: schemas.ItemCreate
|
|
) -> Any:
|
|
"""
|
|
Create new item.
|
|
"""
|
|
item = Item(**item_in.model_dump())
|
|
db.add(item)
|
|
db.commit()
|
|
db.refresh(item)
|
|
return item
|
|
|
|
|
|
@router.get("/{item_id}", response_model=schemas.Item)
|
|
def read_item(
|
|
*, db: Session = Depends(get_db), item_id: int
|
|
) -> Any:
|
|
"""
|
|
Get item by ID.
|
|
"""
|
|
item = db.query(Item).filter(Item.id == item_id).first()
|
|
if not item:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Item with ID {item_id} not found"
|
|
)
|
|
return item
|
|
|
|
|
|
@router.put("/{item_id}", response_model=schemas.Item)
|
|
def update_item(
|
|
*, db: Session = Depends(get_db), item_id: int, item_in: schemas.ItemUpdate
|
|
) -> Any:
|
|
"""
|
|
Update an item.
|
|
"""
|
|
item = db.query(Item).filter(Item.id == item_id).first()
|
|
if not item:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Item with ID {item_id} not found"
|
|
)
|
|
|
|
update_data = item_in.model_dump(exclude_unset=True)
|
|
for field, value in update_data.items():
|
|
setattr(item, field, value)
|
|
|
|
db.add(item)
|
|
db.commit()
|
|
db.refresh(item)
|
|
return item
|
|
|
|
|
|
@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
|
def delete_item(
|
|
*, db: Session = Depends(get_db), item_id: int
|
|
) -> Any:
|
|
"""
|
|
Delete an item.
|
|
"""
|
|
item = db.query(Item).filter(Item.id == item_id).first()
|
|
if not item:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Item with ID {item_id} not found"
|
|
)
|
|
|
|
db.delete(item)
|
|
db.commit()
|
|
return None |