From 18dfad910bc26f6704e0ae9866f6274dbdf68d10 Mon Sep 17 00:00:00 2001 From: Lan Hui <1348141770@qq.com> Date: Thu, 27 Jan 2022 17:01:03 +0800 Subject: [PATCH] Use named style for sqlite3 execute() --- app/Article.py | 5 ++--- app/Login.py | 26 +++++++++++++++----------- app/UseSqlite.py | 26 +++++++++++++------------- app/account_service.py | 18 +++++++++--------- app/templates/mainpage_get.html | 2 +- app/templates/reset.html | 4 ++-- 6 files changed, 42 insertions(+), 39 deletions(-) diff --git a/app/Article.py b/app/Article.py index 7f41b1e..774d25a 100644 --- a/app/Article.py +++ b/app/Article.py @@ -49,8 +49,7 @@ def get_today_article(user_word_list, articleID): d = {} d_user = load_freq_history(user_word_list) - user_level = user_difficulty_level(d_user, - d3) # more consideration as user's behaviour is dynamic. Time factor should be considered. + user_level = user_difficulty_level(d_user, d3) # more consideration as user's behaviour is dynamic. Time factor should be considered. random.shuffle(result) # shuffle list d = random.choice(result) text_level = text_difficulty_level(d['text'], d3) @@ -128,7 +127,7 @@ def get_answer_part(s): else e.style.display = 'block'; } - + ''' html_code = js html_code += '\n' diff --git a/app/Login.py b/app/Login.py index c06a1b2..65047f7 100644 --- a/app/Login.py +++ b/app/Login.py @@ -1,6 +1,5 @@ import hashlib from datetime import datetime - from UseSqlite import InsertQuery, RecordQuery path_prefix = '/var/www/wordfreq/wordfreq/' @@ -10,7 +9,8 @@ path_prefix = './' # comment this line in deployment def verify_user(username, password): rq = RecordQuery(path_prefix + 'static/wordfreqapp.db') password = md5(username + password) - rq.instructions_with_parameters("SELECT * FROM user WHERE name=? AND password=?", (username, password)) + rq.instructions_with_parameters("SELECT * FROM user WHERE name=:username AND password=:password", dict( + username=username, password=password)) # the named style https://docs.python.org/3/library/sqlite3.html rq.do_with_parameters() result = rq.get_results() return result != [] @@ -22,14 +22,16 @@ def add_user(username, password): # 将用户名和密码一起加密,以免暴露不同用户的相同密码 password = md5(username + password) rq = InsertQuery(path_prefix + 'static/wordfreqapp.db') - rq.instructions("INSERT INTO user VALUES ('%s', '%s', '%s', '%s')" % (username, password, start_date, expiry_date)) - rq.do() + rq.instructions_with_parameters("INSERT INTO user VALUES (:username, :password, :start_date, :expiry_date)", dict( + username=username, password=password, start_date=start_date, expiry_date=expiry_date)) + rq.do_with_parameters() def check_username_availability(username): rq = RecordQuery(path_prefix + 'static/wordfreqapp.db') - rq.instructions("SELECT * FROM user WHERE name='%s'" % (username)) - rq.do() + rq.instructions_with_parameters( + "SELECT * FROM user WHERE name=:username", dict(username=username)) + rq.do_with_parameters() result = rq.get_results() return result == [] @@ -47,15 +49,17 @@ def change_password(username, old_password, new_password): # 将用户名和密码一起加密,以免暴露不同用户的相同密码 password = md5(username + new_password) rq = InsertQuery(path_prefix + 'static/wordfreqapp.db') - rq.instructions("UPDATE user SET password = '%s' WHERE name = '%s'" % (password, username)) - rq.do() + rq.instructions_with_parameters("UPDATE user SET password=:password WHERE name=:username", dict( + password=password, username=username)) + rq.do_with_parameters() return True def get_expiry_date(username): rq = RecordQuery(path_prefix + 'static/wordfreqapp.db') - rq.instructions("SELECT expiry_date FROM user WHERE name='%s'" % (username)) - rq.do() + rq.instructions_with_parameters( + "SELECT expiry_date FROM user WHERE name=:username", dict(username=username)) + rq.do_with_parameters() result = rq.get_results() if len(result) > 0: return result[0]['expiry_date'] @@ -70,4 +74,4 @@ def md5(s): :return: 经MD5以后的字符串 ''' h = hashlib.md5(s.encode(encoding='utf-8')) - return h.hexdigest() \ No newline at end of file + return h.hexdigest() diff --git a/app/UseSqlite.py b/app/UseSqlite.py index 660710f..ea4baeb 100644 --- a/app/UseSqlite.py +++ b/app/UseSqlite.py @@ -12,26 +12,26 @@ import sqlite3 class Sqlite3Template: def __init__(self, db_fname): self.db_fname = db_fname - + def connect(self, db_fname): self.conn = sqlite3.connect(self.db_fname) - + def instructions(self, query_statement): raise NotImplementedError() - + def operate(self): self.conn.row_factory = sqlite3.Row self.results = self.conn.execute(self.query) # self.query is to be given in the child classes self.conn.commit() - + def format_results(self): - raise NotImplementedError() - + raise NotImplementedError() + def do(self): self.connect(self.db_fname) self.instructions(self.query) self.operate() - + def instructions_with_parameters(self, query_statement, parameters): self.query = query_statement self.parameters = parameters @@ -46,11 +46,11 @@ class Sqlite3Template: self.results = self.conn.execute(self.query, self.parameters) # self.query is to be given in the child classes self.conn.commit() - + class InsertQuery(Sqlite3Template): def instructions(self, query): self.query = query - + class RecordQuery(Sqlite3Template): def instructions(self, query): @@ -64,23 +64,23 @@ class RecordQuery(Sqlite3Template): lst.append( row_dict[k] ) output.append(', '.join(lst)) return '\n\n'.join(output) - + def get_results(self): result = [] for row_dict in self.results.fetchall(): result.append( dict(row_dict) ) return result - + if __name__ == '__main__': - + #iq = InsertQuery('RiskDB.db') #iq.instructions("INSERT INTO inspection Values ('FoodSupplies', 'RI2019051301', '2019-05-13', '{}')") #iq.do() #iq.instructions("INSERT INTO inspection Values ('CarSupplies', 'RI2019051302', '2019-05-13', '{[{\"risk_name\":\"elevator\"}]}')") #iq.do() - + rq = RecordQuery('wordfreqapp.db') rq.instructions("SELECT * FROM article WHERE level=3") rq.do() diff --git a/app/account_service.py b/app/account_service.py index 3f5cf60..753c51e 100644 --- a/app/account_service.py +++ b/app/account_service.py @@ -17,8 +17,8 @@ def signup(): return render_template('signup.html') elif request.method == 'POST': # POST方法需判断是否注册成功,再根据结果返回不同的内容 - username = request.form['username'] - password = request.form['password'] + username = escape(request.form['username']) + password = escape(request.form['password']) available = check_username_availability(username) if not available: # 用户名不可用 @@ -60,8 +60,8 @@ def login(): elif request.method == 'POST': # POST方法用于判断登录是否成功 # check database and verify user - username = request.form['username'] - password = request.form['password'] + username = escape(request.form['username']) + password = escape(request.form['password']) verified = verify_user(username, password) if verified: # 登录成功,写入session @@ -104,15 +104,15 @@ def reset(): return render_template('reset.html', username=session['username'], state='wait') else: # POST请求用于提交修改后信息 - old_psd = request.form['old-psd'] - new_psd = request.form['new-psd'] - flag = change_password(username, old_psd, new_psd) # flag表示是否修改成功 + old_password = escape(request.form['old-password']) + new_password = escape(request.form['new-password']) + flag = change_password(username, old_password, new_password) # flag表示是否修改成功 if flag: session['logged_in'] = False return \ ''' @@ -122,7 +122,7 @@ window.location.href="/login"; return \ ''' diff --git a/app/templates/mainpage_get.html b/app/templates/mainpage_get.html index 6e1d9b4..4e69243 100644 --- a/app/templates/mainpage_get.html +++ b/app/templates/mainpage_get.html @@ -25,7 +25,7 @@ {% if session['logged_in'] %} {{session['username']}}
{% else %} - +{{random_ads|safe}}
{% endif %}