在Flask中将配置文件读取为字典

时间:2018-05-18 16:12:18

标签: python flask

/ pance/app.cfg中的

我已配置:

test=test

在我的烧瓶文件app.py中:

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

打印config <class 'bytes'>

阅读烧瓶文档,它没有详细说明如何从配置文件读取值,这是如何实现的?

可以配置读取字典而不是字节吗?

更新:

app.py:

# Shamelessly copied from http://flask.pocoo.org/docs/quickstart/

from flask import Flask
app = Flask(__name__)

import os

ac = app.config.from_pyfile(os.path.join('.', 'conf/api.conf'), silent=True)
logging_configuration = app.config.get('LOGGING')
if ac:
    print(logging.config.dictConfig(ac))

@app.route('/')
def hello_world():
    return 'Hello World!'

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

api.conf:

myvar=tester

返回错误:

/./conf/api.conf", line 1, in <module>
    myvar=tester
NameError: name 'tester' is not defined

更新2:

app.py:

from flask import Flask
app = Flask(__name__)

import os
from logging.config import dictConfig

app.config.from_pyfile(os.path.join('.', 'conf/api.conf'), silent=True)

logging_configuration = app.config.get('LOGGING')
if logging_configuration:
    print(dictConfig(logging_configuration))

@app.route('/')
def hello_world():
    return 'Hello World!'

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

api.conf:

LOGGING="tester"

返回错误:

ValueError: dictionary update sequence element #0 has length 1; 2 is required

2 个答案:

答案 0 :(得分:2)

  

阅读烧瓶文档,它没有详细说明如何从配置文件读取值,这是如何实现的?

你可以在flask的文档here中读到它(标题为“从文件配置”)

open_instance_resource只是处理位于“实例文件夹”(一个可以存储部署特定文件的特殊位置)的文件的快捷方式。它不应该是让你的配置成为一个词典的方法。

Flask将他的配置变量(app.config)存储为dict对象。您可以通过一系列方法对其进行更新:from_envvarfrom_pyfilefrom_object等。请查看source code

人们在基于烧瓶的应用中阅读配置文件的典型方式之一:

app = Flask('your_app')
...
app.config.from_pyfile(os.path.join(basedir, 'conf/api.conf'), silent=True)
...

之后,您可以根据需要使用类似dict的配置对象:

...
logging_configuration = app.config.get('LOGGING')
if logging_configuration:
    logging.config.dictConfig(logging_configuration)
...
from flask import Flask
app = Flask(__name__)

import os

app.config.from_pyfile(os.path.join('.', 'conf/api.conf'), silent=True)

@app.route('/')
def hello_world():
    return 'Hello World! {}'.format(app.config.get('LOGGING'))

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

答案 1 :(得分:0)

如果您执行app.config.from_pyfile('app.cfg'),则可以dict(app.config)将您的配置作为字典获取。

但是,此词典将包含app整个配置,而不仅仅是配置文件设置的那些变量。