Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading properties from config file with Flask and Python

Tags:

python

flask

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.

like image 674
blue-sky Avatar asked Jan 02 '23 08:01

blue-sky


1 Answers

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")
like image 57
zwer Avatar answered Jan 05 '23 16:01

zwer