The Problem with Hard-Coding Configuration
Hard-coding configuration values in code can lead to security risks and deployment challenges. For example, consider the following code snippet:
PASSWORD=123
USERNAME=myusername
This approach has several drawbacks:
- Sensitive data is exposed in the code
- Changes to configuration values require code changes
Introducing Python-dotenv
Python-dotenv is a library that allows you to load environment variables from a .env
file. This approach separates configuration from code and provides several benefits:
- Keep sensitive data out of code
- Use different configurations per environment
To use Python-dotenv, you’ll need to create a .env
file with your configuration values. Here’s an example:
#.env
PASSWORD=123
USERNAME=myusername
Next, you can load the environment variables from the .env
file using the load_dotenv()
function:
from dotenv import load_dotenv
import os
load_dotenv()
PASSWORD = os.getenv('PASSWORD') # 123
USERNAME = os.getenv('USERNAME') # myusername
This code loads environment variables from a .env file, allowing secure access to configuration values like PASSWORD and USERNAME.