python-decouple

3.8 · active · verified Thu Apr 09

python-decouple provides a clean, strict separation of configuration settings from code, inspired by The Twelve-Factor App methodology. It allows you to store parameters in environment variables, `.env` files, or `settings.ini` files, making it easy to manage different environments (development, staging, production). The current version is 3.8, and it sees active maintenance with minor releases typically a few times a year addressing bug fixes and minor improvements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `decouple.config` to load settings from a `.env` file (or environment variables). It shows retrieving a simple string, casting a boolean, providing a default value, and parsing a comma-separated string into a list using a custom cast function. `decouple` automatically looks for `.env` or `settings.ini` files in the current directory or parent directories.

import os
from decouple import config

# Create a dummy .env file for demonstration
with open('.env', 'w') as f:
    f.write('DATABASE_URL=postgres://user:pass@host:5432/dbname\n')
    f.write('DEBUG=True\n')
    f.write('SECRET_KEY="my_secret_key"\n')
    f.write('ALLOWED_HOSTS=localhost,127.0.0.1\n')

# Read a setting from .env or environment variable
db_url = config('DATABASE_URL')
print(f"Database URL: {db_url}")

# Read a boolean setting, casting it
debug = config('DEBUG', cast=bool)
print(f"Debug mode: {debug} (type: {type(debug)})")

# Read a string with a default value if not found
api_key = config('API_KEY', default='default_api_key')
print(f"API Key: {api_key}")

# Read a list using Csv cast
hosts = config('ALLOWED_HOSTS', cast=lambda v: v.split(','))
print(f"Allowed Hosts: {hosts} (type: {type(hosts)})")

# Clean up the dummy .env file
os.remove('.env')

view raw JSON →