从多个文件加载Flask配置 [英] Load Flask config from multiple files

查看:56
本文介绍了从多个文件加载Flask配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从多个文件加载配置.我使用下面的代码加载一个文件.我应该重复使用吗?如何加载多个配置?

I need to load configuration from multiple files. I use the code below to load one file. Should I use it repeatedly? How do I load multiple configs?

app = Flask(__name__)
app.config.from_object('yourapplication.default_settings')

推荐答案

您可以根据需要加载配置,唯一的要求是它必须以 app.config 结尾. from_object 只是一种帮助方法,用于您的配置是否位于可导入的Python文件中,例如示例中的默认设置.还有其他帮助程序,或者您可以将 app.config 当作字典并根据需要设置值.

You can load config however you want, the only requirement is that it ends up in app.config. from_object is just a helper method for if your config is in an importable Python file, such as the default settings in your example. There are other helpers as well, or you can just treat app.config as a dict and set values however you want.

覆盖默认设置的标准方法是先加载它们,然后从实例文件夹中加载本地设置.

The standard method for overriding default settings is to load them and then load local settings from the instance folder.

app = Flask(__name__, instance_relative_config=True)
app.config.from_object('myapp.default_settings')
app.config.from_pyfile('local_settings.py', silent=True)

这会将实例文件夹中的 local_settings.py 加载到配置中,并忽略该文件是否不存在.

This will load local_settings.py in the instance folder into the config, and ignore if the file doesn't exist.

myproject/
    myapp/
        __init__.py
        default_settings.py
    instance/
        local_settings.py

通过导入应用程序在需要的地方访问配置.

Access the config wherever you need it by importing the app.

from myapp import app
my_value = app.config['my_key']

这篇关于从多个文件加载Flask配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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