How to read field values from environment variables with pydantic?
To read values and secrets from environment variables we can use python's os module. Another option is a model class based on pydantic.BaseSettings. The nice thing with BaseSettings is that by default it tries to read field values from environment variables that are either named exactly like the field name in all caps, defined by Field.env, or defined by the model class config. In addition, we can also decide to pass the values as kwargs during instantiation of the model class which then has precedence over the values from the environment variables. If we do not have the expected environment variables set and no arguments are passed during init, pydantic throws a ValidationError.
dependencies: python3.9, pydantic==1.9.2
Comments
Post a Comment