icon: LiWrench
Title: A More Secure way to Store Credentials
After getting familiar with Jupyter Notebook, especially Google Colab that is hosted remotely on a server, you would realize that it is very dangerous to specify our API key in the notebook or script.
What we have been using until this point is to rely on the getpass()
function to allow users (in fact us), to input the API Key
and store the value into a variable, shown below.
from openai import OpenAI
from getpass import getpass
openai_key = getpass("Enter your API Key:")
client = OpenAI(api_key=openai_key)
This method helps keep the key secure by not hardcoding it into the script, which could be accidentally shared or exposed.
While the getpass()
method helps keep the key secure by not hardcoding it into the script which which could be accidentally shared or exposed, this method is not suitable for scenarios where the Python script or application needs to run autonomously, without human interaction, such as:
getpass()
impractical.When building an application, the app may require access to a variety of APIs and other services, such as Google Sheet, AWS account, or Telegram messages. All these access would require some forms of credentials (i.e., username and password pair, API key).
Think of an environment variable as a special, secure place on your computer or server where you can store these credentials Your Python scripts or applications can access the credentials, such as the OpenAI API key, when they need to access the services, but the credentials aren't visible to anyone just looking through the code.
One way to set the environment variable is through a configuration file (.env).
.env
File?.env
file is a simple text file used to store configuration settings, environment variables, and other key-value pairs related to a Python project. .env
file, which is loaded into the project's environment during runtime. .env
files in Python ensures secure management of sensitive information and allows for flexible configuration across different environments. .env
File?.env
file. .env
File:.env
File:
.env
at the root level. .env
file, for exampe: KEY="<my_OpenAI_Key>"
python-dotenv
library using the following command: pip install python-dotenv
.env
File in Your Python Code:
dotenv
module in your Python code. load_dotenv()
to load variables from the .env
file. os.getenv("KEY")
for each key-value pair defined in the .env
file. Example: ```Python
import os
from dotenv import load_dotenv
load_dotenv()
print(os.getenv("KEY"))
```