-
Notifications
You must be signed in to change notification settings - Fork 0
/
flask-compose-poc.py
81 lines (66 loc) · 1.8 KB
/
flask-compose-poc.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
from flask import Flask, render_template, g, request, redirect, url_for
import psycopg2
import humanize
app = Flask(__name__)
def get_db():
"""
Returns the connection to the database, opening a new
one if there is none
"""
if not hasattr(g, 'db'):
g.db = psycopg2.connect(dbname='flaskapp',
user='flaskapp',
password='hunter2',
host='db')
return g.db
@app.teardown_appcontext
def close_db(error):
"""
Closes the database connection on teardown
"""
if hasattr(g, 'db'):
g.db.close()
@app.route('/')
def show_guestbook():
# Let's show all posts from the last week, with a maximum of
# 100 posts
sql = """
SELECT
author, comment_text, posted_at
FROM
guestbook
WHERE
posted_at >= now() - interval '1 week'
ORDER BY
posted_at DESC
LIMIT
100;
"""
cur = get_db().cursor()
cur.execute(sql)
posts = []
for post_in_db in cur.fetchall():
posts.append({
'author': post_in_db[0],
'comment_text': post_in_db[1],
'posted_at': humanize.naturaltime(post_in_db[2])
})
cur.close()
return render_template('index.html', posts=posts)
@app.route('/add', methods=["POST"])
def add_post():
sql = """
INSERT INTO
guestbook
(author, comment_text, posted_at)
VALUES
(%s, %s, now());
"""
db = get_db()
cur = db.cursor()
cur.execute(sql, (request.form['author'],
request.form['comment_text']))
db.commit()
return redirect(url_for('show_guestbook'))
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)