Reading Config File As Dictionary In Flask
Solution 1:
Reading the flask doc it does not detail how to read values from configuration files, how is this achieved ?
You can read about it in flask's doc here (title "configuring-from-files")
open_instance_resource
is only a shortcut to make deal with files which are located in "instance folder" (a special place where you can store deploy specific files). It's not supposed to be a way to get your config as a dict.
Flask stores his config variable(app.config) as a dict object. You can update it via a bunch of methods: from_envvar
, from_pyfile
, from_object
etc. Look at the source code
One of the typical ways how people read config files in flask-based apps:
app = Flask('your_app')
...
app.config.from_pyfile(os.path.join(basedir, 'conf/api.conf'), silent=True)
...
After that, you can use your dict-like config object as you want:
...
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('/')defhello_world():
return'Hello World! {}'.format(app.config.get('LOGGING'))
if __name__ == '__main__':
app.run()
Solution 2:
If you do app.config.from_pyfile('app.cfg')
you can obtain your config as a dictionary by dict(app.config)
.
However, this dictionary will contain the whole configuration for your app
not only those variables which were set by the configuration file.
Post a Comment for "Reading Config File As Dictionary In Flask"