Last active
April 8, 2018 02:00
-
-
Save sloria/9f6214b37aab3a6aa37e9a361a50cfd8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from copy import deepcopy | |
from marshmallow import Schema, fields | |
def PartialSchemaFactory(schema_cls): | |
schema = schema_cls(partial=True) | |
for field_name, field in schema.fields.items(): | |
if isinstance(field, fields.Nested): | |
new_field = deepcopy(field) | |
new_field.schema.partial = True | |
schema.fields[field_name] = new_field | |
return schema | |
class Address(Schema): | |
street = fields.Str(required=True) | |
city = fields.Str(required=True) | |
state = fields.Str(required=True) | |
zipcode = fields.Str(required=True) | |
country = fields.Str(required=True) | |
class User(Schema): | |
first_name = fields.Str(required=True) | |
last_name = fields.Str(required=True) | |
address = fields.Nested(Address) | |
payload = { | |
'first_name': 'John', | |
'address': { | |
'zipcode': '90210' | |
} | |
} | |
user_schema = PartialSchemaFactory(User) | |
data, errors = user_schema.load(payload) | |
assert errors == {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment