gpt4 book ai didi

python - 使用 Flask 和 Python 从配置文件中读取属性

转载 作者:太空宇宙 更新时间:2023-11-03 13:28:57 26 4
gpt4 key购买 nike

建筑自 Reading config file as dictionary in Flask我正在尝试定义自定义配置文件以自定义我的 Flask 应用程序。

运行代码:

from flask import Flask
app = Flask(__name__)

import os

my_config = app.config.from_pyfile(os.path.join('.', 'config/app.conf'), silent=False)

@app.route('/')
def hello_world():

with app.open_instance_resource('app.cfg') as f:
print(type(f.read()))

return 'Hello World! {}'.format(app.config.get('LOGGING'))

if __name__ == '__main__':
app.run()

在 config/app.conf 中添加了这些属性:

myvar1="tester"
myvar2="tester"
myvar3="tester"

hello_world() 函数调用服务返回:

Hello World! None

不应该返回文件的内容而不是 None 吗?

我尝试使用 app.config.get('myvar1') 访问属性,但在这种情况下也返回了 None

最佳答案

来自official Flask documentation :

The configuration files themselves are actual Python files. Only values in uppercase are actually stored in the config object later on. So make sure to use uppercase letters for your config keys.

因此,将 ./config/app.conf 变量的结构设置为:

VARIABLE_NAME = "variable value"

加载为:

app.config.from_pyfile(os.path.join(".", "config/app.conf"), silent=False)

注意:如果您没有使用特定于实例的配置,您实际上不需要构建路径,因为它会将 Flask 应用程序路径作为其根。

稍后访问这些值:

app.config.get("VARIABLE_NAME")

关于python - 使用 Flask 和 Python 从配置文件中读取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50433962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com