-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecite_app.py
More file actions
executable file
·585 lines (547 loc) · 20.3 KB
/
recite_app.py
File metadata and controls
executable file
·585 lines (547 loc) · 20.3 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
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
from flask import Flask, render_template, request, session, redirect, Blueprint
import pymongo
import uuid
import random
import time
import defender
recite_app = Blueprint('recite_app', __name__)
recite_app.secret_key = 'aiueb823hfkah38whwkdnfea874hiwn'
client = pymongo.MongoClient()
db = client.reciter
'''
集合名 lists
id 表格id
username 用户名
listname 表格名
difficulty 难度
en 英文信息
zh 中文信息
timef 创建时间
o 是否为官方
sm 是否有例句
sen 例句
'''
from collections import defaultdict
from flask import abort
# 设置频率限制参数
LIMIT = 10 # 允许的最大请求次数
PERIOD = 10 # 时间窗口(秒)
# 存储IP地址和对应的访问次数及时间戳
visits = defaultdict(list)
def is_rate_limited(ip):
current_time = time.time()
for timestamp in visits[ip]:
# 移除时间窗口之外的记录
if current_time - timestamp > PERIOD:
visits[ip].remove(timestamp)
else:
break
# 如果请求次数超过限制,则返回True
if len(visits[ip]) >= LIMIT:
return True
# 否则,添加当前时间戳并返回False
visits[ip].append(current_time)
return False
AUTO_BOT_UA = ['bot', 'spider', 'crawl']
@recite_app.before_request
def check_bot():
user_agent = request.headers.get('User-Agent', '').lower()
if any(ua in user_agent for ua in AUTO_BOT_UA):
abort(403) # 禁止访问
# 检查HTTP头部信息
@recite_app.before_request
def check_http_headers():
accept = request.headers.get('Accept', '')
if 'text/html' not in accept and 'application/xhtml+xml' not in accept:
abort(403) # 禁止访问
@recite_app.before_request
def limit_requests():
ip = request.remote_addr
if is_rate_limited(ip):
abort(429) # 返回429 Too Many Requests
def get_theme():
theme = session.get('theme')
if theme == None:
theme = 'white'
return theme
@recite_app.route('/lists', methods=["GET"]) # 依据条件展示表格列表
def lists():
username = session.get('username')
difficulty = request.args.get('difficulty')
key = request.args.get('key')
if key == None or key == '':
if difficulty == 'all' or difficulty == None:
lists_o = db.lists.find({'o': True})
lists_o = list(lists_o)
lists_u = db.lists.find({'o': False})
lists_u = list(lists_u)
else:
lists_o = db.lists.find({'difficulty': difficulty, 'o': True})
lists_o = list(lists_o)
lists_u = db.lists.find({'difficulty': difficulty, 'o': False})
lists_u = list(lists_u)
else:
if difficulty == 'all':
lists_o = db.lists.find({'listname': key, 'o': True})
lists_o = list(lists_o)
lists_u = db.lists.find({'listname': key, 'o': False})
lists_u = list(lists_u)
else:
lists_o = db.lists.find({'listname': key, 'difficulty': difficulty, 'o': True})
lists_o = list(lists_o)
lists_u = db.lists.find({'listname': key, 'difficulty': difficulty, 'o': False})
lists_u = list(lists_u)
lists_o.sort(key=lambda x: x['listname'])
lists_u.sort(key=lambda x: x['timef'], reverse=True)
show_mode = request.args.get('show_mode')
if show_mode == None:
show_mode = 'official'
return render_template('recite/lists.html',
t_username=username,
t_lists_o=lists_o,
t_lists_u=lists_u,
t_theme=get_theme(),
t_show_mode=show_mode)
@recite_app.route('/create') # 提供创建词汇表的页面
def create():
if session.get('username') == None:
return redirect('/login')
userdic = db.users.find_one({'username': session['username']})
captcha_text, captcha_image = defender.generate_captcha()
session['captcha'] = captcha_text.lower()
return render_template('recite/create.html',
t_username=session.get('username'),
t_admin=userdic['admin'],
t_theme=get_theme(),
t_captcha_image=captcha_image)
@recite_app.route('/check_create', methods=['POST']) # 处理提供的创建信息
def check_create():
if session.get('username') == None:
return redirect('/login')
user_captcha = request.form.get('user_captcha').lower()
if user_captcha != session['captcha']:
captcha_text, captcha_image = defender.generate_captcha()
session['captcha'] = captcha_text.lower()
userdic = db.users.find_one({'username': session['username']})
return render_template('recite/create.html',
t_username=session.get('username'),
t_admin=userdic['admin'],
t_theme=get_theme(),
t_captcha_image=captcha_image,
t_error='Wrong graph validate code')
wordlist = request.form['wordlist']
listname = request.form['listname']
difficulty = request.form.get('difficulty')
sm = request.form.get('sm')
o = request.form.get('o')
en = []
zh = []
sen = []
if sm == 'y':
sm = True
s = ''
flag = 1
for i in wordlist:
if i == '\n':
continue
if i == '\r':
if flag == 1:
en.append(s)
elif flag == 2:
zh.append(s)
elif flag == 3:
sen.append(s)
s = ''
flag %= 3
flag += 1
else:
s += i
sen.append(s)
else:
sm = False
s = ''
flag = 1
for i in wordlist:
if i == '\n':
continue
if i == '\r':
if flag == 1:
en.append(s)
elif flag == 0:
zh.append(s)
s = ''
flag ^= 1
else:
s += i
zh.append(s)
if o == 'y':
o = True
else:
o = False
id = str(uuid.uuid1())
now = time.localtime()
now_temp = time.strftime("%Y-%m-%d %H:%M", now)
db.lists.insert_one({'id': id,
'username': session.get('username'),
'listname': listname,
'difficulty': difficulty,
'en': en,
'zh': zh,
'timef': now_temp,
'o': o,
'sen': sen,
'sm': sm})
return redirect('/lists')
@recite_app.route('/prepare_recite', methods=['POST']) # 准备开始背诵
def prepare_recite():
if session.get('username') == None:
return redirect('/login')
id = request.form['id']
res = db.lists.find_one({'id': id})
dic = {}
dic['username'] = session.get('username')
dic['pat'] = request.form['pattern']
dic['en'] = res['en']
dic['zh'] = res['zh']
dic['num'] = len(res['en'])
dic['show'] = random.randint(0, dic['num'] - 1)
if res['sm']:
dic['sm'] = True
else:
dic['sm'] = False
dic['sen'] = res['sen']
dic['tong'] = {}
dic['list_id'] = id
dic['list_username'] = res['username']
dic['listname'] = res['listname']
dic['difficulty'] = res['difficulty']
for i in dic['en']:
dic['tong'][i] = 2
dic['fir'] = {}
for i in dic['en']:
dic['fir'][i] = True
db.temp.delete_one({'username': session.get('username')})
db.temp.insert_one(dic)
return redirect('/recite')
@recite_app.route('/recite', methods=['GET']) # 背诵
def recite():
if session.get('username') == None:
return redirect('/login')
dic = db.temp.find_one({'username': session.get('username')})
fir = ""
if dic['fir'][dic['en'][dic['show']]]:
fir = "first time"
if dic['pat'] == 'Learn meaning':
return render_template('recite/recite_meaning.html',
t_username=session.get('username'),
t_en=dic['en'][dic['show']],
t_num=dic['num'],
t_rem=dic['tong'][dic['en'][dic['show']]],
t_fir=fir,
t_pat=dic['pat'],
t_sm=dic['sm'],
t_sen=dic['sen'],
t_theme=get_theme(),
t_listname=dic['listname'])
else:
return render_template('recite/recite_spelling.html',
t_username=session.get('username'),
t_zh=dic['zh'][dic['show']],
t_num=dic['num'],
t_rem=dic['tong'][dic['en'][dic['show']]],
t_fir=fir,
t_pat=dic['pat'],
t_sm=dic['sm'],
t_sen=dic['sen'],
t_theme=get_theme(),
t_listname=dic['listname'])
@recite_app.route('/check_recite', methods=['GET']) # 检查背诵信息
def check_recite():
if session.get('username') == None:
return redirect('/login')
dic = db.temp.find_one({'username': session.get('username')})
flag = False
if dic['pat'] == 'Learn meaning':
res = request.args['know']
if res == 'Know':
if dic['fir'][dic['en'][dic['show']]]:
dic['tong'][dic['en'][dic['show']]] = 0
else:
dic['tong'][dic['en'][dic['show']]] -= 1
else:
dic['tong'][dic['en'][dic['show']]] = 2
else:
res = request.args['ans']
if res == dic['en'][dic['show']]:
if dic['fir'][dic['en'][dic['show']]]:
dic['tong'][dic['en'][dic['show']]] = 0
else:
dic['tong'][dic['en'][dic['show']]] -= 1
else:
dic['tong'][dic['en'][dic['show']]] = 2
flag = True
dic['fir'][dic['en'][dic['show']]] = False
ent = dic['en'][dic['show']]
zht = dic['zh'][dic['show']]
if dic['sm']:
sen = dic['sen'][dic['show']]
else:
sen = ''
if dic['tong'][dic['en'][dic['show']]] <= 0:
dic['num'] -= 1
del dic['en'][dic['show']]
del dic['zh'][dic['show']]
if dic['sm']:
del dic['sen'][dic['show']]
if dic['num'] == 0:
now = time.localtime()
now_temp = time.strftime("%Y-%m-%d %H:%M", now)
userdic = db.users.find_one({'username': session['username']})
flag = True
for i in userdic['list_record']:
if i['id'] == dic['list_id']:
i['timef'] = now_temp
flag = False
break
if flag:
userdic['list_record'].append({'username': dic['list_username'],
'id': dic['list_id'],
'listname': dic['listname'],
'difficulty': dic['difficulty'],
'timef': now_temp})
db.users.update({'username': session['username']}, userdic)
return render_template('recite/finish.html',
t_username=session['username'],
t_theme=get_theme(),
t_listname=dic['listname'])
dic['show'] = random.randint(0, dic['num'] - 1)
db.temp.update({'username': session['username']}, dic)
if flag:
fir = ""
if dic['fir'][dic['en'][dic['show']]]:
fir = "first time"
if dic['pat'] == 'Learn spelling':
return render_template('recite/tip.html',
t_username=session['username'],
t_en=ent,
t_zh=zht,
t_pat=dic['pat'],
t_res=res,
t_num=dic['num'],
t_rem=dic['tong'][dic['en'][dic['show']]],
t_fir=fir,
t_sm=dic['sm'],
t_sen=sen,
t_theme=get_theme(),
t_listname=dic['listname'])
else:
return render_template('recite/tip_meaning.html',
t_username=session['username'],
t_en=ent,
t_zh=zht,
t_pat=dic['pat'],
t_res=res,
t_num=dic['num'],
t_rem=dic['tong'][dic['en'][dic['show']]],
t_fir=fir,
t_sm=dic['sm'],
t_sen=sen,
t_theme=get_theme(),
t_listname=dic['listname'])
return redirect('/recite')
@recite_app.route('/show_tip')
def show_tip():
if session.get('username') == None:
return redirect('/login')
dic = db.temp.find_one({'username': session['username']})
ent = dic['en'][dic['show']]
zht = dic['zh'][dic['show']]
if dic['sm']:
sen = dic['sen'][dic['show']]
else:
sen = ''
fir = ""
if dic['fir'][dic['en'][dic['show']]]:
fir = "first time"
if dic['pat'] == 'Learn spelling':
return render_template('recite/tip.html',
t_username=session['username'],
t_en=ent,
t_zh=zht,
t_pat=dic['pat'],
t_num=dic['num'],
t_rem=dic['tong'][dic['en'][dic['show']]],
t_fir=fir,
t_sm=dic['sm'],
t_sen=sen,
t_theme=get_theme(),
t_listname=dic['listname'])
else:
return render_template('recite/tip_meaning.html',
t_username=session['username'],
t_en=ent,
t_zh=zht,
t_pat=dic['pat'],
t_num=dic['num'],
t_rem=dic['tong'][dic['en'][dic['show']]],
t_fir=fir,
t_sm=dic['sm'],
t_sen=sen,
t_theme=get_theme(),
t_listname=dic['listname'])
# @recite_app.route('/mod_list', methods=['POST'])
# def mod_list():
# o = request.form.get('o')
# if o == 'y':
# o = True
# else:
# o = False
# id = request.form.get('id')
# wordlist = db.lists.find_one({'id': id})
# wordlist['o'] = o
# db.lists.update({'id': id}, wordlist)
# return redirect('/lists')
#
@recite_app.route('/show_list', methods=['GET']) # 展示表格
def show_list():
id = request.args.get('id')
wordlist = db.lists.find_one({'id': id})
if session.get('username') == None:
admin = False
else:
admin = db.users.find_one({'username': session['username']})['admin']
return render_template('recite/show_list.html',
t_username=session.get('username'),
t_wordlist=wordlist,
t_size=len(wordlist['en']),
t_sm=wordlist['sm'],
t_admin=admin,
t_theme=get_theme())
@recite_app.route('/check_del_list', methods=['GET'])
def check_del_list():
if session.get('username') == None:
return redirect('/login')
id = request.args.get('id')
return render_template('recite/check_del_list.html',
t_id=id,
t_username=session.get('username'),
t_theme=get_theme(),
t_listname=db.lists.find_one({'id': id})['listname'])
@recite_app.route('/del_list', methods=['GET']) # 删除表格
def del_list():
if session.get('username') == None:
return redirect('/login')
id = request.args.get('id')
userdic = db.users.find_one({'username': session['username']})
dic = db.lists.find_one({'id': id})
if dic['username'] == session['username'] or userdic['admin']:
db.lists.delete_one({'id': id})
dics = list(db.users.find())
for i in dics:
for j in range(0, len(i['list_record'])):
if i['list_record'][j]['id'] == id:
del i['list_record'][j]
break
db.users.update({'username': i['username']}, i)
return redirect('/lists')
else:
return 'No permission'
@recite_app.route('/modify_list', methods=['GET']) # provide modification page
def modify_list():
if session.get('username') == None:
return redirect('/login')
captcha_text, captcha_image = defender.generate_captcha()
session['captcha'] = captcha_text.lower()
id = request.args.get('id')
dic = db.lists.find_one({'id': id})
userdic = db.users.find_one({'username': session['username']})
if dic['username'] == session['username'] or userdic['admin']:
info = ''
for i in range(0, len(dic['en'])):
info += dic['en'][i] + '\n'
info += dic['zh'][i] + '\n'
if dic['sm']:
info += dic['sen'][i] + '\n'
errorr = request.args.get('error')
if errorr == None:
errorr = ''
return render_template('recite/modify_list.html',
t_id=id,
t_info=info,
t_admin=userdic['admin'],
t_listname=dic['listname'],
t_username=session['username'],
t_theme=get_theme(),
t_captcha_image=captcha_image,
t_error=errorr)
else:
return 'No permission'
@recite_app.route('/modifier', methods=['POST']) # check the modification infomation
def modifier():
if session.get('username') == None:
return redirect('/login')
id = request.form.get('id')
user_captcha = request.form.get('user_captcha').lower()
if user_captcha != session['captcha']:
return redirect('/modify_list?id=' + id + '&error=Wrong graph validate code')
wordlist = request.form.get('wordlist')
listname = request.form.get('listname')
difficulty = request.form.get('difficulty')
sm = request.form.get('sm')
o = request.form.get('o')
en = []
zh = []
sen = []
if sm == 'y':
sm = True
s = ''
flag = 1
for i in wordlist:
if i == '\n':
continue
if i == '\r':
if flag == 1:
en.append(s)
elif flag == 2:
zh.append(s)
elif flag == 3:
sen.append(s)
s = ''
flag %= 3
flag += 1
else:
s += i
sen.append(s)
else:
sm = False
s = ''
flag = 1
for i in wordlist:
if i == '\n':
continue
if i == '\r':
if flag == 1:
en.append(s)
elif flag == 0:
zh.append(s)
s = ''
flag ^= 1
else:
s += i
zh.append(s)
dic = db.lists.find_one({'id': id})
if o == 'y':
o = True
elif o == 'n':
o = False
else:
o = dic['o']
dic['listname'] = listname
dic['difficulty'] = difficulty
dic['en'] = en
dic['zh'] = zh
dic['o'] = o
dic['sen'] = sen
dic['sm'] = sm
db.lists.update({'id': id}, dic)
return redirect('/lists')