Flask App Config
App config holds the settings of an app. The app.config dict stores each setting by name.
Make the app and set a value
This line makes the app. The next line sets the GREETING setting to Hi.
from flask import Flask
app = Flask(__name__)
app.config["GREETING"] = "Hi"Read the setting
The view reads GREETING from the config. Hello is the default when the setting is missing.
@app.route("/")
def home():
return app.config.get("GREETING", "Hello")Ask, change, ask again
The first ask prints Hi. The program then changes the setting, and the second ask prints Hey.
client = app.test_client()
print(client.get("/").data.decode())
app.config["GREETING"] = "Hey"
print(client.get("/").data.decode())Example
from flask import Flask
app = Flask(__name__)
app.config["GREETING"] = "Hi"
@app.route("/")
def home():
return app.config.get("GREETING", "Hello")
client = app.test_client()
print(client.get("/").data.decode())
app.config["GREETING"] = "Hey"
print(client.get("/").data.decode())Key points
- app.config holds settings like a dict.
- app.config["GREETING"] = "Hi" sets one setting.
- A view reads settings with app.config.get.
- Settings change behaviour without code edits.
In this example, the GREETING setting starts as Hi. The view reads it with app.config.get. The test client asks for / and prints Hi. The program then changes the setting to Hey, and the second ask prints Hey.
Note
Config names use capital letters by habit.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does a view read the GREETING setting?