在烧瓶应用中设置和检索环境变量 [英] Setting and retrieving environmental variables in flask applications

查看:98
本文介绍了在烧瓶应用中设置和检索环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用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文件,其中文件将env vars设置为键值对,形式为

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆