# -*- coding: utf-8 -*-
from contextlib import closing
import psycopg2
import os
import logging
from pyramid.config import Configurator
from pyramid.session import SignedCookieSessionFactory
from pyramid.view import view_config
from waitress import serve


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


logging.basicConfig()
log = logging.getLogger(__file__)


@view_config(route_name='home', renderer='string')
def home(request):
    return "Hello World"


def connect_db(settings):
    """Return a connection to the configured database"""
    return psycopg2.connect(settings['db'])


def init_db():
    """Create database dables defined by DB_SCHEMA

    Warning: This function will not update existing table definitions
    """
    settings = {}
    settings['db'] = os.environ.get(
        'DATABASE_URL', 'dbname=learning_journal user=aabulota'
    )
    with closing(connect_db(settings)) as db:
        db.cursor().execute(DB_SCHEMA)
        db.commit()


def main():
    """Create a configured wsgi app"""
    settings = {}
    settings['reload_all'] = os.environ.get('DEBUG', True)
    settings['debug_all'] = os.environ.get('DEBUG', True)
    settings['db'] = os.environ.get(
        'DATABASE_URL', 'dbname=learning_journal user=aabulota'
    )
    # secret value for session signing:
    secret = os.environ.get('JOURNAL_SESSION_SECRET', 'itsaseekrit')
    session_factory = SignedCookieSessionFactory(secret)
    # configuration setup
    config = Configurator(
        settings=settings,
        session_factory=session_factory
    )
    config.add_route('home', '/')
    config.scan()
    app = config.make_wsgi_app()
    return app


if __name__ == '__main__':
    app = main()
    port = os.environ.get('PORT', 5000)
    serve(app, host='0.0.0.0', port=port)

@@ -17,16 +17,87 @@
 f-8 -*-%0A
+# import transaction%0Afrom pyramid.events import NewRequest, subscriber%0A
 from con
@@ -319,17 +319,32 @@
 t serve%0A
+import datetime
 %0A
-
 %0ADB_SCHE
@@ -513,16 +513,488 @@
 )%0A%22%22%22%0A%0A%0A
+INSERT_ENTRY = %22%22%22%0AINSERT INTO entries (title, text, created) VALUES (%25s, %25s, %25s)%0A%22%22%22%0A%0A%0ADB_ENTRIES_LIST = %22%22%22%0ASELECT id, title, text, created FROM entries ORDER BY created DESC%0A%22%22%22%0A%0A%0Adef read_entries(request):%0A    %22%22%22return a list of all entries as dicts%22%22%22%0A    cursor = request.db.cursor()%0A    cursor.execute(DB_ENTRIES_LIST)%0A    keys = ('id', 'title', 'text', 'created')%0A    entries = %5Bdict(zip(keys, row)) for row in cursor.fetchall()%5D%0A    return %7B'entries': entries%7D%0A%0A
 logging.
@@ -1642,24 +1642,902 @@
 .commit()%0A%0A%0A
+@subscriber(NewRequest)%0Adef open_connection(event):%0A    request = event.request%0A    settings = request.registry.settings%0A    request.db = connect_db(settings)%0A    request.add_finished_calllback(close_connection)%0A%0A%0Adef close_connection(request):%0A    %22%22%22close the database connection for this request%0A%0A    If there has been an error in the processing of the request, abort any%0A    open transactions.%0A    %22%22%22%0A    db = getattr(request, 'db', None)%0A    if db is not None:%0A        if request.exception is not None:%0A            db.rollback()%0A        else:%0A            db.commit()%0A        request.db.close()%0A%0A%0Adef write_entry(request):%0A    %22%22%22write a single entry to the database%22%22%22%0A    title = request.params.get('title', None)%0A    text = request.params.get('text', None)%0A    created = datetime.datetime.utcnow()%0A    request.db.cursor().execute(INSERT_ENTRY, %5Btitle, text, created%5D)%0A%0A%0A
 def main():%0A
@@ -3103,22 +3103,59 @@
 factory%0A
-
     )%0A
+    config.include('pyramid_jinja2')%0A
     conf

Set up testing for reading and writing entries, created code for a renderer add-on