Wednesday, August 17, 2016

Dissecting a Flask App


"How might I share content to the world through some web thing?"

I'll show you how we might do that in Python. is where I'm serving my example.

The source code is on Github.  Also:  see Addendum (followup blog post).

The engine sitting behind the HTTP listening port is a WSGI process named Flask, which is an already completed project that just needs to be hacked on (customized)., the custom Flask process (written in pure Python), routes (dispatches) incoming web requests (web addresses, URLs) to Python functions.

Each function develops an appropriate response, either as HTML (styled for human browsers) or JSON (bare bones data, more for machine readers).  We call this a web API.

HTML or "hypertext markup language" is what your web browser is designed to render into web pages, possibly interactive thanks to JavaScript, if you have your JavaScript engine turned on.

JavaScript is also known as ES (ECMAScript) and is not the same as Java.

Python also talks to SQLite databases on the server, to look up and serve the requested information. The application also handles POST requests, with a simple hard-coded string for authentication.

Add chemical elements to the Periodic Table database (Elements table) or new terms to the Glossary database (Glossary table).  No delete or update features have been implemented, as a goal is to keep the application's anatomy fairly simple.

I'm using Python "context managers" to open and close the database files, as needed.

In my forty hour Python course, I take you through building a context manager using contextlib, from the "batteries included" Standard Library.

Forty hours is about right to develop a strong reading knowledge of Python, which in turn provides enough traction to keep improving your own code through practice.

SQLite is also included in the Standard Library, as sqlite3.

The HTML is developed through a Flask component named Jinja2, which allows Python to pass content from the database into a web page that's being built.

Jinja2 uses templates as raw material, very like HTML files, which in turn link to Cascading Style Sheets (CSS files) and any JavaScript (.js files) we might need.

The well-known Django framework, also in Python, is quite similar to Flask in structure, and also includes a templating engine.  Web2py is another one.

A standard development process for writing these things is to have your localhost serve a developer version, the one you hack on, then practice (A) keeping the Github version up to date and (B) maintaining a world readable cloud instance.

We also do a lot with Jupyter Notebooks during the forty hours (or less if the course is accelerated).