class PackageSchema(Schema): name = fields.Str(required=True) version = Version(required=True) description = fields.Str(required=True) main = fields.Str(required=False) homepage = fields.URL(required=False) scripts = fields.Dict(keys=fields.Str(), values=fields.Str()) license = fields.Str(required=True) dependencies = fields.Dict(keys=fields.Str(), values=fields.Str(), required=False) dev_dependencies = fields.Dict( keys=fields.Str(), values=fields.Str(), required=False, data_key="devDependencies", ) class Meta: # Include unknown fields in the # deserialized output unknown = INCLUDE
class UserMetaSchema(Schema): """The equivalent of the UserSchema, using the ``fields`` option.""" uppername = Uppercased(attribute="name", dump_only=True) balance = fields.Decimal() is_old = fields.Method("get_is_old") lowername = fields.Function(get_lowername) updated_local = fields.LocalDateTime(attribute="updated", dump_only=True) species = fields.String(attribute="SPECIES") homepage = fields.Url() email = fields.Email() various_data = fields.Dict() def get_is_old(self, obj): if obj is None: return missing if isinstance(obj, dict): age = obj.get("age") else: age = obj.age try: return age > 80 except TypeError as te: raise ValidationError(str(te)) class Meta: fields = ( "name", "age", "created", "updated", "id", "homepage", "uppername", "email", "balance", "is_old", "lowername", "updated_local", "species", "registered", "hair_colors", "sex_choices", "finger_count", "uid", "time_registered", "birthdate", "since_created", "various_data", )
class UserSchema(Schema): name = fields.String() age = fields.Float() created = fields.DateTime() created_formatted = fields.DateTime(format="%Y-%m-%d", attribute="created", dump_only=True) created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) updated = fields.DateTime() updated_local = fields.LocalDateTime(attribute="updated", dump_only=True) species = fields.String(attribute="SPECIES") id = fields.String(default="no-id") uppername = Uppercased(attribute="name", dump_only=True) homepage = fields.Url() email = fields.Email() balance = fields.Decimal() is_old = fields.Method("get_is_old") lowername = fields.Function(get_lowername) registered = fields.Boolean() hair_colors = fields.List(fields.Raw) sex_choices = fields.List(fields.Raw) finger_count = fields.Integer() uid = fields.UUID() time_registered = fields.Time() birthdate = fields.Date() activation_date = fields.Date() since_created = fields.TimeDelta() sex = fields.Str(validate=validate.OneOf(["male", "female"])) various_data = fields.Dict() class Meta: render_module = simplejson def get_is_old(self, obj): if obj is None: return missing if isinstance(obj, dict): age = obj.get("age") else: age = obj.age try: return age > 80 except TypeError as te: raise ValidationError(str(te)) @post_load def make_user(self, data): return User(**data)
class MySchema(Schema): foo = fields.Dict(keys=fields.Str(), values=fields.Int())
def test_structured_dict_validates(self, user): user.various_data = {"foo": "bar"} field = fields.Dict(values=fields.Decimal) with pytest.raises(ValidationError): field.serialize("various_data", user)
def test_structured_dict_key_value_serialize(self, user): user.various_data = {1: decimal.Decimal("1")} field = fields.Dict(keys=fields.Str, values=fields.Decimal) assert field.serialize("various_data", user) == {"1": 1}
def test_structured_dict_key_serialize(self, user): user.various_data = {1: "bar"} field = fields.Dict(keys=fields.Str) assert field.serialize("various_data", user) == {"1": "bar"}
def test_dict_field_serialize_ordereddict(self, user): user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) field = fields.Dict() assert field.serialize("various_data", user) == OrderedDict([("foo", "bar"), ("bar", "baz")])
def test_dict_field_serialize(self, user): user.various_data = {"foo": "bar"} field = fields.Dict() assert field.serialize("various_data", user) == {"foo": "bar"}
def test_dict_field_invalid_dict_but_okay(self, user): user.various_data = "okaydict" field = fields.Dict() field.serialize("various_data", user) assert field.serialize("various_data", user) == "okaydict"
def test_dict_field_serialize_none(self, user): user.various_data = None field = fields.Dict() assert field.serialize("various_data", user) is None