Easily manage settings with Pydantic

During development, configuration files are often needed to easily change the behavior of the system. For example, the switch of Debug mode, database related settings, etc. are usually placed in configuration files.

In addition to the built-in module configparser provided by Python to easily implement configuration files, it can also easily implement configuration files using classes, such as the following two files are examples of configuration

class Settings(object):
    DB_HOST = 'localhost'
    DB_PORT = 8888

settings = Settings()
from settings import settings

print(settings.DB_HOST, settings.DB_PORT)

However, nowadays development projects also often use dotenv (e.g. python-dotenv) to make configuration easier.

In addition to developing the functionality of dotenv by yourself, you can actually choose to integrate class-style configuration files and dotenv easily with pydantic.

Posted on  Jul 1, 2020  in  Useful Python Modules , Python Programming - Advanced Level  by  Amo Chen  ‐ 5 min read