无法获取Flask应用程序中设置的环境变量 [英] cannot get environment variables set in Flask application
问题描述
我试图在CentOS中将敏感信息设置为环境变量,并将其传递给主文件中使用的Flask配置文件,即 init .py.但这没有用.Flask应用程序正在Apache下运行.
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.
我首先以root用户身份编辑/etc/environment
I first edit /etc/environment as root user
MAIL_USERNAME="abcde@abc.com"
然后注销,再次登录然后通过运行
then logout, login again Then verify MAIL_USERNAME is set by running
echo $MAIL_USERNAME
这很好
在configuration.py中,这就是我设置MAIL_USERNAME的方式.
And in configuration.py, this is how I set MAIL_USERNAME.
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
出于测试目的,我打印了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
它打印出MAIL_USERNAME的正确值
it print out correct values of MAIL_USERNAME
但是,如果我在网络浏览器上进行了测试,则未设置MAIL_USERNAME.它显示NONE.我通过查看Apache日志来验证这一点.
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.
谢谢
推荐答案
使用CLI,根据需要设置环境变量.在Linux和macOS上,这是通过 export KEY = value
来完成的.
With your CLI, set the environment variable as you want. On Linux and macOS, this is done with export KEY=value
.
之后,环境变量 KEY
将通过 os.environ.get('KEY')
用于Python脚本或Flask应用,如下所示:
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
这篇关于无法获取Flask应用程序中设置的环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!