Skip to content

Instantly share code, notes, and snippets.

@sloria
Last active April 8, 2018 02:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sloria/9f6214b37aab3a6aa37e9a361a50cfd8 to your computer and use it in GitHub Desktop.
Save sloria/9f6214b37aab3a6aa37e9a361a50cfd8 to your computer and use it in GitHub Desktop.
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