我在使用attrs / cattrs将自定义数据类转换为JSON格式时遇到问题。我的班级形式为:

@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转换为cattrs.unstructure并通过cattrs.structure cattrs转换为ValueError: Unsupported type: <class 'datetime.datetime'>. Register a structure hook for it.时,显示一条错误告诉我应该使用钩子:

# 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


TypeError: strptime() argument 1 must be str, not datetime.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))


但随后出现以下错误%Y-%m-%d %H:%M:%S

我需要能够使用格式为的datetime从对象实例转换为JSON,然后再转换为JSON,如何实现?

最佳答案

问题出在Set类型。如果类型中存在它,则cattr.unstructure无法序列化它。将其替换为元组,事情将解决:

from typing import Tuple, Set
from datetime import datetime

import cattr
import attr
import pytest


TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
COMPLEX_TYPE = Tuple[Tuple[str, datetime]]
COMPLEX_TYPE_BAD = Set[Tuple[str, datetime]]

cattr.register_unstructure_hook(
    datetime, lambda dt: datetime.strftime(dt, format=TIME_FORMAT)
)
cattr.register_structure_hook(
    datetime, lambda dt_str, _: datetime.strptime(dt_str, TIME_FORMAT)
)


def test_cattrs_io_for_a():
    @attr.s(auto_attribs=True)
    class A:
        ds: datetime = attr.ib(factory=datetime.utcnow)

    a = A()
    a_ser = cattr.unstructure(a)
    a_des = cattr.structure(a_ser, A)
    assert isinstance(a_des, A)


def test_cattrs_io_for_b():
    @attr.s(auto_attribs=True)
    class B:
        ds: COMPLEX_TYPE = attr.ib(factory=set)

    b = B((("a", datetime.utcnow()), ("b", datetime.utcnow())))
    b_ser = cattr.unstructure(b)
    b_des = cattr.structure(b_ser, B)
    assert isinstance(b_des, B)


def test_cattrs_io_for_b_bad():
    @attr.s(auto_attribs=True)
    class B:
        ds: COMPLEX_TYPE_BAD = attr.ib(factory=set)

    b = B({("a", datetime.utcnow()), ("b", datetime.utcnow())})
    b_ser = cattr.unstructure(b)
    with pytest.raises(TypeError):
        b_des = cattr.structure(b_ser, B)
        assert isinstance(b_des, B)


在cattrs https://github.com/Tinche/cattrs/issues/48中看起来像是一个问题

将在cattrs的下一版本中修复。或者您可以从master分支构建它

07-27 13:50