File size: 3,656 Bytes
194469b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | """Global database models and base classes."""
from datetime import datetime
from typing import Any
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field
class CustomBaseModel(BaseModel):
"""Custom base model with common configurations."""
model_config = ConfigDict(
# Use enum values instead of enum objects
use_enum_values=True,
# Validate assignment
validate_assignment=True,
# Allow population by field name or alias
populate_by_name=True,
# Serialize datetime as ISO format
json_encoders={datetime: lambda v: v.isoformat()},
# Extra fields are forbidden
extra="forbid",
)
def model_dump_json_safe(self, **kwargs: Any) -> dict[str, Any]:
"""Return a dict that is safe for JSON serialization."""
return self.model_dump(mode="json", **kwargs)
class TimestampMixin(BaseModel):
"""Mixin for models with timestamp fields."""
created_at: datetime = Field(description="Creation timestamp")
updated_at: datetime | None = Field(default=None, description="Last update timestamp")
class UUIDMixin(BaseModel):
"""Mixin for models with UUID primary key."""
id: UUID = Field(description="Unique identifier")
class BaseDBModel(CustomBaseModel, UUIDMixin, TimestampMixin):
"""Base model for database entities."""
pass
class PaginationParams(CustomBaseModel):
"""Pagination parameters."""
page: int = Field(default=1, ge=1, description="Page number (1-based)")
size: int = Field(default=20, ge=1, le=100, description="Page size")
@property
def offset(self) -> int:
"""Calculate offset for database queries."""
return (self.page - 1) * self.size
@property
def limit(self) -> int:
"""Get limit for database queries."""
return self.size
class PaginatedResponse(CustomBaseModel):
"""Generic paginated response."""
items: list[Any] = Field(description="List of items")
total: int = Field(description="Total number of items")
page: int = Field(description="Current page number")
size: int = Field(description="Page size")
pages: int = Field(description="Total number of pages")
@classmethod
def create(
cls,
items: list[Any],
total: int,
page: int,
size: int,
) -> "PaginatedResponse":
"""Create a paginated response."""
pages = (total + size - 1) // size # Ceiling division
return cls(
items=items,
total=total,
page=page,
size=size,
pages=pages,
)
class HealthCheck(CustomBaseModel):
"""Health check response model."""
status: str = Field(description="Service status")
timestamp: datetime = Field(description="Check timestamp")
version: str = Field(description="Application version")
environment: str = Field(description="Environment name")
class ErrorResponse(CustomBaseModel):
"""Standard error response model."""
error: str = Field(description="Error type")
message: str = Field(description="Error message")
details: dict[str, Any] | None = Field(default=None, description="Error details")
timestamp: datetime = Field(description="Error timestamp")
path: str | None = Field(default=None, description="Request path")
class SuccessResponse(CustomBaseModel):
"""Standard success response model."""
success: bool = Field(default=True, description="Success flag")
message: str = Field(description="Success message")
data: dict[str, Any] | None = Field(default=None, description="Response data")
|