marshmallow ?
This library. schema library.
Read quick start
It's written in quite detail, so it's good to read it.
The rough usage is as follows (quick start is more detailed).
from marshmallow import Schema, fields
#schema definition
class Perseon(Schema):
name = fields.String()
age = fields.Integer()
# load(json.Load-like image)
data, errs = Person().load({"name": "foo", "age": "10"})
# dump
dumped, errs = Person().dump(data)
The values returned by load ()
and dump ()
are namedtuples with data, errors
as their values. So you can also write Person.dump (data) .data
etc.
strict mode
By default, no error occurs even if validation is caught. Enable strict mode to make an error.
Person(strict=True).load({})
Note the following points
--By default, strict mode is false
--Values that do not exist in the schema definition are automatically deleted
--required = True
must be explicitly added to be required
--By default dump ʻupdate_fields = True`
Personally, true is good for default, so basically I set strict = True in Meta.
class Person(Schema):
name = fields.String()
class Meta:
strict = True
Person().load({}) # marshmallow.ValidationError
When you want to remove the strict, you explicitly pass strict = False
.
data, err = Person(strict=False).load({})
Values that do not exist in the schema definition are automatically deleted. Note that you have to define the necessary fields firmly.
class Person(Schema):
name = fields.String()
data, _ = Person().load({"name": "foo", "age": 20})
print(data) # => {"name": "foo"}
required = True
cannot be required unless explicitly addedThis name cannot be required. You have to explicitly add required.
class Person(Schema):
name = fields.String()
like this.
class Person(Schema):
name = fields.String(required=True)
This also applies when specifying fields in Meta. So you can't define required fields in Meta.fields
class Person(Schema):
class Meta:
filds = ("name",)
This is a small story. Be careful if you want to benchmark performance. By default, marshmallow has update_fields set to true. This is a function that uses the value of the passed data to change the handling of automatically defined types such as field in a nice way. For example, after passing a number, it's just like fields.Field becomes fields.Integer.
It's convenient, though. It is a process that takes a lot of load, so if you are concerned about the speed, you should turn it off. It seems that it cannot be specified with meta.
schema.dump(data, update_fields=False)
If you have a problem, read the source code to solve it.
Recommended Posts