Keeping sensitive data (API keys, client secrets, database credentials) out of your codebase is essential for security. Use environment variables and a .env file to store secrets, and load them in Python using the pydantic-settings package.
uv add pydantic-settings
Create a settings class to load secrets from your .env file:
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
CLIENT_ID: str
CLIENT_SECRET: str
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
settings = Settings() # type: ignore
Access your secrets anywhere in your project:
from src.settings import settings
print(settings.CLIENT_ID)
print(settings.CLIENT_SECRET)
.env FileAdd your secrets to a .env file (never commit this file to version control):
CLIENT_ID=your_client_id_here
CLIENT_SECRET=your_client_secret_here
.env to your .gitignore:To use secrets in Jupyter, load the .env file with the dotenv extension:
%load_ext dotenv
%dotenv
from src.settings import settings
print(settings.CLIENT_ID)