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:
- Install the
python-dotenv
library if you haven’t already:
pip install python-dotenv
- 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:
ACCESS_KEY=your_access_key_here
ACCESS_ID=your_access_id_here
- 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
load_dotenv()
# Access the environment variables
access_key = os.getenv("ACCESS_KEY")
access_id = os.getenv("ACCESS_ID")
- 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 + '.logicmonitor.com/santaba/rest' + 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.