avatarLivia Ellen

Summarize

What is .env files in Python? Managing Environment Variable & Securing Your Secrets

Python Tip of The Day

Photo by Andras Vas on Unsplash

In Python development, managing sensitive data such as API keys and passwords is crucial for security and efficiency. This article explains .env files in Python, their importance, and demonstrates their use with an OpenAI API example.

What is a .env File?

A .env file is a simple text file holding key-value pairs, used to manage environment variables like API keys and passwords. Each line represents a data entry, separating the variable name and value with an "=" sign.

Importance of .env Files in Python:

  1. Security: Safeguards sensitive information from exposure, especially in public code repositories.
  2. Environment Separation: Manages different settings for development, testing, and production environments.
  3. Convenience: Streamlines updates to configuration without altering source code.

Using .env Files in Python: To utilize .env files, the python-dotenv library is required. This library loads key-value pairs as environment variables.

Installation:

pip install python-dotenv

Example: Using OpenAI API with .env File:

  1. Create .env File: In your project directory, create a .env file:
OPENAI_API_KEY=your-openai-api-key

2. Python Script:

This script demonstrates how to securely use an API key from a .env file for making authenticated requests to an external API, in this case, OpenAI. This method ensures sensitive information like API keys are not hard-coded into the source code, enhancing security and maintainability.

from dotenv import load_dotenv
import os
import requests

load_dotenv()  # Load .env file

openai_api_key = os.getenv('OPENAI_API_KEY')  # Get API key

url = "https://api.openai.com/v1/engines/davinci/completions"

headers = {"Authorization": f"Bearer {openai_api_key}"}

data = {
    "prompt": "Translate 'Hello, how are you?' to French.",
    "max_tokens": 60
}

response = requests.post(url, headers=headers, json=data)
print(response.json())

Bonus: .Env Cheatsheet

Accessing environment variables in the terminal and within Python code can be done through simple steps. Here’s how:

In the Terminal:

Setting an Environment Variable:

  • In Unix/Linux/macOS:
export VARIABLE_NAME=value
  • In Windows Command Prompt:
set VARIABLE_NAME=value
  • In Windows PowerShell:
$env:VARIABLE_NAME="value"

Accessing the Environment Variable:

  • In Unix/Linux/macOS:
echo $VARIABLE_NAME
  • In Windows Command Prompt or PowerShell:
echo %VARIABLE_NAME%
  • or
echo $env:VARIABLE_NAME

In Python Code:

Accessing an Environment Variable:

First, you need to import the os module, which provides a portable way of using operating system-dependent functionality.

import os  
variable_value = os.getenv('VARIABLE_NAME') 
print(variable_value)

The os.getenv function retrieves the value of the environment variable named 'VARIABLE_NAME'. If the variable doesn't exist, None is returned. You can also provide a default value as a second argument to os.getenv which will be used if the variable isn’t found.

Setting an Environment Variable (for use within the same script):

Although environment variables are typically set outside your Python script, sometimes you might want to set them from within the script.

os.environ['VARIABLE_NAME'] = 'value'

This sets the environment variable 'VARIABLE_NAME' for the current script and any child processes started by the script. However, this change won't affect the environment outside of the script.

Note: Environment variables are a key part of working with different environments and keeping sensitive data (like API keys) secure.

It’s important to never hard-code sensitive data directly into your .env code, especially if it’s going to be shared publicly or stored in version control systems.

Important Considerations:

  • Never Commit .env Files: Always add .env to your .gitignore file to prevent committing it to version control.
  • Keep It Updated: Regularly update .env files as your project's environment variables change.
  • Limit Access: Restrict access to .env files, especially in shared working environments.

Possible Limitations:

  • Environment-Specific: .env files can differ across environments, necessitating separate management.
  • Not Foolproof: If accessed, it can expose sensitive information, so additional security measures might be needed.

Conclusion:

Using .env files in Python is a best practice for secure and efficient code management. It is particularly useful for APIs like OpenAI, as it prevents sensitive keys from being hard-coded into the source. While powerful, remember to handle .env files with care to maintain their security benefits.

Happy Coding! Ellen

If you like to read more about my Python coding tips, you can take a look at my curated lists: Python Tips

Let’s Connect

  • 🌐 Follow me on LinkedIn and Medium
  • 📬 Subscribe to my Medium newsletter for email updates!
  • 🚀 Please clap, save into your reading list, share, and comment on this article if you found this useful! 👏 Oh Hey! you can clap more than one (50 max)in 1 article — that will help me get a cup of coffee to write my upcoming articles with ;)
  • ☕ or just buy me a real coffee ❤ — Yes I love coffee.

PlainEnglish.io 🚀

Thank you for being a part of the In Plain English community! Before you go:

Python Programming
Python
Programming
Data Science
Artificial Intelligence
Recommended from ReadMedium