Skip to content
Python

Variables d'environnement

Lire et définir des variables d'environnement.

#env#env-vars

Code

python
import os
from dotenv import load_dotenv

# Read env variable
db_url = os.getenv("DATABASE_URL", "sqlite:///default.db")
debug = os.getenv("DEBUG", "false").lower() == "true"

# Set env variable
os.environ["APP_MODE"] = "production"

# Load from .env file
load_dotenv()
api_key = os.getenv("API_KEY")

# Check existence
if "SECRET_KEY" not in os.environ:
    raise RuntimeError("Missing SECRET_KEY")