forked from jwasham/computer-science-flash-cards
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flash_cards.py
281 lines (227 loc) · 6.95 KB
/
flash_cards.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
app = Flask(__name__)
app.config.from_object(__name__)
# Load default config and override config from an environment variable
app.config.update(dict(
DATABASE=os.path.join(app.root_path, 'db', 'cards.db'),
SECRET_KEY='development key',
USERNAME='admin',
PASSWORD='default'
))
app.config.from_envvar('CARDS_SETTINGS', silent=True)
def connect_db():
rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv
def init_db():
db = get_db()
with app.open_resource('data/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()
# -----------------------------------------------------------
# Uncomment and use this to initialize database, then comment it
# You can rerun it to pave the database and start over
# @app.route('/initdb')
# def initdb():
# init_db()
# return 'Initialized the database.'
@app.route('/')
def index():
if session.get('logged_in'):
return redirect(url_for('general'))
else:
return redirect(url_for('login'))
@app.route('/cards')
def cards():
if not session.get('logged_in'):
return redirect(url_for('login'))
db = get_db()
query = '''
SELECT id, type, front, back, known
FROM cards
ORDER BY id DESC
'''
cur = db.execute(query)
cards = cur.fetchall()
return render_template('cards.html', cards=cards, filter_name="all")
@app.route('/filter_cards/<filter_name>')
def filter_cards(filter_name):
if not session.get('logged_in'):
return redirect(url_for('login'))
filters = {
"all": "where 1 = 1",
"general": "where type = 1",
"code": "where type = 2",
"known": "where known = 1",
"unknown": "where known = 0",
}
query = filters.get(filter_name)
if not query:
return redirect(url_for('cards'))
db = get_db()
fullquery = "SELECT id, type, front, back, known FROM cards " + query + " ORDER BY id DESC"
cur = db.execute(fullquery)
cards = cur.fetchall()
return render_template('cards.html', cards=cards, filter_name=filter_name)
@app.route('/add', methods=['POST'])
def add_card():
if not session.get('logged_in'):
return redirect(url_for('login'))
db = get_db()
db.execute('INSERT INTO cards (type, front, back) VALUES (?, ?, ?)',
[request.form['type'],
request.form['front'],
request.form['back']
])
db.commit()
flash('New card was successfully added.')
return redirect(url_for('cards'))
@app.route('/edit/<card_id>')
def edit(card_id):
if not session.get('logged_in'):
return redirect(url_for('login'))
db = get_db()
query = '''
SELECT id, type, front, back, known
FROM cards
WHERE id = ?
'''
cur = db.execute(query, [card_id])
card = cur.fetchone()
return render_template('edit.html', card=card)
@app.route('/edit_card', methods=['POST'])
def edit_card():
if not session.get('logged_in'):
return redirect(url_for('login'))
selected = request.form.getlist('known')
known = bool(selected)
db = get_db()
command = '''
UPDATE cards
SET
type = ?,
front = ?,
back = ?,
known = ?
WHERE id = ?
'''
db.execute(command,
[request.form['type'],
request.form['front'],
request.form['back'],
known,
request.form['card_id']
])
db.commit()
flash('Card saved.')
return redirect(url_for('cards'))
@app.route('/delete/<card_id>')
def delete(card_id):
if not session.get('logged_in'):
return redirect(url_for('login'))
db = get_db()
db.execute('DELETE FROM cards WHERE id = ?', [card_id])
db.commit()
flash('Card deleted.')
return redirect(url_for('cards'))
@app.route('/general')
@app.route('/general/<card_id>')
def general(card_id=None):
if not session.get('logged_in'):
return redirect(url_for('login'))
return memorize("general", card_id)
@app.route('/code')
@app.route('/code/<card_id>')
def code(card_id=None):
if not session.get('logged_in'):
return redirect(url_for('login'))
return memorize("code", card_id)
def memorize(card_type, card_id):
if card_type == "general":
type = 1
elif card_type == "code":
type = 2
else:
return redirect(url_for('cards'))
if card_id:
card = get_card_by_id(card_id)
else:
card = get_card(type)
if not card:
flash("You've learned all the " + card_type + " cards.")
return redirect(url_for('cards'))
short_answer = (len(card['back']) < 75)
return render_template('memorize.html',
card=card,
card_type=card_type,
short_answer=short_answer)
def get_card(type):
db = get_db()
query = '''
SELECT
id, type, front, back, known
FROM cards
WHERE
type = ?
and known = 0
ORDER BY RANDOM()
LIMIT 1
'''
cur = db.execute(query, [type])
return cur.fetchone()
def get_card_by_id(card_id):
db = get_db()
query = '''
SELECT
id, type, front, back, known
FROM cards
WHERE
id = ?
LIMIT 1
'''
cur = db.execute(query, [card_id])
return cur.fetchone()
@app.route('/mark_known/<card_id>/<card_type>')
def mark_known(card_id, card_type):
if not session.get('logged_in'):
return redirect(url_for('login'))
db = get_db()
db.execute('UPDATE cards SET known = 1 WHERE id = ?', [card_id])
db.commit()
flash('Card marked as known.')
return redirect(url_for(card_type))
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
session.permanent = True # stay logged in
return redirect(url_for('cards'))
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
session.pop('logged_in', None)
flash("You've logged out")
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(host='0.0.0.0')