Skip to main content
 首页 » 编程设计

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

2024年09月07日8虾米哥

在/instance/app.cfg 中我配置了:

test=test 

在我的 flask 文件 app.py 中:

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

打印 config <class 'bytes'>

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

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

更新:

应用程序.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:

应用程序.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 

请您参考如下方法:

Reading the flask doc it does not detail how to read values from configuration files, how is this achieved ?

您可以在 flask 的文档中阅读 here (标题“从文件配置”)

open_instance_resource 只是处理位于“实例文件夹”(可以存储部署特定文件的特殊位置)中文件的快捷方式。它不应该是一种将您的配置作为字典获取的方法。

Flask 将他的配置变量 (app.config) 存储为一个字典对象。您可以通过一系列方法更新它:from_envvar、from_pyfile、from_object 等。查看 source code

人们在基于 Flask 的应用程序中读取配置文件的典型方式之一:

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

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

... 
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()