class KeepOrder(Schema): class Meta: ordered = True name = fields.String(allow_none=True) email = fields.Email(allow_none=True) age = fields.Integer() created = fields.DateTime() id = fields.Integer(allow_none=True) homepage = fields.Url() birthdate = fields.Date()
class PostSchema(Schema): value = fields.Integer() @post_load def load_none(self, item): return None @post_dump def dump_none(self, item): return None
class Foo(Schema): field = fields.Integer() @pre_dump def hook(s, data): data["generated_field"] = 7 return data class Meta: # Removing generated_field from here drops it from the output fields = ("field", "generated_field")
def test_repr(self): default = "œ∑´" field = fields.Field(default=default, attribute=None) assert repr(field) == ("<fields.Field(default={0!r}, attribute=None, " "validate=None, required=False, " "load_only=False, dump_only=False, " "missing={missing}, allow_none=False, " "error_messages={error_messages})>".format( default, missing=missing, error_messages=field.error_messages)) int_field = fields.Integer(validate=lambda x: True) assert "<fields.Integer" in repr(int_field)
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 ExampleSchema(Schema): """Includes different ways to invoke decorators and set up methods""" TAG = "TAG" value = fields.Integer(as_string=True) # Implicit default raw, pre dump, static method. @pre_dump def increment_value(self, item): item["value"] += 1 return item # Implicit default raw, post dump, class method. @post_dump def add_tag(self, item): item["value"] = self.TAG + item["value"] return item # Explicitly raw, post dump, instance method. @post_dump(pass_many=True) def add_envelope(self, data, many): key = self.get_envelope_key(many) return {key: data} # Explicitly raw, pre load, instance method. @pre_load(pass_many=True) def remove_envelope(self, data, many): key = self.get_envelope_key(many) return data[key] @staticmethod def get_envelope_key(many): return "data" if many else "datum" # Explicitly not raw, pre load, instance method. @pre_load(pass_many=False) def remove_tag(self, item): item["value"] = item["value"][len(self.TAG):] return item # Explicit default raw, post load, instance method. @post_load() def decrement_value(self, item): item["value"] -= 1 return item
class ConfusedDumpToAndAttributeSerializer(Schema): name = fields.String(data_key="FullName") username = fields.String(attribute="uname", data_key="UserName") years = fields.Integer(attribute="le_wild_age", data_key="Years")
class DumpToSchema(Schema): name = fields.String(data_key="NamE") years = fields.Integer(data_key="YearS")
def test_integer_field_default_set_to_none(self, user): user.age = None field = fields.Integer(default=None) assert field.serialize("age", user) is None
def test_integer_field_default(self, user): user.age = None field = fields.Integer(default=0) assert field.serialize("age", user) is None # missing assert field.serialize("age", {}) == 0
def test_integer_as_string_field(self, user): field = fields.Integer(as_string=True) assert field.serialize("age", user) == "42"
def test_integer_field(self, user): field = fields.Integer() assert field.serialize("age", user) == 42
class FooSerializer(Schema): _id = fields.Integer()
class UserIntSchema(UserSchema): age = fields.Integer()