author.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. """作者领域模型 —— Author 数据类及其序列化/反序列化."""
  2. from dataclasses import dataclass
  3. from typing import Any
  4. @dataclass
  5. class Author:
  6. name: str
  7. affiliation: str | None = None
  8. email: str | None = None
  9. orcid: str | None = None
  10. db_id: int | None = None
  11. def to_dict(self) -> dict[str, Any]:
  12. d: dict[str, Any] = {
  13. "name": self.name,
  14. "affiliation": self.affiliation,
  15. "email": self.email,
  16. "orcid": self.orcid,
  17. }
  18. if self.db_id is not None:
  19. d["db_id"] = int(self.db_id)
  20. return d
  21. @classmethod
  22. def from_dict(cls, data: dict[str, Any]) -> "Author":
  23. raw_id = data.get("db_id")
  24. db_id: int | None = None
  25. if raw_id is not None:
  26. try:
  27. db_id = int(raw_id)
  28. except Exception:
  29. db_id = None
  30. return cls(
  31. name=data.get("name", ""),
  32. affiliation=data.get("affiliation"),
  33. email=data.get("email"),
  34. orcid=data.get("orcid"),
  35. db_id=db_id,
  36. )