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 TodoSchema(Schema): id = fields.Int(dump_only=True) done = fields.Boolean(attribute="is_done", missing=False) user = fields.Nested(UserSchema, exclude=("joined_on", "password"), dump_only=True) content = fields.Str(required=True) posted_on = fields.DateTime(dump_only=True) # Again, add an envelope to responses @post_dump(pass_many=True) def wrap(self, data, many): key = "todos" if many else "todo" return {key: data} # We use make_object to create a new Todo from validated data @post_load def make_object(self, data): if not data: return None return Todo( content=data["content"], is_done=data["is_done"], posted_on=dt.datetime.utcnow(), )
def test_datetime_invalid_serialization(self, value, user): field = fields.DateTime() user.created = value with pytest.raises(ValidationError) as excinfo: field.serialize("created", user) assert excinfo.value.args[ 0] == '"{}" cannot be formatted as a datetime.'.format(value)
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 QuoteSchema(Schema): id = fields.Int(dump_only=True) author = fields.Nested(AuthorSchema, validate=must_not_be_blank) content = fields.Str(required=True, validate=must_not_be_blank) posted_at = fields.DateTime(dump_only=True) # Allow client to pass author's full name in request body # e.g. {"author': 'Tim Peters"} rather than {"first": "Tim", "last": "Peters"} @pre_load def process_author(self, data): author_name = data.get("author") if author_name: first, last = author_name.split(" ") author_dict = dict(first=first, last=last) else: author_dict = {} data["author"] = author_dict return data
class UserSchema(Schema): id = fields.Int(dump_only=True) email = fields.Str( required=True, validate=validate.Email(error="Not a valid email address"), ) password = fields.Str( required=True, validate=[validate.Length(min=6, max=36)], load_only=True, ) joined_on = fields.DateTime(dump_only=True) # Clean up data @pre_load def process_input(self, data): data["email"] = data["email"].lower().strip() return data # We add a post_dump hook to add an envelope to responses @post_dump(pass_many=True) def wrap(self, data, many): key = "users" if many else "user" return {key: data}
class AliasingUserSerializer(Schema): name = fields.String() birthdate = fields.DateTime( default=lambda: dt.datetime(2017, 9, 29))
def test_datetime_format(self, user): format = "%Y-%m-%d" field = fields.DateTime(format=format) assert field.serialize("created", user) == user.created.strftime(format)
def test_datetime_iso8601(self, fmt, user): field = fields.DateTime(format=fmt) expected = utils.isoformat(user.created, localtime=False) assert field.serialize("created", user) == expected
def test_datetime_serializes_to_iso_by_default(self, user): field = fields.DateTime() # No format specified expected = utils.isoformat(user.created, localtime=False) assert field.serialize("created", user) == expected