DEV Community

Discussion on: Using .env Files for Environment Variables in Python Applications

Collapse
 
vishal_sahu_fc7baf0e7eb01 profile image
Vishal Sahu

To read environment variables from a .env file in Python, the most commonly used library is python-dotenv. This library helps load key-value pairs from a .env file into environment variables, allowing you to access them using Python's os module. Here's a step-by-step guide:

Step 1: Install python-dotenv

First, ensure you have the python-dotenv package installed:

pip install python-dotenv
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a .env File

In your project directory, create a .env file with key-value pairs:

DATABASE_URL=postgres://user:password@localhost/dbname
SECRET_KEY=supersecretkey
DEBUG=True
Enter fullscreen mode Exit fullscreen mode

Step 3: Load the .env File in Your Python Code

Use the load_dotenv method from dotenv to load the environment variables:

from dotenv import load_dotenv
import os

# Load .env file
load_dotenv()

# Access environment variables
database_url = os.getenv("DATABASE_URL")
secret_key = os.getenv("SECRET_KEY")
debug_mode = os.getenv("DEBUG")

print(f"Database URL: {database_url}")
print(f"Secret Key: {secret_key}")
print(f"Debug Mode: {debug_mode}")
Enter fullscreen mode Exit fullscreen mode

Step 4: Use the Variables

Now, you can use these variables throughout your application securely without hardcoding sensitive information in your source code.

Best Practices for Using .env Files:

  1. Do Not Commit .env Files: Always include .env in your .gitignore file to avoid exposing sensitive data in version control.
  2. Use Defaults: Provide default values in your code to handle cases where environment variables are missing.
  3. Separation of Configurations: Use separate .env files for development, testing, and production environments.

For a more detailed discussion, you can refer to the LambdaTest community thread, where we dive deeper into practical use cases and advanced tips for managing environment variables in Python applications.