-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp-easier.py
104 lines (82 loc) · 2.93 KB
/
app-easier.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
import os,json
from flask import Flask,render_template,g
from sqlite3 import dbapi2 as sqlite3
''' ------------------------------- setup and initialize app ------------------------------- '''
app = Flask(__name__)
app.config.update(dict(
DATABASE='todos.db',
DEBUG=True,
USERNAME='admin',
PASSWORD='default'
))
''' ------------------------------- your routes go here ------------------------------- '''
@app.route('/')
def index():
return render_template('index.html')
''' ------------------------------- helper functions for accessing database ------------------------------- '''
def get_by_id(todo_id):
''' returns a dictionary representation of the todo with the id todo_id '''
db = get_db()
cur = db.execute('SELECT * FROM todos WHERE rowid = ?', [todo_id])
return cur.fetchone()
def get_all():
'''returns an array of todos'''
db = get_db()
cur = db.execute('SELECT * FROM todos ORDER BY id DESC')
return cur.fetchall()
def add_new(item):
'''create todo with the values in item (a dictionary). returns the id of the newly added todo '''
db = get_db()
placeholders = ', '.join(['?'] * len(item))
columns = ', '.join(item.keys())
query = 'INSERT INTO todos (%s) VALUES (%s)' % (columns, placeholders)
cur = db.execute(query, item.values())
new_item_id = cur.lastrowid
db.commit()
return new_item_id
def update(todo_id, item):
'''update todo with the id todo_id with the values in item (a dictionary)'''
db = get_db()
for key,val in item.iteritems():
query = 'UPDATE todos SET %s = ? WHERE rowid = ?' % (key)
db.execute(query, [val, todo_id])
db.commit()
def delete(todo_id):
'''delete todo with the id todo_id'''
db = get_db()
cur = db.cursor().execute('DELETE FROM todos WHERE rowid = ?', [int(todo_id)])
db.commit()
def dict_factory(cursor, row):
""" Makes sqlite3 return dictionaries instead of row objects."""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def connect_db():
"""Connects to the specific database."""
conn = sqlite3.connect(app.config['DATABASE'])
conn.row_factory = dict_factory
return conn
def init_db():
"""Creates the database tables."""
with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
if __name__ == '__main__':
init_db()
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)