import datetime as dt
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
The whole application hinges on a Flask object, an instance of the main class of the
framework. Instantiating the class with name lets the object inherit the application name
(i.e., main) when the script is executed, for example, from a shell:
# the application object from the main Flask class
app = Flask(__name__)
The next step is to do some configuration for the new application object. In particular, we
need to provide a database filename:
# override config from environment variable
app.config.update(dict(
DATABASE=os.path.join(app.root_path, ‘tradechat.db’),
# the SQLite3 database file (“TC database”)
DEBUG=True,
SECRET_KEY=‘secret_key’,
# use secure key here for real applications
))
app.config.from_envvar(‘TC_SETTINGS’, silent=True)
# do not complain if no config file exists
Having provided the path and filename of the database, the function connect_db connects
to the database and returns the connection object:
def connect_db():
”’ Connects to the TC database.”’
rv = sqlite3.connect(app.config[‘DATABASE’])
rv.row_factory = sqlite3.Row
return rv
Flask uses an object called g to store global data and other objects. For example, web
applications serving large numbers of users make it necessary to connect regularly to
databases. It would be inefficient to instantiate a connection object every time a database
operation has to be executed. One can rather store such a connection object in the attribute
sqlite_db of the g object. The function get_db makes use of this approach in that a new
database connection is opened only when there is no connection object stored in the g
object already:
def get_db():
”’ Opens a new connection to the TC database. ”’
if not hasattr(g, ‘sqlite_db’):
# open only if none exists yet
g.sqlite_db = connect_db()
return g.sqlite_db
At least once, we need to create the tables in the database. Calling the function init_db
for a second time will delete all information previously stored in the database (according
to the SQL schema used):
def init_db():
”’ Creates the TC database tables.”’
with app.app_context():
db = get_db()
with app.open_resource(‘tables.sql’, mode=‘r’) as f:
db.cursor().executescript(f.read())
# creates entries and users tables
db.commit()
The function close_db closes the database connection if one exists in the g object. For the
first time (and for sure not the last time), we encounter a Flask function decorator, i.e.,
@app.teardown_appcontext. This decorator ensures that the respective function is called