Python5 min read

Python Environment Variables

Manage configuration using environment variables.

David Miller
December 18, 2025
0.0k0

Secure configuration management.

Read Environment Variables

```python import os

Get variable db_host = os.environ.get('DB_HOST', 'localhost') db_port = os.environ.get('DB_PORT', '5432')

print(f"Connecting to {db_host}:{db_port}") ```

Set Environment Variables

```python import os

Set in Python os.environ['API_KEY'] = 'your_key_here'

Access it api_key = os.environ['API_KEY'] ```

Using .env File

```bash pip install python-dotenv ```

```python # .env file: # DB_HOST=localhost # DB_PORT=5432 # API_KEY=secret123

from dotenv import load_dotenv import os

load_dotenv()

db_host = os.getenv('DB_HOST') api_key = os.getenv('API_KEY')

print(f"Host: {db_host}") ```

Configuration Class

```python import os from dotenv import load_dotenv

load_dotenv()

class Config: DB_HOST = os.getenv('DB_HOST', 'localhost') DB_PORT = int(os.getenv('DB_PORT', 5432)) API_KEY = os.getenv('API_KEY') DEBUG = os.getenv('DEBUG', 'False') == 'True'

config = Config() print(config.DB_HOST) ```

Different Environments

```python import os

class Config: DEBUG = False TESTING = False

class DevelopmentConfig(Config): DEBUG = True

class ProductionConfig(Config): DEBUG = False

def get_config(): env = os.getenv('FLASK_ENV', 'development') if env == 'production': return ProductionConfig() return DevelopmentConfig()

config = get_config() ```

Remember

- Never commit .env files - Use different configs per environment - Always provide defaults

#Python#Advanced#Configuration