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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With