What Are Environment Variables? | ||||||||
environment variables are dynamic values used to store configuration settings
|
||||||||
Why Use Environment Variables? | ||||||||
|
||||||||
Setting Environment Variables | ||||||||
set environment variables in the shell before running script in Unix-based system export DATABASE_URL="postgres://user:password@localhost/dbname" export SECRET_KEY="supersecretkey" export API_KEY="your_api_key"in Windows set DATABASE_URL="postgres://user:password@localhost/dbname" set SECRET_KEY="supersecretkey" set API_KEY="your_api_key"when the script runs it has access to the environment variables |
||||||||
Example Python Script | ||||||||
import os def main() -> None: database_url = os.getenv('DATABASE_URL') secret_key = os.getenv('SECRET_KEY') api_key = os.getenv('API_KEY') if not all([database_url, secret_key, api_key]): raise ValueError("Missing one or more environment variables: DATABASE_URL, SECRET_KEY, API_KEY") print(f"Connecting to database at {database_url}") print(f"Using secret key: {secret_key}") print(f"API key: {api_key}") # Add application logic here if __name__ == "__main__": main() |
||||||||
Using a .env File with python-dotenv | ||||||||
use use a .env file with python-dotenv to manage environment variables stores environment variables in a file and load them into the app create a .env file in project's root of directory DATABASE_URL=postgres://user:password@localhost/dbname SECRET_KEY=supersecretkey API_KEY=your_api_keyload environment variables in main.py modify script to use python-dotenv to load the environment variables from the .env file import os from dotenv import load_dotenv def main(): # Load environment variables from .env file load_dotenv() database_url = os.getenv('DATABASE_URL') secret_key = os.getenv('SECRET_KEY') api_key = os.getenv('API_KEY') if not all([database_url, secret_key, api_key]): raise ValueError("Missing one or more environment variables: DATABASE_URL, SECRET_KEY, API_KEY") print(f"Connecting to database at {database_url}") print(f"Using secret key: {secret_key}") print(f"API key: {api_key}") # Add your application logic here if __name__ == "__main__": main() |
||||||||
Best Practices | ||||||||
|