|
| 1 | +from dataclasses import dataclass, field |
| 2 | +from enum import Enum |
| 3 | +from pathlib import Path |
| 4 | +from typing import Optional |
| 5 | + |
| 6 | +from marshmallow import Schema, fields |
| 7 | +from marshmallow_dataclass import class_schema |
| 8 | + |
| 9 | + |
| 10 | +class Command(Enum): |
| 11 | + CREATE = 'create' |
| 12 | + DELETE = 'delete' |
| 13 | + |
| 14 | + |
| 15 | +class PathField(fields.String): |
| 16 | + def _serialize(self, value, attr, obj, **kwargs) -> Optional[str]: |
| 17 | + if isinstance(value, Path): |
| 18 | + value = str(value) |
| 19 | + |
| 20 | + return super()._serialize(value, attr, obj, **kwargs) |
| 21 | + |
| 22 | + def _deserialize(self, value, attr, data, **kwargs) -> Optional[Path]: |
| 23 | + result = super()._deserialize(value, attr, data, **kwargs) |
| 24 | + |
| 25 | + if result is None: |
| 26 | + return None |
| 27 | + |
| 28 | + return Path(result) |
| 29 | + |
| 30 | + |
| 31 | +Schema.TYPE_MAPPING[Path] = PathField |
| 32 | + |
| 33 | + |
| 34 | +@dataclass |
| 35 | +class Config: |
| 36 | + file_path: Path |
| 37 | + command: Command = field(metadata=dict(by_value=True)) |
| 38 | + bulk_size: int = 20 |
| 39 | + |
| 40 | + |
| 41 | +Config.Schema = class_schema(Config) |
| 42 | + |
| 43 | +json_data = { |
| 44 | + 'file_path': '/validators-example/file', |
| 45 | + 'command': 'create', |
| 46 | +} |
| 47 | + |
| 48 | +config = Config.Schema().load(json_data) |
| 49 | +print(config) |
| 50 | + |
| 51 | +assert config.file_path == Path('/validators-example/file') |
| 52 | +assert config.command is Command.CREATE |
| 53 | +assert config.bulk_size == 20 |
0 commit comments