Files
cleveragents-core/simulations/sim2/models.py
T

67 lines
2.2 KiB
Python

from pydantic import BaseModel, Field, validator
from typing import Optional
import re
class BookBase(BaseModel):
title: str = Field(..., min_length=1, max_length=200, description="Book title")
author: str = Field(..., min_length=1, max_length=100, description="Book author")
price: float = Field(..., gt=0, description="Book price (must be positive)")
isbn: str = Field(..., min_length=10, max_length=17, description="ISBN-10 or ISBN-13")
@validator('isbn')
def validate_isbn(cls, v):
# Remove hyphens and spaces for validation
isbn_clean = re.sub(r'[-\s]', '', v)
# Check if it's numeric and correct length
if not isbn_clean.isdigit():
raise ValueError('ISBN must contain only digits, hyphens, and spaces')
if len(isbn_clean) not in [10, 13]:
raise ValueError('ISBN must be 10 or 13 digits long')
return v
@validator('price')
def validate_price(cls, v):
# Round to 2 decimal places for currency
return round(v, 2)
class BookCreate(BookBase):
pass
class BookUpdate(BaseModel):
title: Optional[str] = Field(None, min_length=1, max_length=200)
author: Optional[str] = Field(None, min_length=1, max_length=100)
price: Optional[float] = Field(None, gt=0)
isbn: Optional[str] = Field(None, min_length=10, max_length=17)
@validator('isbn')
def validate_isbn(cls, v):
if v is not None:
isbn_clean = re.sub(r'[-\s]', '', v)
if not isbn_clean.isdigit():
raise ValueError('ISBN must contain only digits, hyphens, and spaces')
if len(isbn_clean) not in [10, 13]:
raise ValueError('ISBN must be 10 or 13 digits long')
return v
@validator('price')
def validate_price(cls, v):
if v is not None:
return round(v, 2)
return v
class Book(BookBase):
id: int = Field(..., description="Unique book identifier")
class Config:
schema_extra = {
"example": {
"id": 1,
"title": "The Python Guide",
"author": "John Doe",
"price": 29.99,
"isbn": "978-0123456789"
}
}