Member-only story
How To Configure The Settings of Your Python App With Pydantic
Pydantic is a popular Python library that is commonly used for data parsing and validation. However, it is also very useful for configuring the settings of a project, by using the BaseSettings class.
In this article we will see how the BaseSettings class works, and how to implement settings configuration with it.
The BaseSettings class of the Pydantic package allows you to define all of the settings/secrets your project will need such as third party API keys, DB passwords etc. The implementation is very straightforward. You create a class that inherits from it and in it you specify all the fields that your application will use. You also specify the types, which will validate if the values are of the expected format. For example:
from pydantic import BaseSettings
class Settings(BaseSettings):
API_KEY: str = 'some_secret'
DB_URL: str = 'some db url'
Now we load these settings into our app:
from settings import Settings
if __name__ == '__main__':
app_settings = Settings()
print(f'The API key is {app_settings.API_KEY}')
print(f'The Db url is {app_settings.DB_URL}')
and we get the expected result:
~/$ python3 app.py
The API key is some_secret
The Db url is some db…