コード例 #1
0
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
コード例 #2
0
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",
        )
コード例 #3
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)
コード例 #4
0
ファイル: test_fields.py プロジェクト: CyberGRX/marshmallow
 class MySchema(Schema):
     foo = fields.Dict(keys=fields.Str(), values=fields.Int())
コード例 #5
0
 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)
コード例 #6
0
 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}
コード例 #7
0
 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"}
コード例 #8
0
 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")])
コード例 #9
0
 def test_dict_field_serialize(self, user):
     user.various_data = {"foo": "bar"}
     field = fields.Dict()
     assert field.serialize("various_data", user) == {"foo": "bar"}
コード例 #10
0
 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"
コード例 #11
0
 def test_dict_field_serialize_none(self, user):
     user.various_data = None
     field = fields.Dict()
     assert field.serialize("various_data", user) is None