39 lines
1.1 KiB
Python
39 lines
1.1 KiB
Python
"""SQLAlchemy base model."""
|
|
|
|
from datetime import datetime, timezone
|
|
from sqlalchemy import func
|
|
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
|
|
|
|
|
class Base(DeclarativeBase):
|
|
"""Base class for all models."""
|
|
pass
|
|
|
|
|
|
def utcnow():
|
|
"""Return current UTC time as timezone-aware datetime."""
|
|
return datetime.now(timezone.utc)
|
|
|
|
|
|
def format_datetime(dt):
|
|
"""Format datetime as ISO string with UTC marker for API responses.
|
|
|
|
If the datetime is naive (no timezone), assumes UTC and appends Z.
|
|
This ensures JavaScript Date() correctly interprets the timezone.
|
|
"""
|
|
if not dt:
|
|
return None
|
|
# If naive (no timezone), assume UTC and append Z
|
|
if dt.tzinfo is None:
|
|
return dt.isoformat() + "Z"
|
|
return dt.isoformat()
|
|
|
|
|
|
class TimestampMixin:
|
|
"""Mixin for created_at and updated_at timestamps.
|
|
|
|
Uses UTC timestamps for consistency. Frontend should convert to local time.
|
|
"""
|
|
created_at: Mapped[datetime] = mapped_column(default=utcnow)
|
|
updated_at: Mapped[datetime] = mapped_column(default=utcnow, onupdate=utcnow)
|