Provides a complete OpenAPI-first CRUD example with a Pydantic model layer, explicit runtime semantics, and integration tests to support developer onboarding and real-world service structure.
45 lines
925 B
Python
45 lines
925 B
Python
"""
|
|
In-memory data store using Pydantic models.
|
|
|
|
This module is NOT thread-safe and is intended for demos and scaffolds only.
|
|
"""
|
|
|
|
from typing import Dict
|
|
|
|
from models import Item, ItemCreate
|
|
|
|
_items: Dict[int, Item] = {
|
|
1: Item(id=1, name="Apple", price=0.5),
|
|
2: Item(id=2, name="Banana", price=0.3),
|
|
}
|
|
|
|
_next_id = 3
|
|
|
|
|
|
def list_items() -> list[Item]:
|
|
return list(_items.values())
|
|
|
|
|
|
def get_item(item_id: int) -> Item:
|
|
return _items[item_id]
|
|
|
|
|
|
def create_item(payload: ItemCreate) -> Item:
|
|
global _next_id
|
|
item = Item(id=_next_id, **payload.model_dump())
|
|
_items[_next_id] = item
|
|
_next_id += 1
|
|
return item
|
|
|
|
|
|
def update_item(item_id: int, payload: ItemCreate) -> Item:
|
|
if item_id not in _items:
|
|
raise KeyError(item_id)
|
|
item = Item(id=item_id, **payload.model_dump())
|
|
_items[item_id] = item
|
|
return item
|
|
|
|
|
|
def delete_item(item_id: int) -> None:
|
|
del _items[item_id]
|