Read Environment Variables with Python dotenv
Last Updated : 05 Aug, 2024
Environment variables play a crucial role in the configuration and operation of software applications. They provide a mechanism to store configuration settings that can be used by applications to function properly. This separation of configuration from code allows for more secure and flexible software development practices.
Introduction to python-dotenv
python-dotenv is a Python package that automates the process of loading environment variables from a .env file into the environment. A .env file is a simple text file that contains key-value pairs representing environment variables. By using python-dotenv, you can easily manage and load these variables in your Python applications without manually setting them in your operating system. With python-dotenv, you can load these variables into your application with just a few lines of code, simplifying configuration management and enhancing security.
A .env file is a simple text file used to store environment variables in a key-value pair format. This file is typically placed in the root directory of your project. The .env file allows you to manage your application's configuration settings in a centralized and organized manner.
Example Project Structure
my_project/
│
├── .env
├── my_script.py
└── requirements.txt
Installing python-dotenv
To get started with python-dotenv
, you'll need to install it. You can do this using pip:
pip install python-dotenv
Creating a .env File
Create the .env File: Open your project root directory and create a new file named .env.
Add Environment Variables: In the .env file, add your environment variables as key-value pairs. Each pair should be on a new line. The format is KEY=VALUE.
Here’s an example of a .env file containing:
- DATABASE_URL stores the connection string for a PostgreSQL database.
- SECRET_KEY is used for cryptographic operations such as signing cookies or tokens.
- DEBUG is a flag to indicate whether the application should run in debug mode.
# .env
DATABASE_URL=postgres://user:password@localhost/dbname
SECRET_KEY=your_secret_key
DEBUG=True
Important Considerations
Security: The .env file often contains sensitive information such as API keys, database credentials, and other secrets. It is crucial to ensure that this file is not exposed publicly.
.gitignore: To prevent the .env file from being committed to your version control system (e.g., Git), add it to your .gitignore file. This ensures that sensitive information is not shared inadvertently. Add the following line to your .gitignore file:
Consistency Across Environments: Maintain separate .env files for different environments (e.g., .env.development, .env.testing, .env.production). This allows you to have different configurations for different stages of your application lifecycle without modifying the source code.
example of adding different .env file for different environmentsExample .env Files for Different Environments
.env file for development environmentBy keeping environment-specific configurations separate, you can easily switch between environments without altering your codebase.
Loading .env Files with python-dotenv
Once you have created and configured your .env file, you can use python-dotenv to load these environment variables into your Python application. This simplifies the process of managing configuration settings and ensures that your application can access the necessary variables.
Reading Environment Variables
Once you have set up your .env file with the necessary environment variables, the next step is to read these variables into your Python application. The python-dotenv package makes this process straightforward.
Step 1. Install python-dotenv
First, you need to install the python-dotenv package if you haven't already. You can do this using pip.
pip install python-dotenv
Step 2. Import and Load the .env File
In your Python script, import the load_dotenv function from the dotenv module and call it to load the environment variables from the .env file.
Python from dotenv import load_dotenv import os # Load environment variables from .env file load_dotenv()
Step 3. Read Environment Variables
Use the os.getenv() function to read the environment variables. This function takes the name of the environment variable as an argument and returns its value.
Python database_url = os.getenv('DATABASE_URL') secret_key = os.getenv('SECRET_KEY') debug = os.getenv('DEBUG')
Step 4. Provide Default Values( Optional )
It’s a good practice to provide default values in case an environment variable is not set. This can prevent your application from crashing due to missing environment variables.
Python database_url = os.getenv('DATABASE_URL', 'default_database_url') secret_key = os.getenv('SECRET_KEY', 'default_secret_key') debug = os.getenv('DEBUG', 'False')
Step 5. Using the Environment Variables
You can now use these variables in your application as needed. For instance, you can configure your database connection, set up your application’s secret key, or enable/disable debug mode based on these variables.
Python from sqlalchemy import create_engine # Use the DATABASE_URL to create a database engine engine = create_engine(database_url) # Print the values to verify print(f"Database URL: {database_url}") print(f"Secret Key: {secret_key}") print(f"Debug Mode: {debug}")