Skip to content

Instantly share code, notes, and snippets.

@danhodge
Created May 31, 2022 17:19
Show Gist options
  • Save danhodge/9016d4886214e3c73f7ff2e5ecfd44eb to your computer and use it in GitHub Desktop.
Save danhodge/9016d4886214e3c73f7ff2e5ecfd44eb to your computer and use it in GitHub Desktop.
marshmallow notes
# creating a custom field that validates values on serialization/deserialization
class CustomField(object):
# if inheriting from an built-in field like fields.Str
def __init__(self, *args, **kwargs):
super(CustomField, self).__init__(*args, **kwargs)
def _validated(self, value):
"""Format the value or raise a :exc:`ValidationError` if an error occurs."""
if value is None:
return None
# TODO: convert value to expected type and return
raise ValidationError("{} is an invalid".format(value))
def _serialize(self, value, attr, obj):
validated = self._validated(value)
return validated.display_name() if validated is not None else None
def _deserialize(self, value, attr, data):
return self._validated(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment