简体   繁体   中英

Reading properties from config file with Flask and Python

Building from Reading config file as dictionary in Flask I'm attempting to define a custom configuration file in order to customize my Flask app.

Running code :

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

In config/app.conf these properties are added :

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

Invoking the service for hello_world() function returns :

Hello World! None

Shouldn't the contents of the file be returned instead of None ?

I attempt to access a property using app.config.get('myvar1') but None is also returned in this case.

From the 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.

Therefore, set structure your ./config/app.conf variables as:

VARIABLE_NAME = "variable value"

Load as:

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

NOTE: If you're not using instance specific configuration you don't actually need to build the path as it will take the Flask app path as its root.

And access the values later as:

app.config.get("VARIABLE_NAME")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM