Hello everyone, today I want to introduce a super useful Python library – python-dotenv. When developing projects, we often need to manage various configuration information, such as database passwords, API keys, etc. Writing these sensitive information directly in the code is not a good idea! python-dotenv is specifically designed to solve this problem, allowing us to manage these configurations more securely and conveniently.
What are Environment Variables?
Environment variables are like a “global notepad” on our computer, capable of storing various configuration information. For example, your computer has a PATH environment variable that tells the system where to find programs. In Python projects, we also often use environment variables to store configuration information.
Installing python-dotenv
We need to install python-dotenv:
pip install python-dotenv
Creating and Using .env Files
Create a <span>.env</span>
file in the root directory of your project and write the configuration information inside:
# Database Configuration
DB_HOST=localhost
DB_USER=root
DB_PASS=123456
# API Configuration
API_KEY=your_secret_key
DEBUG=True
Tip: The <span>.env</span>
file should be added to <span>.gitignore</span>
so that it won’t be tracked by Git!
Now let’s see how to use these configurations in the code:
from dotenv import load_dotenv
import os
# Load .env file
load_dotenv()
# Get environment variables
db_host = os.getenv('DB_HOST')
db_user = os.getenv('DB_USER')
db_pass = os.getenv('DB_PASS')
print(f"Connecting to database: {db_host}")
Advanced Usage
1. Setting Default Values
If an environment variable does not exist, we can set a default value:
# If DEBUG environment variable does not exist, default to False
debug_mode = os.getenv('DEBUG', 'False') == 'True'
2. Multi-Environment Configuration
We can create different .env files for different environments:
.env # Default configuration
.env.dev # Development environment
.env.prod # Production environment
Load the specified environment configuration:
from dotenv import load_dotenv
# Load production environment configuration
load_dotenv('.env.prod')
3. Overriding Existing Environment Variables
By default, dotenv does not override existing environment variables. If you need to force an override:
load_dotenv(override=True)
Notes
- 🔔 Sensitive information (such as passwords and keys) must be placed in the .env file and added to .gitignore.
- 💡 Values in the .env file are all strings, and you need to convert types as necessary.
- ⚠️ The .env file for the production environment should be managed separately; do not carry over test environment configurations to production.
Practical Example
Let’s look at a simple web application configuration:
from dotenv import load_dotenv
import os
load_dotenv()
class Config:
def __init__(self):
self.database_url = os.getenv('DATABASE_URL')
self.api_key = os.getenv('API_KEY')
self.debug = os.getenv('DEBUG', 'False') == 'True'
self.port = int(os.getenv('PORT', '5000'))
config = Config()
print(f"The application will start on port {config.port}")
print(f"Debug mode: {'On' if config.debug else 'Off'}")
Exercise: Try creating a .env file, configure the above environment variables, and then run this code to see the effect!
Friends, that’s all for today’s Python learning journey! Remember to code actively, and feel free to ask me any questions in the comments. Using python-dotenv not only makes your code more secure but also makes configuration management super easy! Wishing everyone a happy learning experience and continuous improvement in Python!
Like and Share
LetMoneyandLoveFlow to You