cannot get environment variables set in Flask application
With your CLI, set the environment variable as you want. On Linux and macOS, this is done with export KEY=value
.
After that, the environment variable KEY
will be available for your Python script or Flask app via os.environ.get('KEY')
, like this:
import os
print os.environ.get('key')
>>> value
Related videos on Youtube
DBS
Updated on June 04, 2022Comments
-
DBS almost 2 years
I tried to set up sensitive information as environment variables in CentOS, and pass them to Flask config file used in main file, i.e. init.py . But it did not work. The Flask application is running under Apache.
I first edit /etc/environment as root user
MAIL_USERNAME="[email protected]"
then logout, login again Then verify MAIL_USERNAME is set by running
echo $MAIL_USERNAME
This works fine
And in configuration.py, this is how I set MAIL_USERNAME.
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
for testing purpose, I print out MAIL_USERNAME
in __init__.py print(MAIL_USERNAME)
Then from terminal, if I run
python3.4 __init__.py
it print out correct values of MAIL_USERNAME
However, if I tested on web browser, MAIL_USERNAME is just not set. it shows NONE. I verify this by looking Apache log.
Any idea of how this works would be really appreciated.
Thanks