56 lines
1.3 KiB
Python
56 lines
1.3 KiB
Python
"""SQLAlchemy 2.0 基础模型类与 Mixin。"""
|
|
|
|
import uuid
|
|
from datetime import datetime
|
|
|
|
from sqlalchemy import String, text
|
|
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
|
|
|
|
|
def generate_uuid() -> str:
|
|
"""生成 UUID4 十六进制字符串(32字符)。"""
|
|
return uuid.uuid4().hex
|
|
|
|
|
|
def utcnow_iso() -> str:
|
|
"""当前时间,格式:年-月-日 时:分:秒(容器时区,生产为 Asia/Shanghai)。
|
|
|
|
定长格式保证字符串排序 = 时间排序。
|
|
"""
|
|
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
|
|
class Base(DeclarativeBase):
|
|
"""SQLAlchemy 声明式基类。"""
|
|
pass
|
|
|
|
|
|
class UUIDPrimaryKeyMixin:
|
|
"""UUID 主键 Mixin。"""
|
|
|
|
id: Mapped[str] = mapped_column(
|
|
String(32),
|
|
primary_key=True,
|
|
default=generate_uuid,
|
|
comment="UUID4 十六进制主键",
|
|
)
|
|
|
|
|
|
class TimestampMixin:
|
|
"""创建/更新时间 Mixin。"""
|
|
|
|
created_at: Mapped[str] = mapped_column(
|
|
String(32),
|
|
default=utcnow_iso,
|
|
nullable=False,
|
|
comment="创建时间 (ISO8601)",
|
|
)
|
|
|
|
updated_at: Mapped[str] = mapped_column(
|
|
String(32),
|
|
default=utcnow_iso,
|
|
onupdate=utcnow_iso,
|
|
nullable=False,
|
|
comment="更新时间 (ISO8601)",
|
|
)
|