A simple package to transform/map dictionaries, before parsing it into Pydantic.
Project description
Pydantic Model Parser
A simple package to transform/map dictionaries, before parsing it into Pydantic.
Requirements
- The models/entities should conform to
Pydantic's
Model specifications and should inherit thepydantic.BaseModel
.
Installation
pip3 install pydantic-model-parser
Usage
Firstly, define your entity using Pydantic's BaseModel
.
# comment.py
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
class Comment(BaseModel):
id: int
comment_str: str
user: User
Next, define the Mapper
. The mapper can be used to rearrange dictionary keys and perform transformations on the values.
The tuples definitions are as follows:
- (
old_field_path
: str,new_field_path
: str,transform_func
: Optional[Callable]) transform_func
ofNone
maps the value as per the original valuetransform_func
oflambda x: x * 2
maps the value as double of the original valueold_field_path
's value is placed innew_field_path
in the new dictionary and subsequently parsed into theBaseModel
- The
.
in the path delimits the nested levels in the dictionaries. e.g.user.id
refers to:
- The
{
"user": {
"id": 1
}
}
Defining a Mapper:
# comment.py
from model_parser.custom_types import Mapping
from model_parser.mapper import BaseMapper
class CommentMapper(BaseMapper):
@staticmethod
def get_mapping() -> List[Mapping]:
return [
('id', 'id', None),
('comment_str', 'comment_str', None),
('user_name', 'user.name', None),
('user_id', 'user.id', None)
]
Lastly, to parse objects:
# main.py
from comment import Comment, CommentMapper
data = {
"id": 1,
"comment_str": "HelloWorld",
"user_id": 2,
"user_name": "bob"
}
data_list = [data, data]
parser = Parser(Comment, CommentMapper)
# parse into a Comment entity
comment = parser.parse(data)
# parse into a list of Comment entities
comments = parser.parse(data_list)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Close
Hashes for pydantic-model-parser-1.0.1.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 57e1032d4eb2a6f60b7b7b4a24d991b989a7937f01a7ee98ee77906ece02563f |
|
MD5 | e9c087c88c7a0e9411562a98d59f8d3e |
|
BLAKE2b-256 | 9dd6252830fd36a5f2f5363766e6728c6cfd3ae3e3c87171dbe07d194941ceaa |
Close
Hashes for pydantic_model_parser-1.0.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | fb7912040b5f9c404f9a68b9be12303deea18fa1d18e2a2092e55a56c7337f45 |
|
MD5 | b6b5205c8bd73865f8d89e7bae9b91f1 |
|
BLAKE2b-256 | 60ff1d979acdcd949d51ccd2560bac0b68d1b98ee7a6560204b68d775bc47783 |