81 lines
2.2 KiB
Python
81 lines
2.2 KiB
Python
from typing import List
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.database import get_db
|
|
from app.models.item import Item
|
|
from app.schemas.item import Item as ItemSchema
|
|
from app.schemas.item import ItemCreate, ItemUpdate
|
|
|
|
router = APIRouter()
|
|
|
|
@router.get("/", response_model=List[ItemSchema])
|
|
def read_items(
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""Get a list of items."""
|
|
items = db.query(Item).offset(skip).limit(limit).all()
|
|
return items
|
|
|
|
@router.post("/", response_model=ItemSchema, status_code=status.HTTP_201_CREATED)
|
|
def create_item(
|
|
item_in: ItemCreate,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""Create a new item."""
|
|
db_item = Item(
|
|
name=item_in.name,
|
|
description=item_in.description,
|
|
is_active=item_in.is_active
|
|
)
|
|
db.add(db_item)
|
|
db.commit()
|
|
db.refresh(db_item)
|
|
return db_item
|
|
|
|
@router.get("/{item_id}", response_model=ItemSchema)
|
|
def read_item(
|
|
item_id: str,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""Get an item by ID."""
|
|
db_item = db.query(Item).filter(Item.id == item_id).first()
|
|
if db_item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
return db_item
|
|
|
|
@router.put("/{item_id}", response_model=ItemSchema)
|
|
def update_item(
|
|
item_id: str,
|
|
item_in: ItemUpdate,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""Update an item."""
|
|
db_item = db.query(Item).filter(Item.id == item_id).first()
|
|
if db_item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
|
|
update_data = item_in.dict(exclude_unset=True)
|
|
for field, value in update_data.items():
|
|
setattr(db_item, field, value)
|
|
|
|
db.add(db_item)
|
|
db.commit()
|
|
db.refresh(db_item)
|
|
return db_item
|
|
|
|
@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
|
def delete_item(
|
|
item_id: str,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""Delete an item."""
|
|
db_item = db.query(Item).filter(Item.id == item_id).first()
|
|
if db_item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
|
|
db.delete(db_item)
|
|
db.commit()
|
|
return None |