Beispiel #1
0
class AuthorSchema(Schema):
    id = fields.Int(dump_only=True)
    first = fields.Str()
    last = fields.Str()
    book_count = fields.Float()
    age = fields.Float()
    address = fields.Str()
    full_name = fields.Method("full_name")

    def full_name(self, obj):
        return obj.first + " " + obj.last

    def format_name(self, author):
        return "{}, {}".format(author.last, author.first)
class BlobSchema(Schema):
    polarity = fields.Float()
    subjectivity = fields.Float()
    chunks = fields.List(fields.String, attribute="noun_phrases")
    tags = fields.Raw()
    discrete_sentiment = fields.Method("get_discrete_sentiment")
    word_count = fields.Function(lambda obj: len(obj.words))

    def get_discrete_sentiment(self, obj):
        if obj.polarity > 0.1:
            return "positive"
        elif obj.polarity < -0.1:
            return "negative"
        else:
            return "neutral"
Beispiel #3
0
 def test_number_fields_prohbits_boolean(self):
     strict_field = fields.Float()
     with pytest.raises(ValidationError) as excinfo:
         strict_field.serialize("value", {"value": False})
     assert excinfo.value.args[0] == "Not a valid number."
     with pytest.raises(ValidationError) as excinfo:
         strict_field.serialize("value", {"value": True})
     assert excinfo.value.args[0] == "Not a valid number."
Beispiel #4
0
    def test_float_field_allow_nan(self, value, allow_nan, user):

        user.key = value

        if allow_nan is None:
            # Test default case is False
            field = fields.Float()
        else:
            field = fields.Float(allow_nan=allow_nan)

        if allow_nan is True:
            res = field.serialize("key", user)
            assert isinstance(res, float)
            if value.endswith("nan"):
                assert math.isnan(res)
            else:
                assert res == float(value)
        else:
            with pytest.raises(ValidationError) as excinfo:
                field.serialize("key", user)
            assert str(excinfo.value.args[0]) == (
                "Special numeric values (nan or infinity) are not permitted.")
Beispiel #5
0
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.Int(dump_only=True)
    book_name = fields.Str()
    page_number = fields.Float()
    line_number = fields.Float()
    col_number = fields.Float()

    # 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
Beispiel #6
0
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)
Beispiel #7
0
class UserFloatStringSchema(UserSchema):
    age = fields.Float(as_string=True)