我在使用attrs
/cattrs
将自定义数据类转换为 JSON 格式时遇到问题。我的班级有以下形式:
import attr
from datetime import datetime
from typing import Tuple, Set, Dict, FrozenSet
@attr.s(auto_attribs=True)
class B:
w: Set[datetime] = attr.ib()
x: Set[str] = attr.ib()
y: Set['A'] = attr.ib()
z: Set[Tuple[datetime, str]] = attr.ib(factory=set)
@attr.s(auto_attribs=True, cmp=False)
class A:
a: str = attr.ib()
b: FrozenSet[Team] = attr.ib()
c: FrozenSet[Tuple[datetime, str]] = attr.ib(factory=frozenset)
d: Dict[Tuple[str, str], float] = attr.ib(factory=dict)
我面临的问题是,当我尝试转换为dict
via cattrs.unstructure
,反之亦然 viacattrs.structure
时,cattrs
会显示一个错误,告诉我应该使用钩子:
import cattr
# Create instance of b
b_instance = B(...)
...
data = cattr.unstructure(b_instance)
print()
print(data)
print()
restored = cattr.structure(data, B)
assert b_instance == restored
ValueError: Unsupported type: <class 'datetime.datetime'>. Register a structure hook for it.
我注册了一个钩子来datetime
用str
给定的格式转换为:
import cattr
from datetime import datetime
time_format = '%Y-%m-%d %H:%M:%S'
cattr.register_unstructure_hook(datetime, lambda dt: dt.strftime(time_format))
cattr.register_structure_hook(datetime, lambda s, _: datetime.strptime(s, time_format))
但后来我收到以下错误:
TypeError: strptime() argument 1 must be str, not datetime.datetime
我需要能够使用格式为的日期时间从对象实例转换为 JSON 并返回%Y-%m-%d %H:%M:%S
。我怎样才能做到这一点?