Fun with app.config

In my pre-Python days, whenever I heard the word “Flask”, this is the first image that came to mind:

images

Very appropriate now, since experimenting plays a central role in learning to code.  Even more appropriate for me, since the first Python web framework I’m performing experiments with is a “flask” of a different type.   Here’s a script I wrote to help me learn how app.config works in a Flask app, the blog I learned to create from Real Python Part 2, Chapter 7.  See comments for explanation.

# config fun

from flask import Flask

# configuration
DATABASE = 'blog.db'
USERNAME = 'admin'
PASSWORD = 'admin'
SECRET_KEY = 'wouldnt_you_like_to_know_ha_ha'

app = Flask(__name__)

# pulls in app configuration by looking for UPPERCASE variables
app.config.from_object(__name__)

def print_cfg():
 """
 A little function to print app.config in alphabetical order
 """
 print()
 for key in sorted(app.config):
 print(key,app.config[key])

# show the starting configuration
print("Starting config:")
print_cfg()

# now to test different ways of updating app.config - first I just add a new
# value in like we did above
app.config['FAVORITE FOOD'] = 'spam'

# show me some spam!
print("Added a new one")
print_cfg()

# now I'll add a new value using a file 'cfg.py'
app.config.from_object('cfg')

# 'foo' + 'bar != 'fubar'
print("And another one")
print_cfg() 

The file ‘cfg.py’ referenced in line 37 above contains the following line only:

FAVORITE_FOO = 'bar'

Results from first call of print_cfg. Note all configuration items are listed in nice alphabetical order.

APPLICATION_ROOT None
DATABASE blog.db
DEBUG False
EXPLAIN_TEMPLATE_LOADING False
JSONIFY_MIMETYPE application/json
JSONIFY_PRETTYPRINT_REGULAR True
JSON_AS_ASCII True
JSON_SORT_KEYS True
LOGGER_HANDLER_POLICY always
LOGGER_NAME __main__
MAX_CONTENT_LENGTH None
PASSWORD admin
PERMANENT_SESSION_LIFETIME 31 days, 0:00:00
PREFERRED_URL_SCHEME http
PRESERVE_CONTEXT_ON_EXCEPTION None
PROPAGATE_EXCEPTIONS None
SECRET_KEY wouldnt_you_like_to_know_ha_ha
SEND_FILE_MAX_AGE_DEFAULT 12:00:00
SERVER_NAME None
SESSION_COOKIE_DOMAIN None
SESSION_COOKIE_HTTPONLY True
SESSION_COOKIE_NAME session
SESSION_COOKIE_PATH None
SESSION_COOKIE_SECURE False
SESSION_REFRESH_EACH_REQUEST True
TEMPLATES_AUTO_RELOAD None
TESTING False
TRAP_BAD_REQUEST_ERRORS False
TRAP_HTTP_EXCEPTIONS False
USERNAME admin
USE_X_SENDFILE False

Here are the abbreviated results after adding a very important, and delicious, value from the module using UPPERCASE:

APPLICATION_ROOT None
DATABASE blog.db
DEBUG False
EXPLAIN_TEMPLATE_LOADING False
FAVORITE FOOD spam
JSONIFY_MIMETYPE application/json
.
.
.
USE_X_SENDFILE False

Finally, another value added from the file ‘cfg.py’:

APPLICATION_ROOT None
DATABASE blog.db
DEBUG False
EXPLAIN_TEMPLATE_LOADING False
FAVORITE FOOD spam
FAVORITE_FOO bar
JSONIFY_MIMETYPE application/json
.
.
.
USE_X_SENDFILE False

So..basically app.config is a dictionary.