nex_animation/backend/app/models/base.py

35 lines
1.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from __future__ import annotations
from datetime import datetime, timezone
from sqlalchemy import JSON, DateTime
from sqlalchemy.orm import Mapped, mapped_column
def now_utc() -> datetime:
return datetime.now(timezone.utc)
def as_utc(value: datetime | None) -> datetime | None:
"""把「刚从数据库读回来的 datetime」统一成带 UTC 时区的对象。
SQLite 的 `DateTime(timezone=True)` 并不会真的保存偏移量:写进去的是
带时区的值,读出来却是 naive。于是 `session.expires_at > now_utc()`
这种再自然不过的比较会抛
`TypeError: can't compare offset-naive and offset-aware datetimes`,
表现出来就是「一登录就 500」——而这条路径在 AUTH_ENABLED=false 的
部署里根本跑不到,所以必须靠用例兜住。
"""
if value is None:
return None
return value if value.tzinfo is not None else value.replace(tzinfo=timezone.utc)
class TimestampMixin:
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc, onupdate=now_utc, nullable=False)
class JSONDict(JSON):
"""保持语义清晰的 JSON 别名列(存 dict/list)。"""