So, I wanted to quickly jot down how to use python-dotenv
on PythonAnywhere for managing environment variables.
This is one of those things that’s super handy when you’re dealing with API keys, tokens, or anything sensitive in your Python projects. Let’s break it down step by step.
1. Creating the .env
File
First, create a .env
file in your project directory on PythonAnywhere. This file is where you’ll store all your sensitive information.
Here’s the format:
API_KEY=your_api_key_here
SECRET_TOKEN=your_secret_token_here
Each variable goes on a new line, with KEY=VALUE
.
2. Setting Up Your Environment and Installing python-dotenv
It’s a good idea to set up a virtual environment for your project to keep dependencies isolated. Here’s how you can do it using the Bash console on PythonAnywhere:
- Open the Bash console in PythonAnywhere.
Install python-dotenv
inside the virtual environment:
pip install python-dotenv
Activate the virtual environment:
source venv/bin/activate
Create a virtual environment:
virtualenv -p python3 venv
This creates a new virtual environment in a directory named venv
.
3. Accessing Variables in Your Script
In your Python script, you’ll use the python-dotenv
library to load the .env
file and the os
module to access the variables.
Here’s how:
from dotenv import load_dotenv
import os
# Load the .env file
load_dotenv()
# Access environment variables
api_key = os.getenv("API_KEY")
secret_token = os.getenv("SECRET_TOKEN")
print(f"API Key: {api_key}")
print(f"Secret Token: {secret_token}")
4. That's It!
With this setup:
- Your sensitive info stays out of your codebase.
- Your Python project is organized and secure.
- You’ve isolated your dependencies with a virtual environment.
Perfect for projects on PythonAnywhere or anywhere else, really!
Source: https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/
Subscribe to our email newsletter and unlock access to members-only content and exclusive updates.
Comments