Python
Environment Variables
Read and set environment variables.
By EZ4Code Team
envenv-vars
Code
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")Explanation
Uses os.getenv to read environment variables; python-dotenv loads .env files.
More Python Snippets
Sort Dictionary by Value
Sort a Python dictionary by its values in descending order.
List Comprehension
Quickly generate lists using list comprehensions.
Dictionary Merging
Multiple ways to merge dictionaries.
File Read/Write
Various ways to read and write files.
CSV Processing
Read and write CSV files using the csv module.
JSON Processing
JSON serialization and deserialization.