Managing Environment Configuration Variables In Flask With Dotenv
Overview
Often when developing apps with Flask we need to set up environment variables to keep sensitive information secure and out of version control.
This article describes how to set up environment config variables in Flask with python-dotenv and why we can’t rely in Flask’ instance folder.
dotenv versus instance folders
Flask introduces the concept of instance folder, designed to store sensitive information like credentials and passwords for your local environment, the main problem is that it can’t work with ephemeral filesystems like the one Heroku uses.
In this case the perfect fit for this is to use python-dotenv, so we
define environment config variables in Heroku and locally we put them
in /.env
.
Install
First we install it with pip install -U python-dotenv
$ pip install -U python-dotenv
Collecting python-dotenv
Downloading https://files.pythonhosted.org/packages/24/3d/977140bd94bfb160f98a5c02fdfbb72325130f12a325cf993182956e9d0e/python_dotenv-0.9.1-py2.py3-none-any.whl
Installing collected packages: python-dotenv
Successfully installed python-dotenv-0.9.1
requirements.txt
We add the new package to the requirements file.
$ pip freeze > requirements.txt
gitignore
We make sure that we won’t add it to the source code version control
adding it to .gitignore
:
$ echo ".env" >> .gitignore
add variables
Add variables to .env
, optionally copy all the environment variables
from your heroku app to have this as a skeleton to fill with local
variables:
$ heroku config -s >> .env
or simply add them manually to .env
, for example:
TWITTER_CONSUMER_KEY=MYINCREDIBLEKEY
use the new environment variables
Now we can use this environment variables in our Flask app.
Having the following typical structure:
myapp
.env
myapp
__init__.py
myapp.py
I like to initialize my app in /myapp/__init.py__
, but it should be
the same if you add this to /myapp/myapp.py
.
import os
from flask import Flask
from dotenv import load_dotenv
#...
# load dotenv in the base root
APP_ROOT = os.path.join(os.path.dirname(__file__), '..') # refers to application_top
dotenv_path = os.path.join(APP_ROOT, '.env')
load_dotenv(dotenv_path)
tw_consumer_key = os.getenv('TWITTER_CONSUMER_KEY')
Conclusion
I find it useful to use dotenv
for sensitive variables and custom
paths, and maintain other variables in version control separated by
server, like development, testing or production.
- Understanding Flask's context conceptJanuary 26, 2017
- Avoid Using Flask Instance Folder When Deploying To HerokuJanuary 24, 2017
- Managing Environment Configuration Variables In Flask With Dotenv
- Organize A Flask Project To Handle Production And Development Environments EffectivelyJanuary 11, 2017
- An Overview Of Flask Main Concepts And How It WorksDecember 31, 2016
Articles
Except as otherwise noted, the content of this page is licensed under CC BY-NC-ND 4.0 . Terms and Policy.
Powered by SimpleIT Hugo Theme
·