-
Notifications
You must be signed in to change notification settings - Fork 2k
/
flash_cards.py
472 lines (403 loc) · 12.3 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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
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__)
nameDB='cards.db'
pathDB='db'
def load_config():
app.config.update(dict(
DATABASE=os.path.join(app.root_path, pathDB, nameDB),
SECRET_KEY='development key',
USERNAME='admin',
PASSWORD='default'
))
app.config.from_envvar('CARDS_SETTINGS', silent=True)
if __name__ == "__main__" or __name__ == "flash_cards":
load_config()
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()
@app.route('/')
def index():
if session.get('logged_in'):
return redirect(url_for('list_db'))
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()
tags = getAllTag()
return render_template('cards.html', cards=cards, tags=tags, 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(query is None):
query = "where type = {0}".format(filter_name)
filter_name = int(filter_name)
if not query:
return redirect(url_for('show'))
db = get_db()
fullquery = "SELECT id, type, front, back, known FROM cards " + \
query + " ORDER BY id DESC"
cur = db.execute(fullquery)
cards = cur.fetchall()
tags = getAllTag()
return render_template('show.html', cards=cards, tags=tags, 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()
tags = getAllTag()
return render_template('edit.html', card=card, tags=tags)
@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('show'))
@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('/memorize')
@app.route('/memorize/<card_type>')
@app.route('/memorize/<card_type>/<card_id>')
def memorize(card_type, card_id=None):
tag = getTag(card_type)
if tag is None:
return redirect(url_for('cards'))
if card_id:
card = get_card_by_id(card_id)
else:
card = get_card(card_type)
if not card:
flash("You've learned all the '" + tag[1] + "' cards.")
return redirect(url_for('show'))
short_answer = (len(card['back']) < 75)
tags = getAllTag()
card_type = int(card_type)
return render_template('memorize.html',
card=card,
card_type=card_type,
short_answer=short_answer, tags=tags)
@app.route('/memorize_known')
@app.route('/memorize_known/<card_type>')
@app.route('/memorize_known/<card_type>/<card_id>')
def memorize_known(card_type, card_id=None):
tag = getTag(card_type)
if tag is None:
return redirect(url_for('cards'))
if card_id:
card = get_card_by_id(card_id)
else:
card = get_card_already_known(card_type)
if not card:
flash("You haven't learned any '" + tag[1] + "' cards yet.")
return redirect(url_for('show'))
short_answer = (len(card['back']) < 75)
tags = getAllTag()
card_type = int(card_type)
return render_template('memorize_known.html',
card=card,
card_type=card_type,
short_answer=short_answer, tags=tags)
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('memorize', card_type=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 or password!'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid username or password!'
else:
session['logged_in'] = True
session.permanent = True # stay logged in
return redirect(url_for('index'))
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'))
def getAllTag():
if not session.get('logged_in'):
return redirect(url_for('login'))
db = get_db()
query = '''
SELECT id, tagName
FROM tags
ORDER BY id ASC
'''
cur = db.execute(query)
tags = cur.fetchall()
return tags
@app.route('/tags')
def tags():
if not session.get('logged_in'):
return redirect(url_for('login'))
tags = getAllTag()
return render_template('tags.html', tags=tags, filter_name="all")
@app.route('/addTag', methods=['POST'])
def add_tag():
if not session.get('logged_in'):
return redirect(url_for('login'))
db = get_db()
db.execute('INSERT INTO tags (tagName) VALUES (?)',
[request.form['tagName']])
db.commit()
flash('New tag was successfully added.')
return redirect(url_for('tags'))
@app.route('/editTag/<tag_id>')
def edit_tag(tag_id):
if not session.get('logged_in'):
return redirect(url_for('login'))
tag = getTag(tag_id)
return render_template('editTag.html', tag=tag)
@app.route('/updateTag', methods=['POST'])
def update_tag():
if not session.get('logged_in'):
return redirect(url_for('login'))
db = get_db()
command = '''
UPDATE tags
SET
tagName = ?
WHERE id = ?
'''
db.execute(command,
[request.form['tagName'],
request.form['tag_id']
])
db.commit()
flash('Tag saved.')
return redirect(url_for('tags'))
def init_tag():
if not session.get('logged_in'):
return redirect(url_for('login'))
db = get_db()
db.execute('INSERT INTO tags (tagName) VALUES (?)',
["general"])
db.commit()
db.execute('INSERT INTO tags (tagName) VALUES (?)',
["code"])
db.commit()
db.execute('INSERT INTO tags (tagName) VALUES (?)',
["bookmark"])
db.commit()
@app.route('/show')
def show():
if not session.get('logged_in'):
return redirect(url_for('login'))
tags = getAllTag()
return render_template('show.html', tags=tags, filter_name="")
def getTag(tag_id):
if not session.get('logged_in'):
return redirect(url_for('login'))
db = get_db()
query = '''
SELECT id, tagName
FROM tags
WHERE id = ?
'''
cur = db.execute(query, [tag_id])
tag = cur.fetchone()
return tag
@app.route('/bookmark/<card_type>/<card_id>')
def bookmark(card_type, card_id):
if not session.get('logged_in'):
return redirect(url_for('login'))
db = get_db()
db.execute('UPDATE cards SET type = ? WHERE id = ?',[card_type,card_id])
db.commit()
flash('Card saved.')
return redirect(url_for('memorize', card_type=card_type))
@app.route('/list_db')
def list_db():
if not session.get('logged_in'):
return redirect(url_for('login'))
dbs = [f for f in os.listdir(pathDB) if os.path.isfile(os.path.join(pathDB, f))]
dbs = list(filter(lambda k: '.db' in k, dbs))
return render_template('listDb.html', dbs=dbs)
@app.route('/load_db/<name>')
def load_db(name):
if not session.get('logged_in'):
return redirect(url_for('login'))
global nameDB
nameDB=name
load_config()
handle_old_schema()
return redirect(url_for('memorize', card_type="1"))
@app.route('/create_db')
def create_db():
if not session.get('logged_in'):
return redirect(url_for('login'))
return render_template('createDb.html')
@app.route('/init', methods=['POST'])
def init():
if not session.get('logged_in'):
return redirect(url_for('login'))
global nameDB
nameDB = request.form['dbName'] + '.db'
load_config()
init_db()
init_tag()
return redirect(url_for('index'))
def check_table_tag_exists():
db = get_db()
cur = db.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='tags'")
result = cur.fetchone()
return result
def create_tag_table():
db = get_db()
with app.open_resource('data/handle_old_schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
def handle_old_schema():
result = check_table_tag_exists()
if(result is None):
create_tag_table()
init_tag()
def get_card_already_known(type):
db = get_db()
query = '''
SELECT
id, type, front, back, known
FROM cards
WHERE
type = ?
and known = 1
ORDER BY RANDOM()
LIMIT 1
'''
cur = db.execute(query, [type])
return cur.fetchone()
@app.route('/mark_unknown/<card_id>/<card_type>')
def mark_unknown(card_id, card_type):
if not session.get('logged_in'):
return redirect(url_for('login'))
db = get_db()
db.execute('UPDATE cards SET known = 0 WHERE id = ?', [card_id])
db.commit()
flash('Card marked as unknown.')
return redirect(url_for('memorize_known', card_type=card_type))
if __name__ == '__main__':
app.run(host='0.0.0.0')