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