How to setup environment variables for your Flask application
Welcome to the DevMaesters website! In this article, I'll guide you through setting up environment variables in your Flask application.
Flask is a lightweight framework that enables rapid development of websites and REST API endpoints. Built on Python, it requires knowledge of HTML, CSS, JavaScript for frontend handling, and Python for backend setup.
Let's dive into setting up environment variables for your Flask application.
Prerequisites
Make sure you have your Flask application set up. If not, follow our previous guide on setting up a basic Flask application here.
Getting Started
Step 1: Ensure your virtual environment is active, then install the python-dotenv package using pip:
pip install python-dotenv
Step 2: Create a .env file in the root directory of your application. This file will store your environment variables in a KEY=VALUE format:
SECRET_KEY=mysecretkey
DEBUG=True
DATABASE_URL=your_database_connection_url
Step 3: Load Variables in Your Flask App
Assuming you have a config.py file from the earlier link, this is where we'll load our environment variables.python
from dotenv import load_dotenv
import os
load_dotenv() # Load variables from .env file
# Access your environment variables
secret_key = os.getenv('SECRET_KEY')
debug_mode = os.getenv('DEBUG')
db_url = os.getenv('DATABASE_URL')
SECRET_KEY = secret_key
basedir = os.path.abspath(os.path.dirname(__file__))
DEBUG = debug_mode
SQLALCHEMY_DATABASE_URI = db_url
SQLALCHEMY_TRACK_MODIFICATIONS = False
If you didn't use the tutorial, simply add the above code wherever you need to access environment variables, like in your app.py file.
from dotenv import load_dotenv
import os
load_dotenv() # Load variables from .env file
# Now you can access your environment variables
secret_key = os.getenv('SECRET_KEY')
debug_mode = os.getenv('DEBUG')
db_url = os.getenv('DATABASE_URL')
# Use these variables in your Flask configuration or other parts of the app
app = Flask(__name__)
app.config['SECRET_KEY'] = secret_key
app.config['DEBUG'] = debug_mode
Final Step: Protect Your Secrets
Add the newly created .env file to your .gitignore to prevent keys and credentials from being accessible when pushing your code:
.gitignore:
.env
And that's it! You've successfully set up environment variables for your Flask project. Check out the video below to see the process in action. If you have any questions or comments, feel free to drop them below.