# -*- coding: utf-8 -*-
from flask import Flask
from flask import g
import os
import psycopg2
from contextlib import closing

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
)
"""

app = Flask(__name__)
app.config['DATABASE'] = os.environ.get(
    'DATABASE_URL', 'dbname=learning_journal'
)


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 closing(connect_db()) as db:
        db.cursor().execute(DB_SCHEMA)
        db.commit()


def get_database_connection():
    db = getattr(g, 'db', None)
    if db is None:
        g.db = db = connect_db()
    return db


@app.teardown_request
def teardown_request(exception):
    db = getattr(g, 'db', None)
    if db is not None:
        if exception and isinstance(exception, psycopg2.Error):
            # if there was a problem with the database, rollback any
            # existing transaction
            db.rollback()
        else:
            # otherwise, commit
            db.commit()
        db.close()


@app.route('/')
def hello():
    return u'Hello world!'

if __name__ == '__main__':
    app.run(debug=True)

@@ -118,16 +118,33 @@
 closing%0A
+import datetime%0A%0A
 %0ADB_SCHE
@@ -328,16 +328,106 @@
 %0A)%0A%22%22%22%0A%0A
+DB_ENTRY_INSERT = %22%22%22%0AINSERT INTO entries (title, text, created) VALUES (%25s, %25s, %25s)%0A%22%22%22%0A%0A
 app = Fl
@@ -1420,16 +1420,300 @@
 ose()%0A%0A%0A
+def write_entry(title, text):%0A    if not title or not text:%0A        raise ValueError(%22Title and text required for writing an entry%22)%0A    con = get_database_connection()%0A    cur = con.cursor()%0A    now = datetime.datetime.utcnow()%0A    cur.execute(DB_ENTRY_INSERT, %5Btitle, text, now%5D)%0A%0A%0A
 @app.rou

Add write_entries function.