# -*- coding: utf-8 -*-

import os

# A library of stuff to use with "with", ie context.
from contextlib import closing

from flask import Flask

import psycopg2


DB_SCHEMA = """
DROP TABLE IF EXISTS entries;
CREATE TABLE entries (
    id serial PRIMARY KEY,
    title VARCHAR (127) NOT NULL,
    text TEXT NOT NULL,
    created TIMESTAMP NOT NULL
)
"""


# I still don't know what the significance of __name__ is here.
app = Flask(__name__)

# The value of the third string here called a libpq connection string.
app.config['DATABASE'] = os.environ.get(
    'DATABASE_URL', 'dbname=learning_journal user=fried'
)

def connect_db():
    ''' Return a connection to the configured database. '''

    return psycopg2.connect(app.config['DATABASE'])

def init_db():
    ''' Initialize the database using DB_SCHEMA.

    WARNING: Executing this function will drop existing tables. '''

    # with blocks clean up their context after execution
    # (( closing() is the context ))
    with closing(connect_db()) as db:

        db.cursor().execute(DB_SCHEMA)
        # Cursors do transactions.
        # Transactions must be committed before they take effect.
        db.commit()





@app.route('/')
def hello():
    # Ahh, non-unicode default string encoding... The joys of python 2.
    return u'Hello world!'

if __name__ == '__main__':

    app.run(debug=True)
















@@ -29,16 +29,17 @@
 ort os%0A%0A
+%0A
 # A libr
@@ -115,16 +115,17 @@
 losing%0A%0A
+%0A
 from fla
@@ -141,16 +141,515 @@
  Flask%0A%0A
+# g is a %22local global%22 Flask provides.%0A# This just means it's an object that stores state to pass between funx.%0A# It's a grab bag object.%0A# I would have architected this to use a purpose-named class, such as%0A# %22DatabaseConnector%22 or something, to keep the various state types%0A# separate from each other, but maybe that's too much overhead?%0A# I don't know if it's better to namespace every piece of conceptually%0A# distinct state or just toss it all in one big box like this...%0Afrom flask import g%0A%0A%0A
 import p
@@ -1670,17 +1670,2247 @@
 mmit()%0A%0A
-%0A
+def get_database_connection():%0A%0A    # If this was implemented with keyword arguments, it would be%0A    # easier to understand.%0A    # g appears to be a flask-native object whose purpose is to hold%0A    # connections and pass them between functions without using return.%0A    # That is what they mean by %22local globals,%22 I think.%0A    # What this assignment is doing is:%0A    # 1. Fetching the flask.g object%0A    # 2. Returning its 'db' attribute%0A    # 3. Using None as the default value (I think)%0A    db = getattr(g, 'db', None)%0A%0A    # This part creates a database connection if None exists and%0A    # assigns it to flask.g so it sticks around in global scope under%0A    # the aegis of that wandering object.%0A    # I think the g stands for %22global%22.%0A    if db is None:%0A        # Remember, g comes from the flask library.%0A        g.db = db = connect_db()%0A%0A    # If flask.g has a db in it, that db is passed to whatever called%0A    # get_database_connection() here.%0A    # If flask.g has no db in it, this makes a new connection and%0A    # passes it to whatever called get_database_connection() here.%0A    return db%0A%0A# Teardown requests happen after the execution of a full%0A# HTTP request-reponse cycle, even if the response is precluded by%0A# an unhandled exception.%0A@app.teardown_request%0Adef teardown_request(exception):%0A%0A    # How Flask wants me to shuttle global scope around.%0A    # It feels like pulling state out of a bag.%0A    db = getattr(g, 'db', None)%0A%0A    # Wait, why is this check being done outside of%0A    # get_database_connection()? Can teardown_request() be called when%0A    # there is no database and there isn't supposed to be a database?%0A    if db is not None:%0A%0A        # %22if there was a problem with the database, rollback any%0A        # existing transaction%22%0A        # So teardown_request should never make a database connection,%0A        # only clean up existing ones or save the database state. OK.%0A        db.rollback()%0A%0A    else:%0A%0A        db.commit()%0A%0A    # This will shut down the db connection inside flask.g, too, if I%0A    # understand correctly.%0A    # It looks like HTTP request-response cycles make a connection,%0A    # do stuff in it, and then call teardown_request() to ensure it's%0A    # handled cleanly.%0A    db.close()
 %0A%0A%0A@app.

Set up teardown_request()