-
Notifications
You must be signed in to change notification settings - Fork 0
/
journal.py
205 lines (164 loc) · 5.68 KB
/
journal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# -*- coding: utf-8 -*-
import os
import datetime
import psycopg2
from contextlib import closing
from passlib.hash import pbkdf2_sha256
from flask import Flask, g, render_template, session
from flask import abort, request, url_for, redirect
from flask.ext.markdown import Markdown
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
);
"""
DB_INSERT_ENTRY = """
INSERT INTO entries (title, text, created) VALUES (%s, %s, %s)
"""
DB_SELECT_ENTRIES_LIST = """
SELECT id, title, text, created FROM entries ORDER BY created DESC
"""
DB_SELECT_ENTRY = """
SELECT * FROM entries WHERE id = %s
"""
DB_UPDATE_ENTRY = """
UPDATE entries SET title = %s, text = %s WHERE id = %s
"""
app = Flask(__name__)
app.config['DATABASE'] = os.environ.get(
'DATABASE_URL', 'dbname=learning_journal user=charlesgust'
)
# add the following two settings just below
app.config['ADMIN_USERNAME'] = os.environ.get(
'ADMIN_USERNAME', 'admin'
)
app.config['ADMIN_PASSWORD'] = os.environ.get(
'ADMIN_PASSWORD', pbkdf2_sha256.encrypt('admin')
)
app.config['SECRET_KEY'] = os.environ.get(
'FLASK_SECRET_KEY', 'sooperseekritvaluenooneshouldknow'
)
Markdown(app, extensions=['codehilite'])
def connect_db():
""" return a connection to the configured databse """
return psycopg2.connect(app.config['DATABASE'])
def init_db():
""" initialize the dabatase 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()
def write_entry(title, text):
if not title or not text:
raise ValueError("Title and text required for writing an entry")
con = get_database_connection()
cur = con.cursor()
now = datetime.datetime.utcnow()
cur.execute(DB_INSERT_ENTRY, [title, text, now])
def get_all_entries():
""" return a list of all entries as dicts """
con = get_database_connection()
cur = con.cursor()
cur.execute(DB_SELECT_ENTRIES_LIST)
keys = ('id', 'title', 'text', 'created')
return [dict(zip(keys, row)) for row in cur.fetchall()]
def get_entry(entry_id):
""" return the entry corresponding to the primary key """
conn = get_database_connection()
cur = conn.cursor()
cur.execute(DB_SELECT_ENTRY, (entry_id,))
keys = ('id', 'title', 'text', 'created')
return dict(zip(keys, cur.fetchone()))
def update_entry(entry_id, entry_title, entry_text):
""" update the title and text of a single (unique) entry """
if not entry_title or not entry_text:
raise ValueError("Update to database entry must have title and text")
con = get_database_connection()
cur = con.cursor()
cur.execute(DB_UPDATE_ENTRY, (entry_title, entry_text, entry_id))
return
def find_entry(entries, entry_id):
for entry in entries:
if entry.id == entry_id:
return entry_title
raise IndexError("Cannot find entry in database by entry identifer")
@app.route('/')
def show_entries():
session['editing'] = False
entries = get_all_entries()
default_entry = {'title': '', 'text': ''}
return render_template('list_entries.html',
entries=entries,
default_entry=default_entry)
@app.route('/add', methods=['POST'])
def add_entry():
try:
write_entry(request.form['title'], request.form['text'])
except psycopg2.Error:
# this will catch any errors generated by the database
abort(500)
return redirect(url_for('show_entries'))
@app.route('/edit/<entry_id>')
def edit_entry(entry_id):
session['editing'] = True
entries = get_all_entries()
# CMGTODO: since just hit the DB and have all the entries, the
# default_entry could just come from a lookup in entries.
default_entry = get_entry(entry_id)
return render_template('list_entries.html',
entries=entries,
default_entry=default_entry)
@app.route('/submit/<entry_id>', methods=['POST'])
def submit_entry(entry_id):
try:
update_entry(entry_id, request.form['title'], request.form['text'])
except psycopg2.Error:
# this will catch any errors generated by the database
abort(500)
return redirect(url_for('show_entries'))
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
try:
do_login(request.form['username'].encode('utf-8'),
request.form['password'].encode('utf-8'))
except ValueError:
error = "Login Failed"
else:
return redirect(url_for('show_entries'))
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
session.pop('logged_in', None)
return redirect(url_for('show_entries'))
def do_login(username='', passwd=''):
if username != app.config['ADMIN_USERNAME']:
raise ValueError
if not pbkdf2_sha256.verify(passwd, app.config['ADMIN_PASSWORD']):
raise ValueError
session['logged_in'] = True
if __name__ == "__main__":
app.run(debug=True)