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.

Blogtastic

monty-python

Hopefully, in my latest quest, I won’t end up like these guys…

So I’ve completed the Flask Blog app in Chapter 7  of Real Python part 2.   This simple little beginner app has all the basic functions of a web site: login, entering data, logging out.  I’ve learned a ton so far…not the least of which includes finally getting a grasp of Git and virtualenv and even a decent (though far from perfect) understanding of Python decorators.  At the same time, I see I have a long way to go in my latest quest.

I don’t have a lifestyle in which I can regularly devote long hours of concentration to my web development learning, so I’m taking a different approach than in my previous Python adventures. I’m taking notes as I go through Real Python, to help me remember what I learned, and also remember where I left off.  I’m going to make sure I have a thorough grasp of each chapter’s material before I move on to the next.  I’ll do this by making notes of concepts I need to learn more about, and set goals to work on to do so.   I’ve found Evernote to be helpful in this regard, along with regular updates to my README. Stay tuned…

 

Overwhelmed by Practicality

Capture

Once upon a time, I took a glance at web development and found it was “killer” — in more ways than one.  I then threw my heart and soul into….reinventing the wheel, basically.  Then time, age, distractions and responsibilities crept up on me. I have had to make some decisions about how to make the best use of my time: how much am I able and willing to devote to learning new skills, given my current responsibilities and priorities?

How much sense does it make to create an application that duplicates what not one, but two existing applications (Access and Base) already can do for me perfectly adequately?  Such an effort could be justified if it helped me learn skills that could be useful, and even profitable, in the future.   How useful would the ability to create desktop-only software actually be, in a 21st century world that is rapidly turning to the web as its platform of choice for ALL computing, not just browsing, social networking and online shopping?  Answer: Not very.

Now, two years almost to the day after I took the HTML course at Codecademy, I am embarking on a new quest: learn web development with Python.  The tools are right in front of me:  good old RealPython has not one, but two huge ebooks on web development, that have been gathering digital dust on my hard drive.   My goal is to work through it slowly, so that I understand the concepts.  I have already made progress in grasping virtualenv and command-line Git.  At the moment my brain is tied in knots by Python decorators, but then again, it was once tied in knots by Python importing, so I’m confident I’ll wrestle through it.  At least I was able to complete the Flask Blog exercise.  I even typed out all the code by hand instead of copying and pasting, just like Michael told me to!

I would like to eventually create a web-based finance application, just like I did in Access and Base.  That will take time, however, and in the meantime, I still need to pay bills and track expenses, so Base will do, for now. I would say one of the most useful accomplishments during this blog’s lifetime was to get my financial data from my Access *.accdb file into SQLite, making the live data 100% portable.

As I (slowly, I expect) progress through the two RealPython web development courses, feel free to stop by GitHub to check on my progress!

Oh, and one more thing I’ve learned since my last post: Cities: Skylines is an even cooler game than SimCity4.

20160618213529_1

Python Web development. It’s killer.

Before I start today’s post, I would like to give a huge shout-out to my good friend Dana at Accularian, who generously and unexpectedly donated hosting space, enabling My Python Adventure to move to its own home on the Web!

In my early days of Python (read: less than 6 months ago), I seem to recall reading that web-based applications are the wave of the future. I discovered web2py and learned that a web app can live on my local computer as well as online and reasoned, why bother learning how to write desktop based apps at all, if a web based app can be both desktop and online? I decided to jump right in to web development, fresh out of Code Academy, and web2py turned out to be simple to install and easy to set up (Django was another matter entirely, but that’s a topic for another post.) As I rummaged around the internet looking for a web2py tutorial, I found Killer Web Development.

An amusing aside: at some point I mis-typed the URL and ended up with a “Page Not Found” error, with a sidebar of other suggestions along the lines of “Murderer Web Development”, “Assassin Web Development”, etc.  I hope the internet’s slang-recognition algorithms improve before I get in trouble with Homeland Security.

The best thing about this tutorial is it not only gives a thorough introduction to basic concepts of web development (such as model-view-controller), it also introduces essentials of coding in general, such as version control, using and sharing repositories and test-driven development. I was clueless about all of these before. The author is not a native speaker of English so his grammar is hard to follow at times, but on the other hand, he’s doing way more than I could dream of. I doubt I could come up with an intelligible toilet flushing tutorial in German, even with Google Translate, never mind a highly technical topic like Herr Laspe dared to tackle in a foreign language. His enthusiasm for his subject matter shines through, and is contagious. I came away with the sense that I’d learned, hands-on, all the essential steps of professional programming — not just the particulars of a specific language or tool. This was extraordinarily valuable. Now so much of what I hear from the coding community, phrases like “repository”, “testing framework”, etc. is less and less Greek to me.

I also learned from this site that “web development” Python is almost like a different language from “Code Academy” Python. In studying the web2py code I’d created in the tutorial, it seemed to resemble very little of what I thought I had learned. I therefore decided to do something that is difficult for me: admit that I perhaps bit off more than I can chew, back up and start again from a simpler foundation. So now, off to desktop GUI building.  Hello, Tkinter!