-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
71 lines (53 loc) · 1.28 KB
/
db.py
File metadata and controls
71 lines (53 loc) · 1.28 KB
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
import os
import urlparse
import psycopg2
def create_connection():
url = urlparse.urlparse(os.environ["DATABASE_URL"])
return psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
def run_sql(sql, params=(), fetch=False):
conn = create_connection()
cursor = conn.cursor()
cursor.execute(sql, params)
rows = []
if fetch:
rows = cursor.fetchall()
else:
conn.commit()
cursor.close()
conn.close()
return rows
def create_messages_table():
run_sql(
"""
CREATE TABLE messages (id serial PRIMARY KEY, username text, message text);
"""
)
def insert_message(username, message):
username = username.encode('ascii', 'ignore')
message = message.encode('ascii', 'ignore')
run_sql(
"""
INSERT INTO messages (username, message) VALUES (%s, %s);
""",
(username, message)
)
def get_latest_messages():
rows = run_sql(
"""
SELECT * FROM messages ORDER BY id DESC LIMIT 15;
""",
fetch=True
)
return [
{
'id': r[0],
'username': r[1],
'text': r[2]
} for r in rows
]