
- Add email-validator to requirements.txt - Add fallback email validation for user and supplier schemas - Implement graceful handling when email-validator is not installed
65 lines
1.5 KiB
Python
65 lines
1.5 KiB
Python
import re
|
|
from typing import Optional
|
|
from pydantic import BaseModel, validator
|
|
|
|
# Try to import EmailStr, but fallback to str if email-validator is not installed
|
|
try:
|
|
from pydantic import EmailStr
|
|
email_type = EmailStr
|
|
except ImportError:
|
|
email_type = str
|
|
|
|
|
|
# Shared properties
|
|
class SupplierBase(BaseModel):
|
|
name: Optional[str] = None
|
|
contact_name: Optional[str] = None
|
|
email: Optional[email_type] = None
|
|
phone: Optional[str] = None
|
|
address: Optional[str] = None
|
|
website: Optional[str] = None
|
|
notes: Optional[str] = None
|
|
|
|
# Add email validation if using fallback str type
|
|
@validator('email')
|
|
def validate_email(cls, v):
|
|
if v is None:
|
|
return v
|
|
|
|
if not isinstance(v, str):
|
|
return v
|
|
|
|
# Basic email validation pattern
|
|
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
|
|
if not re.match(pattern, v):
|
|
raise ValueError('Invalid email format')
|
|
return v
|
|
|
|
|
|
# Properties to receive on supplier creation
|
|
class SupplierCreate(SupplierBase):
|
|
name: str
|
|
|
|
|
|
# Properties to receive on supplier update
|
|
class SupplierUpdate(SupplierBase):
|
|
pass
|
|
|
|
|
|
# Properties shared by models in DB
|
|
class SupplierInDBBase(SupplierBase):
|
|
id: int
|
|
name: str
|
|
|
|
class Config:
|
|
from_attributes = True
|
|
|
|
|
|
# Properties to return to client
|
|
class Supplier(SupplierInDBBase):
|
|
pass
|
|
|
|
|
|
# Properties properties stored in DB
|
|
class SupplierInDB(SupplierInDBBase):
|
|
pass |