python-dotenv
environment management
Links
python-dotenv
is a Python library that reads key-value pairs from a .env
file and can set them as environment variables. It helps in the development of applications following the 12-factor principles by managing configurations separately from the codebase.
oaicite:0
Usage Example
-
Install the package:
pip install python-dotenv
-
Create a
.env
file:DATABASE_URL=postgres://user:password@localhost/dbname SECRET_KEY=your_secret_key DEBUG=True
-
Load environment variables in your Python script:
import os from dotenv import load_dotenv load_dotenv() # Load variables from .env file database_url = os.getenv('DATABASE_URL') secret_key = os.getenv('SECRET_KEY') debug_mode = os.getenv('DEBUG') print(f"Database URL: {database_url}") print(f"Secret Key: {secret_key}") print(f"Debug Mode: {debug_mode}")
This script loads the environment variables from the
.env
file and prints their values.oaicite:1