Storing Sensitive Information/Credentials in .env file for Python

Using a .env file to store API keys and other sensitive information is a common practice in Python applications. You can use the python-dotenv library to easily load variables from a .env file into your Python script. Here’s how you can do it:

  1. Install the python-dotenv library if you haven’t already:
pip install python-dotenv
  1. Create a .env file in the same directory as your Python script or in the project’s root directory. In this file, you can store your API keys and other sensitive information in the format VARIABLE_NAME=value. For example:
  1. In your Python script, import and load the environment variables using python-dotenv at the beginning of your script:
import os
from dotenv import load_dotenv

# Load environment variables from .env file

# Access the environment variables
access_key = os.getenv("ACCESS_KEY")
access_id = os.getenv("ACCESS_ID")
  1. Replace your API keys and sensitive information in your script with the variables you loaded from the environment:
auth = 'LMv1 ' + access_id + ':' + signature.decode() + ':' + epoch
url = 'https://' + company + '' + resourcePath + queryParams

By following these steps, you can store your API keys and sensitive information securely in a .env file and load them into your Python script when needed. This approach helps keep your credentials separate from your code and allows you to easily manage different sets of credentials for different environments (e.g., development, production) by using different .env files.

Don’t forget to add .env to .gitignore before committing.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.