[PYTHON] Notes on how to use marshmallow in the schema library

marshmallow ?

This library. schema library.

Read quick start

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).

schema definition

from marshmallow import Schema, fields

#schema definition
class Perseon(Schema):
    name = fields.String()
    age = fields.Integer()

Use of schema (load / dump)

# 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({})

Story after reading

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`

strict mode is false by default

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

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 added

This 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",)

dump by default ʻupdate_fields = True`

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

Notes on how to use marshmallow in the schema library
How to use the C library in Python
Notes on how to use pywinauto
Notes on how to use doctest
[Hyperledger Iroha] Notes on how to use the Python SDK
How to use Python Image Library in python3 series
How to use the graph drawing library Bokeh
How to use the decorator
Notes on transactions in the Java client library in the datastore
A memorandum on how to use keras.preprocessing.image in Keras
[Python] How to use the graph creation library Altair
How to use the exists clause in Django's queryset
Autoencoder with Chainer (Notes on how to use + trainer)
How to use the model learned in Lobe in Python
How to use the Rubik's Cube solver library "kociemba"
How to use the zip function
How to use the optparse module
How to debug the Python standard library in Visual Studio
[python] How to use the library Matplotlib for drawing graphs
How to use classes in Theano
How to use Dataiku on Windows
How to use the __call__ method in a Python class
How to use VS Code in venv environment on windows
How to use homebrew on Debian
[Python] How to import the library
How to use Mysql in python
How to use ChemSpider in Python
How to use PubChem in Python
Notes on how to use StatsModels that can use linear regression and GLM in python
How to use the ConfigParser module
Notes on how to write requirements.txt
How to use python put in pyenv on macOS with PyCall
How to use the asterisk (*) in Python. Maybe this is all? ..
[Beginner memo] How to specify the library reading path in Python
How to use the render function defined in .mako (.html) directly in mako
How to use calculated columns in CASTable
[Introduction to Python] How to use class in Python?
How to use the Spark ML pipeline
How to use mecab, neologd-ipadic on colab
How to use Google Test in C
[Linux] How to use the echo command
How to use Google Assistant on Windows 10
Memorandum on how to use gremlin python
How to use Anaconda interpreter in PyCharm
How to use __slots__ in Python class
How to use the IPython debugger (ipdb)
How to use regular expressions in Python
How to use Map in Android ViewPager
How to use is and == in Python
How to use MkDocs for the first time
How to use Python Kivy ④ ~ Execution on Android ~
Summary of how to use MNIST in Python
How to use the Google Cloud Translation API
How to use the NHK program guide API
[Algorithm x Python] How to use the list
How to get the files in the [Python] folder
How to use tkinter with python in pyenv
How to use PyTorch-based image processing library "Kornia"
Use the LibreOffice app in Python (3) Add library
Use pygogo to get the log in json.
How to pass the path to the library built with pyenv and virtualenv in PyCharm