You use credentials in your (jupyter) notebook or python script and you are about to check it in to a (git) repository. What’s a quick and easy way to get the credentials into a separate file and load them? Use pydantic_settings
.
Firstly, create a .env
file with key value pairs in it in a similar way to a shell script
# Variables for config
API_KEY=your_super_secret_api_key_here_32_chars_minimum
DATABASE_URL=postgresql://username:password@localhost:5432/database_name
Secondly, add this to your .gitignore
echo .env >> .gitignore
Note that this assumes you are in the root of the repo so if not you will need to adjust the path to the .gitignore
file
from typing import Annotated
from pydantic import Field, PostgresDsn
from pydantic_settings import BaseSettings, SettingsConfigDict
class AppSettings(BaseSettings):
# Config variables saved in a .env in this folder
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
# API key expected to be at least 32 chars
api_key: Annotated[str, Field(min_length=32)]
# Postgres connection string
# We call this DATABASE_URL in our .env file
pg_dsn: Annotated[PostgresDsn, Field(alias="DATABASE_URL")]
def main():
settings = AppSettings()
# Example of printing the various settings
for k, v in settings.model_dump().items():
print(f"{k}: {v}")
if __name__ == "__main__":
main()