序列化

使用marshmallow_dataclass拓展

"""marshmallow_dataclass拓展"""
from typing import ClassVar, Type, List, Optional
from dataclasses import field

import marshmallow.validate
from marshmallow_dataclass import dataclass
from marshmallow import Schema


@dataclass
class Point:
    x: float
    y: float

    Schema: ClassVar[Type[Schema]] = Schema


# 序列化
def test_dump():
    assert Point.Schema().dump(Point(4, 2)) == {'x': 4, 'y': 2}


@dataclass
class Building:
    # 校验
    height: float = field(metadata={"validate": marshmallow.validate.Range(min=0)})
    name: str = field(default="anonymous")
    Schema: ClassVar[Type[Schema]] = Schema


@dataclass
class City:
    name: Optional[str]
    buildings: List[Building] = field(default=list)
    Schema: ClassVar[Type[Schema]] = Schema


def test_load():
    schema = City.Schema()
    city: City = schema.load({"name": "Paris", "buildings": [{"name": "Eiffel Tower", "height": 324}]})
    assert city.name == "Paris"
    assert isinstance(city.buildings[0], Building)