在烧瓶应用中设置和检索环境变量 [英] Setting and retrieving environmental variables in flask applications
问题描述
我想使用python3/flask构建一个非常简单的REST api.
I want to build a very simple REST api using python3/flask.
例如,我想将flask
所需的SECRET_KEY
设置为环境变量.
Say for example I want to set my SECRET_KEY
required by flask
as env var.
推荐的处理方式是什么?
What is the recommended way of going about it?
我知道python-dotenv
软件包允许(或者我应该说需要?).flaskenv
文件,其中
I am aware of python-dotenv
package that allows (or should I say requires?) the .flaskenv
file with env vars set as key-value pairs in the form of
SECRET_KEY="my_secret_key"
DB_NAME="mydatabase"
等
然后(我假设)我可以创建一个settings.py
文件,例如
Then (I assume) I can create a settings.py
file such as
import os
SECRET_KEY = os.getenv('SECRET_KEY`)
,然后在我的Flask文件上执行import settings
,依此类推.
and then perform an import settings
on my flask files and so on.
我的主要问题是,如何在没有这样的.flaskenv
文件但容器中本身的运行时环境变量可用的容器化环境中适应该环境(例如通过其协调器)
My main question is how can this be adapted in a containerized environment where there will not be such an .flaskenv
file but the respective variables will be available as runtime env vars in the container itself (say via its orchestrator)
在没有.flaskenv
的情况下,上述形式的settings.py
是否能够检索环境变量?
Will the above form of settings.py
be able to retrieve env vars in the absence of .flaskenv
?
推荐答案
python-dotenv
实际上与Flask无关.它是将您的.env
文件转换为实际的env变量.因此,如果没有它,您将拥有实际的env变量,您的os.getenv
应该仍然可以工作.
python-dotenv
actually has nothing to do with Flask. It is for your .env
file to be translated into actual env variables. So if you're going to have actual env variables without it, your os.getenv
should still work.
旁注:您也可以使用os.environ
:
os.environ.get("SECRET")
这篇关于在烧瓶应用中设置和检索环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!