How to load MariaDB settings from environment using pydantic_settings

Use this code to load MySQL/MariaDB settings from environment variables using the pydantic_settings library:

from pydantic_settings import BaseSettings

class MariaDBSettings(BaseSettings):
    hostname: str = "mariadb"
    user: str = "root"
    password: str = "abc123"
    database: str = "mydb"
    
    class Config:
        env_prefix = 'MARIADB_'

Optionally: if you want to load it from a .env file, you can use load_dotenv from the dotenv library:

# Load environment variables from a .env file if necessary
# This step is optional and only needed if you are using a .env file
from dotenv import load_dotenv
load_dotenv()

Usage example

settings = MariaDBSettings()

print("MARIADB_HOSTNAME:", settings.hostname)
print("MARIADB_USER:", settings.user)
print("MARIADB_PASSWORD:", settings.password)
print("MARIADB_DATABASE:", settings.database)

Example output:

$ ./mariadb_settings.py
MARIADB_HOSTNAME: mariadb
MARIADB_USER: root
MARIADB_PASSWORD: abc123
MARIADB_DATABASE: mydb
$ MARIADB_HOSTNAME=10.1.2.3 ./mariadb_settings.py
MARIADB_HOSTNAME: 10.1.2.3
MARIADB_USER: root
MARIADB_PASSWORD: abc123
MARIADB_DATABASE: mydb