Skip to content

Commit 041ad50

Browse files
author
Adrian Dankiv
committed
Initial commit
0 parents  commit 041ad50

8 files changed

+235
-0
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Project exclude paths
2+
/.venv/

example1_simple.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from dataclasses import dataclass, field
2+
from enum import Enum
3+
4+
from marshmallow_dataclass import class_schema
5+
6+
7+
class Command(Enum):
8+
CREATE = 'create'
9+
DELETE = 'delete'
10+
11+
12+
@dataclass
13+
class Config:
14+
file_path: str
15+
command: Command = field(metadata=dict(by_value=True))
16+
bulk_size: int = 20
17+
18+
19+
Config.Schema = class_schema(Config)
20+
21+
json_data = {
22+
'file_path': '/validators-example/file',
23+
'command': 'create',
24+
}
25+
26+
config = Config.Schema().load(json_data)
27+
print(config)
28+
print(Config.Schema().dump(config))
29+
30+
assert config.file_path == '/validators-example/file'
31+
assert config.command is Command.CREATE
32+
assert config.bulk_size == 20

example1_simple_many.py

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from dataclasses import dataclass, field
2+
from enum import Enum
3+
4+
from marshmallow_dataclass import class_schema
5+
6+
7+
class Command(Enum):
8+
CREATE = 'create'
9+
DELETE = 'delete'
10+
11+
12+
@dataclass
13+
class Config:
14+
file_path: str
15+
command: Command = field(metadata=dict(by_value=True))
16+
bulk_size: int = 20
17+
18+
19+
Config.Schema = class_schema(Config)
20+
21+
json_data = [
22+
{
23+
'file_path': '/validators-example/file1',
24+
'command': 'create',
25+
},
26+
{
27+
'file_path': '/validators-example/file2',
28+
'command': 'delete',
29+
},
30+
]
31+
32+
configs = Config.Schema().load(json_data, many=True)
33+
print(configs)
34+
35+
assert len(configs) == 2
36+
assert configs[0].file_path == '/validators-example/file1'
37+
assert configs[0].command is Command.CREATE
38+
assert configs[0].bulk_size == 20

example2_nested.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
from dataclasses import dataclass, field
2+
from enum import Enum
3+
4+
from marshmallow_dataclass import class_schema
5+
6+
7+
class Command(Enum):
8+
CREATE = 'create'
9+
DELETE = 'delete'
10+
11+
12+
@dataclass
13+
class DatabaseConfig:
14+
host: str
15+
port: int
16+
username: str
17+
password: str
18+
19+
20+
@dataclass
21+
class Config:
22+
file_path: str
23+
command: Command = field(metadata=dict(by_value=True))
24+
database_config: DatabaseConfig
25+
bulk_size: int = 20
26+
27+
28+
DatabaseConfig.Schema = class_schema(DatabaseConfig)
29+
Config.Schema = class_schema(Config)
30+
31+
json_data = {
32+
'file_path': '/validators-example/file',
33+
'command': 'create',
34+
'database_config': {
35+
'host': 'localhost',
36+
'port': 5432,
37+
'username': 'root',
38+
'password': 'qwerty'
39+
}
40+
}
41+
42+
config = Config.Schema().load(json_data)
43+
print(config)
44+
45+
assert config.file_path == '/validators-example/file'
46+
assert config.command is Command.CREATE
47+
assert config.bulk_size == 20
48+
assert config.database_config.host == 'localhost'
49+
assert config.database_config.port == 5432
50+
assert config.database_config.username == 'root'
51+
assert config.database_config.password == 'qwerty'

example3_validation.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from dataclasses import dataclass
2+
from typing import Any, Dict
3+
4+
from marshmallow import ValidationError, validates_schema, validates
5+
from marshmallow_dataclass import class_schema
6+
7+
8+
@dataclass
9+
class Config:
10+
min_value: int
11+
max_value: int
12+
13+
@validates("min_value")
14+
def validate_min(self, value):
15+
if value < 0:
16+
raise ValidationError("Min value must be greater than 0.")
17+
18+
@validates_schema
19+
def validate_min_max(self, data: Dict[str, Any], partial: bool, many: bool) -> None:
20+
if data['min_value'] > data['max_value']:
21+
raise ValidationError('min_value should be less then max_value')
22+
23+
24+
Config.Schema = class_schema(Config)
25+
26+
json_data = {
27+
'min_value': -20,
28+
'max_value': 15,
29+
}
30+
31+
config = Config.Schema().load(json_data)
32+
print(config)

example4_alias.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from dataclasses import dataclass, field
2+
from enum import Enum
3+
4+
from marshmallow_dataclass import class_schema
5+
6+
7+
class Command(Enum):
8+
CREATE = 'create'
9+
DELETE = 'delete'
10+
11+
12+
@dataclass
13+
class Config:
14+
bulk_size: int = field(metadata=dict(data_key='main_bulk_size'))
15+
16+
17+
Config.Schema = class_schema(Config)
18+
19+
json_data = {
20+
'main_bulk_size': 20
21+
}
22+
23+
config = Config.Schema().load(json_data)
24+
print(config)
25+
26+
assert config.bulk_size == 20

example5_custom_fields.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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

requirements.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
marshmallow-dataclass[enum,union]==8.2.0

0 commit comments

Comments
 (0)