1
0
Fork 0

修改了部分代码的书写规划,如注释,空格等

refactor-wangyu
汪瑜 2023-06-01 20:51:58 +08:00
parent 4241cc3a6d
commit 66772b2f8b
12 changed files with 98 additions and 90 deletions

View File

@ -5,11 +5,11 @@ from UseSqlite import InsertQuery, RecordQuery
def md5(s): def md5(s):
''' """
MD5摘要 MD5摘要
:param str: 字符串 :param str: 字符串
:return: 经MD5以后的字符串 :return: 经MD5以后的字符串
''' """
h = hashlib.md5(s.encode(encoding='utf-8')) h = hashlib.md5(s.encode(encoding='utf-8'))
return h.hexdigest() return h.hexdigest()
@ -46,13 +46,13 @@ def check_username_availability(username):
def change_password(username, old_password, new_password): def change_password(username, old_password, new_password):
''' """
修改密码 修改密码
:param username: 用户名 :param username: 用户名
:param old_password: 旧的密码 :param old_password: 旧的密码
:param new_password: 新密码 :param new_password: 新密码
:return: 修改成功:True 否则:False :return: 修改成功:True 否则:False
''' """
if not verify_user(username, old_password): # 旧密码错误 if not verify_user(username, old_password): # 旧密码错误
return False return False
# 将用户名和密码一起加密,以免暴露不同用户的相同密码 # 将用户名和密码一起加密,以免暴露不同用户的相同密码
@ -69,6 +69,7 @@ def get_expiry_date(username):
else: else:
return user.expiry_date return user.expiry_date
class UserName: class UserName:
def __init__(self, username): def __init__(self, username):
self.username = username self.username = username

View File

@ -9,6 +9,7 @@
import sqlite3 import sqlite3
class Sqlite3Template: class Sqlite3Template:
def __init__(self, db_fname): def __init__(self, db_fname):
self.db_fname = db_fname self.db_fname = db_fname
@ -72,7 +73,6 @@ class RecordQuery(Sqlite3Template):
return result return result
if __name__ == '__main__': if __name__ == '__main__':
#iq = InsertQuery('RiskDB.db') #iq = InsertQuery('RiskDB.db')

View File

@ -6,6 +6,7 @@
from wordfreqCMD import remove_punctuation, freq, sort_in_descending_order from wordfreqCMD import remove_punctuation, freq, sort_in_descending_order
import string import string
class WordFreq: class WordFreq:
def __init__(self, s): def __init__(self, s):
self.s = remove_punctuation(s) self.s = remove_punctuation(s)

View File

@ -1,10 +1,10 @@
''' """
Yaml.py Yaml.py
配置文件包括: 配置文件包括:
./static/config.yml ./static/config.yml
./layout/partial/header.html ./layout/partial/header.html
./layout/partial/footer.html ./layout/partial/footer.html
''' """
import yaml as YAML import yaml as YAML
import os import os

View File

@ -8,10 +8,10 @@ accountService = Blueprint("accountService", __name__)
### Sign-up, login, logout ### ### Sign-up, login, logout ###
@accountService.route("/signup", methods=['GET', 'POST']) @accountService.route("/signup", methods=['GET', 'POST'])
def signup(): def signup():
''' """
注册 注册
:return: 根据注册是否成功返回不同界面 :return: 根据注册是否成功返回不同界面
''' """
if request.method == 'GET': if request.method == 'GET':
# GET方法直接返回注册页面 # GET方法直接返回注册页面
return render_template('signup.html') return render_template('signup.html')
@ -45,10 +45,10 @@ def signup():
@accountService.route("/login", methods=['GET', 'POST']) @accountService.route("/login", methods=['GET', 'POST'])
def login(): def login():
''' """
登录 登录
:return: 根据登录是否成功返回不同页面 :return: 根据登录是否成功返回不同页面
''' """
if request.method == 'GET': if request.method == 'GET':
# GET请求 # GET请求
return render_template('login.html') return render_template('login.html')
@ -73,10 +73,10 @@ def login():
@accountService.route("/logout", methods=['GET', 'POST']) @accountService.route("/logout", methods=['GET', 'POST'])
def logout(): def logout():
''' """
登出 登出
:return: 重定位到主界面 :return: 重定位到主界面
''' """
# 将session标记为登出状态 # 将session标记为登出状态
session['logged_in'] = False session['logged_in'] = False
return redirect(url_for('mainpage')) return redirect(url_for('mainpage'))
@ -84,10 +84,10 @@ def logout():
@accountService.route("/reset", methods=['GET', 'POST']) @accountService.route("/reset", methods=['GET', 'POST'])
def reset(): def reset():
''' """
重设密码 重设密码
:return: 返回适当的页面 :return: 返回适当的页面
''' """
# 下列方法用于防止未登录状态下的修改密码 # 下列方法用于防止未登录状态下的修改密码
if not session.get('logged_in'): if not session.get('logged_in'):
return render_template('login.html') return render_template('login.html')

View File

@ -52,7 +52,7 @@ def article():
max(1, int(request.args.get("page", 1))), _article_number // _page_size + (_article_number % _page_size > 0) max(1, int(request.args.get("page", 1))), _article_number // _page_size + (_article_number % _page_size > 0)
) # 最小的page是1 ) # 最小的page是1
except ValueError: except ValueError:
return "page parmas must be int!" return "page params must be int!"
_articles = get_page_articles(_cur_page, _page_size) _articles = get_page_articles(_cur_page, _page_size)
for article in _articles: # 获取每篇文章的title for article in _articles: # 获取每篇文章的title

View File

@ -65,10 +65,10 @@ def get_difficulty_level_for_user(d1, d2):
def revert_dict(d): def revert_dict(d):
''' """
In d, word is the key, and value is a list of dates. In d, word is the key, and value is a list of dates.
In d2 (the returned value of this function), time is the key, and the value is a list of words picked at that time. In d2 (the returned value of this function), time is the key, and the value is a list of words picked at that time.
''' """
d2 = {} d2 = {}
for k in d: for k in d:
if type(d[k]) is list: # d[k] is a list of dates. if type(d[k]) is list: # d[k] is a list of dates.
@ -80,7 +80,7 @@ def revert_dict(d):
for time_info in lst: for time_info in lst:
date = time_info[:10] # until hour date = time_info[:10] # until hour
if not date in d2: if date not in d2:
d2[date] = [k] d2[date] = [k]
else: else:
d2[date].append(k) d2[date].append(k)
@ -105,7 +105,7 @@ def user_difficulty_level(d_user, d):
word = t[0] word = t[0]
hard = t[1] hard = t[1]
# print('WORD %s HARD %4.2f' % (word, hard)) # print('WORD %s HARD %4.2f' % (word, hard))
geometric = geometric * (hard) geometric = geometric * hard
count += 1 count += 1
if count >= 10: if count >= 10:
return geometric ** (1 / count) return geometric ** (1 / count)
@ -131,7 +131,7 @@ def text_difficulty_level(s, d):
for t in lst2: for t in lst2:
word = t[0] word = t[0]
hard = t[1] hard = t[1]
geometric = geometric * (hard) geometric = geometric * hard
count += 1 count += 1
if count >= 20: # we look for n most difficult words if count >= 20: # we look for n most difficult words
return geometric ** (1 / count) return geometric ** (1 / count)

View File

@ -23,33 +23,34 @@ app.register_blueprint(adminService)
path_prefix = '/var/www/wordfreq/wordfreq/' path_prefix = '/var/www/wordfreq/wordfreq/'
path_prefix = './' # comment this line in deployment path_prefix = './' # comment this line in deployment
def get_random_image(path): def get_random_image(path):
''' """
返回随机图 返回随机图
:param path: 图片文件(JPEG格式)不包含后缀名 :param path: 图片文件(JPEG格式)不包含后缀名
:return: :return:
''' """
img_path = random.choice(glob.glob(os.path.join(path, '*.jpg'))) img_path = random.choice(glob.glob(os.path.join(path, '*.jpg')))
return img_path[img_path.rfind('/static'):] return img_path[img_path.rfind('/static'):]
def get_random_ads(): def get_random_ads():
''' """
返回随机广告 返回随机广告
:return: 一个广告(包含HTML标签) :return: 一个广告(包含HTML标签)
''' """
return random.choice(['个性化分析精准提升', '你的专有单词本', '智能捕捉阅读弱点,针对性提高你的阅读水平']) return random.choice(['个性化分析精准提升', '你的专有单词本', '智能捕捉阅读弱点,针对性提高你的阅读水平'])
def appears_in_test(word, d): def appears_in_test(word, d):
''' """
如果字符串里没有指定的单词则返回逗号加单词 如果字符串里没有指定的单词则返回逗号加单词
:param word: 指定单词 :param word: 指定单词
:param d: 字符串 :param d: 字符串
:return: 逗号加单词 :return: 逗号加单词
''' """
if not word in d: if word not in d:
return '' return ''
else: else:
return ','.join(d[word]) return ','.join(d[word])
@ -57,10 +58,10 @@ def appears_in_test(word, d):
@app.route("/mark", methods=['GET', 'POST']) @app.route("/mark", methods=['GET', 'POST'])
def mark_word(): def mark_word():
''' """
标记单词 标记单词
:return: 重定位到主界面 :return: 重定位到主界面
''' """
if request.method == 'POST': if request.method == 'POST':
d = load_freq_history(path_prefix + 'static/frequency/frequency.p') d = load_freq_history(path_prefix + 'static/frequency/frequency.p')
lst_history = pickle_idea.dict_to_lst(d) lst_history = pickle_idea.dict_to_lst(d)
@ -76,10 +77,10 @@ def mark_word():
@app.route("/", methods=['GET', 'POST']) @app.route("/", methods=['GET', 'POST'])
def mainpage(): def mainpage():
''' """
根据GET或POST方法来返回不同的主界面 根据GET或POST方法来返回不同的主界面
:return: 主界面 :return: 主界面
''' """
if request.method == 'POST': # when we submit a form if request.method == 'POST': # when we submit a form
content = escape(request.form['content']) content = escape(request.form['content'])
f = WordFreq(content) f = WordFreq(content)

View File

@ -11,15 +11,15 @@ from datetime import datetime
def lst_to_dict(lst, d): def lst_to_dict(lst, d):
''' """
Store the information in list lst to dictionary d. Store the information in list lst to dictionary d.
Note: nothing is returned. Note: nothing is returned.
''' """
for x in lst: for x in lst:
word = x[0] word = x[0]
freq = x[1] freq = x[1]
if not word in d: if word not in d:
d[word] = freq d[word] = freq
else: else:
d[word] += freq d[word] += freq
@ -73,6 +73,7 @@ def familiar(path, word):
fp = open(path, "wb") fp = open(path, "wb")
pickle.dump(dic, fp) pickle.dump(dic, fp)
if __name__ == '__main__': if __name__ == '__main__':
lst1 = [('apple', 2), ('banana', 1)] lst1 = [('apple', 2), ('banana', 1)]
@ -80,7 +81,6 @@ if __name__ == '__main__':
lst_to_dict(lst1, d) # d will change lst_to_dict(lst1, d) # d will change
save_frequency_to_pickle(d, 'frequency.p') # frequency.p is our database save_frequency_to_pickle(d, 'frequency.p') # frequency.p is our database
lst2 = [('banana', 2), ('orange', 4)] lst2 = [('banana', 2), ('orange', 4)]
d = load_record('frequency.p') d = load_record('frequency.p')
lst1 = dict_to_lst(d) lst1 = dict_to_lst(d)

View File

@ -12,22 +12,22 @@ import pickle
from datetime import datetime from datetime import datetime
def lst2dict(lst, d): def lst_to_dict(lst, d):
''' """
Store the information in list lst to dictionary d. Store the information in list lst to dictionary d.
Note: nothing is returned. Note: nothing is returned.
''' """
for x in lst: for x in lst:
word = x[0] word = x[0]
dates = x[1] dates = x[1]
if not word in d: if word not in d:
d[word] = dates d[word] = dates
else: else:
d[word] += dates d[word] += dates
def deleteRecord(path, word): def delete_record(path, word):
with open(path, 'rb') as f: with open(path, 'rb') as f:
db = pickle.load(f) db = pickle.load(f)
try: try:
@ -37,7 +37,8 @@ def deleteRecord(path, word):
with open(path, 'wb') as ff: with open(path, 'wb') as ff:
pickle.dump(db, ff) pickle.dump(db, ff)
def dict2lst(d):
def dict_to_lst(d):
if len(d) > 0: if len(d) > 0:
keys = list(d.keys()) keys = list(d.keys())
if isinstance(d[keys[0]], int): if isinstance(d[keys[0]], int):
@ -50,10 +51,11 @@ def dict2lst(d):
return [] return []
def merge_frequency(lst1, lst2): def merge_frequency(lst1, lst2):
d = {} d = {}
lst2dict(lst1, d) lst_to_dict(lst1, d)
lst2dict(lst2, d) lst_to_dict(lst2, d)
return d return d
@ -69,23 +71,22 @@ def save_frequency_to_pickle(d, pickle_fname):
exclusion_lst = ['one', 'no', 'has', 'had', 'do', 'that', 'have', 'by', 'not', 'but', 'we', 'this', 'my', 'him', 'so', 'or', 'as', 'are', 'it', 'from', 'with', 'be', 'can', 'for', 'an', 'if', 'who', 'whom', 'whose', 'which', 'the', 'to', 'a', 'of', 'and', 'you', 'i', 'he', 'she', 'they', 'me', 'was', 'were', 'is', 'in', 'at', 'on', 'their', 'his', 'her', 's', 'said', 'all', 'did', 'been', 'w'] exclusion_lst = ['one', 'no', 'has', 'had', 'do', 'that', 'have', 'by', 'not', 'but', 'we', 'this', 'my', 'him', 'so', 'or', 'as', 'are', 'it', 'from', 'with', 'be', 'can', 'for', 'an', 'if', 'who', 'whom', 'whose', 'which', 'the', 'to', 'a', 'of', 'and', 'you', 'i', 'he', 'she', 'they', 'me', 'was', 'were', 'is', 'in', 'at', 'on', 'their', 'his', 'her', 's', 'said', 'all', 'did', 'been', 'w']
d2 = {} d2 = {}
for k in d: for k in d:
if not k in exclusion_lst and not k.isnumeric() and not len(k) < 2: if k not in exclusion_lst and not k.isnumeric() and not len(k) < 2:
d2[k] = list(sorted(d[k])) # 原先这里是d2[k] = list(sorted(set(d[k]))) d2[k] = list(sorted(d[k])) # 原先这里是d2[k] = list(sorted(set(d[k])))
pickle.dump(d2, f) pickle.dump(d2, f)
f.close() f.close()
if __name__ == '__main__': if __name__ == '__main__':
lst1 = [('apple',['201910251437', '201910251438']), ('banana', ['201910251439'])] lst1 = [('apple',['201910251437', '201910251438']), ('banana', ['201910251439'])]
d = {} d = {}
lst2dict(lst1, d) # d will change lst_to_dict(lst1, d) # d will change
save_frequency_to_pickle(d, 'frequency.p') # frequency.p is our database save_frequency_to_pickle(d, 'frequency.p') # frequency.p is our database
lst2 = [('banana',['201910251439']), ('orange', ['201910251440', '201910251439'])] lst2 = [('banana',['201910251439']), ('orange', ['201910251440', '201910251439'])]
d = load_record('frequency.p') d = load_record('frequency.p')
lst1 = dict2lst(d) lst1 = dict_to_lst(d)
d = merge_frequency(lst2, lst1) d = merge_frequency(lst2, lst1)
print(d) print(d)

View File

@ -21,6 +21,7 @@ userService = Blueprint("user_bp", __name__)
path_prefix = '/var/www/wordfreq/wordfreq/' path_prefix = '/var/www/wordfreq/wordfreq/'
path_prefix = './' # comment this line in deployment path_prefix = './' # comment this line in deployment
@userService.route("/get_next_article/<username>",methods=['GET','POST']) @userService.route("/get_next_article/<username>",methods=['GET','POST'])
def get_next_article(username): def get_next_article(username):
user_freq_record = path_prefix + 'static/frequency/' + 'frequency_%s.pickle' % (username) user_freq_record = path_prefix + 'static/frequency/' + 'frequency_%s.pickle' % (username)
@ -42,12 +43,13 @@ def get_next_article(username):
return 'Under construction' return 'Under construction'
return json.dumps(data) return json.dumps(data)
@userService.route("/get_pre_article/<username>",methods=['GET']) @userService.route("/get_pre_article/<username>",methods=['GET'])
def get_pre_article(username): def get_pre_article(username):
user_freq_record = path_prefix + 'static/frequency/' + 'frequency_%s.pickle' % (username) user_freq_record = path_prefix + 'static/frequency/' + 'frequency_%s.pickle' % (username)
if request.method == 'GET': if request.method == 'GET':
visited_articles = session.get("visited_articles") visited_articles = session.get("visited_articles")
if(visited_articles["index"]==0): if visited_articles["index"] == 0:
data = '' data = ''
else: else:
visited_articles["index"] -= 1 # 上一篇index-=1 visited_articles["index"] -= 1 # 上一篇index-=1
@ -62,15 +64,16 @@ def get_pre_article(username):
} }
return json.dumps(data) return json.dumps(data)
@userService.route("/<username>/<word>/unfamiliar", methods=['GET', 'POST']) @userService.route("/<username>/<word>/unfamiliar", methods=['GET', 'POST'])
def unfamiliar(username, word): def unfamiliar(username, word):
''' """
:param username: :param username:
:param word: :param word:
:return: :return:
''' """
user_freq_record = path_prefix + 'static/frequency/' + 'frequency_%s.pickle' % (username) user_freq_record = path_prefix + 'static/frequency/' + 'frequency_%s.pickle' % username
pickle_idea.unfamiliar(user_freq_record, word) pickle_idea.unfamiliar(user_freq_record, word)
session['thisWord'] = word # 1. put a word into session session['thisWord'] = word # 1. put a word into session
session['time'] = 1 session['time'] = 1
@ -79,13 +82,13 @@ def unfamiliar(username, word):
@userService.route("/<username>/<word>/familiar", methods=['GET', 'POST']) @userService.route("/<username>/<word>/familiar", methods=['GET', 'POST'])
def familiar(username, word): def familiar(username, word):
''' """
:param username: :param username:
:param word: :param word:
:return: :return:
''' """
user_freq_record = path_prefix + 'static/frequency/' + 'frequency_%s.pickle' % (username) user_freq_record = path_prefix + 'static/frequency/' + 'frequency_%s.pickle' % username
pickle_idea.familiar(user_freq_record, word) pickle_idea.familiar(user_freq_record, word)
session['thisWord'] = word # 1. put a word into session session['thisWord'] = word # 1. put a word into session
session['time'] = 1 session['time'] = 1
@ -94,14 +97,14 @@ def familiar(username, word):
@userService.route("/<username>/<word>/del", methods=['GET', 'POST']) @userService.route("/<username>/<word>/del", methods=['GET', 'POST'])
def delete_word(username, word): def delete_word(username, word):
''' """
删除单词 删除单词
:param username: 用户名 :param username: 用户名
:param word: 单词 :param word: 单词
:return: 重定位到用户界面 :return: 重定位到用户界面
''' """
user_freq_record = path_prefix + 'static/frequency/' + 'frequency_%s.pickle' % (username) user_freq_record = path_prefix + 'static/frequency/' + 'frequency_%s.pickle' % (username)
pickle_idea2.deleteRecord(user_freq_record, word) pickle_idea2.delete_record(user_freq_record, word)
# 模板userpage_get.html中删除单词是异步执行而flash的信息后续是同步执行的所以注释这段代码同时如果这里使用flash但不提取信息则会影响 signup.html的显示。bug复现删除单词后点击退出点击注册注册页面就会出现提示信息 # 模板userpage_get.html中删除单词是异步执行而flash的信息后续是同步执行的所以注释这段代码同时如果这里使用flash但不提取信息则会影响 signup.html的显示。bug复现删除单词后点击退出点击注册注册页面就会出现提示信息
# flash(f'{word} is no longer in your word list.') # flash(f'{word} is no longer in your word list.')
return "success" return "success"
@ -109,11 +112,11 @@ def delete_word(username, word):
@userService.route("/<username>/userpage", methods=['GET', 'POST']) @userService.route("/<username>/userpage", methods=['GET', 'POST'])
def userpage(username): def userpage(username):
''' """
用户界面 用户界面
:param username: 用户名 :param username: 用户名
:return: 返回用户界面 :return: 返回用户界面
''' """
# 未登录,跳转到未登录界面 # 未登录,跳转到未登录界面
if not session.get('logged_in'): if not session.get('logged_in'):
return render_template('not_login.html') return render_template('not_login.html')
@ -136,7 +139,7 @@ def userpage(username):
elif request.method == 'GET': # when we load a html page elif request.method == 'GET': # when we load a html page
d = load_freq_history(user_freq_record) d = load_freq_history(user_freq_record)
lst = pickle_idea2.dict2lst(d) lst = pickle_idea2.dict_to_lst(d)
lst2 = [] lst2 = []
for t in lst: for t in lst:
lst2.append((t[0], len(t[1]))) lst2.append((t[0], len(t[1])))
@ -159,19 +162,20 @@ def userpage(username):
yml=Yaml.yml, yml=Yaml.yml,
words=words) words=words)
@userService.route("/<username>/mark", methods=['GET', 'POST']) @userService.route("/<username>/mark", methods=['GET', 'POST'])
def user_mark_word(username): def user_mark_word(username):
''' """
标记单词 标记单词
:param username: 用户名 :param username: 用户名
:return: 重定位到用户界面 :return: 重定位到用户界面
''' """
username = session[username] username = session[username]
user_freq_record = path_prefix + 'static/frequency/' + 'frequency_%s.pickle' % (username) user_freq_record = path_prefix + 'static/frequency/' + 'frequency_%s.pickle' % username
if request.method == 'POST': if request.method == 'POST':
# 提交标记的单词 # 提交标记的单词
d = load_freq_history(user_freq_record) d = load_freq_history(user_freq_record)
lst_history = pickle_idea2.dict2lst(d) lst_history = pickle_idea2.dict_to_lst(d)
lst = [] lst = []
for word in request.form.getlist('marked'): for word in request.form.getlist('marked'):
lst.append((word, [get_time()])) lst.append((word, [get_time()]))
@ -183,9 +187,9 @@ def user_mark_word(username):
def get_time(): def get_time():
''' """
获取当前时间 获取当前时间
:return: 当前时间 :return: 当前时间
''' """
return datetime.now().strftime('%Y%m%d%H%M') # upper to minutes return datetime.now().strftime('%Y%m%d%H%M') # upper to minutes

View File

@ -11,12 +11,12 @@ import pickle_idea
def freq(s): def freq(s):
''' """
功能 把字符串转成列表 目的是得到每个单词的频率 功能 把字符串转成列表 目的是得到每个单词的频率
输入 字符串 输入 字符串
输出 列表 列表里包含一组元组每个元组包含单词与单词的频率 比如 [('apple', 2), ('banana', 1)] 输出 列表 列表里包含一组元组每个元组包含单词与单词的频率 比如 [('apple', 2), ('banana', 1)]
注意事项 首先要把字符串转成小写原因是 注意事项 首先要把字符串转成小写原因是
''' """
result = [] result = []
s = s.lower() # 字母转小写 s = s.lower() # 字母转小写
@ -71,9 +71,9 @@ def sort_in_ascending_order(lst): # 单词按频率降序排列
def make_html_page(lst, fname): # 只是在wordfreqCMD.py中的main函数中调用所以不做修改 def make_html_page(lst, fname): # 只是在wordfreqCMD.py中的main函数中调用所以不做修改
''' """
功能把lst的信息存到fname中以html格式 功能把lst的信息存到fname中以html格式
''' """
s = '' s = ''
count = 1 count = 1
for x in lst: for x in lst: