0
0
Fork 0

Use named style for sqlite3 execute()

Hui-SaferSQL
Lan Hui 2022-01-27 17:01:03 +08:00
parent 922e1ee652
commit 18dfad910b
6 changed files with 42 additions and 39 deletions

View File

@ -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';
}
</script>
</script>
'''
html_code = js
html_code += '\n'

View File

@ -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()
return h.hexdigest()

View File

@ -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()

View File

@ -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 \
'''
<script>
alert('修改密码成功!!!请重新登录');
alert('密码修改成功,请重新登录。');
window.location.href="/login";
</script>
@ -122,7 +122,7 @@ window.location.href="/login";
return \
'''
<script>
alert('修改密码失败!!!');
alert('密码修改失败');
window.location.href="/reset";
</script>

View File

@ -25,7 +25,7 @@
{% if session['logged_in'] %}
<a href="/{{session['username']}}">{{session['username']}}</a></p>
{% else %}
<p><a href="/login">登录</a> <a href="/signup">成为会员</a> <a href="/static/usr/instructions.html">使用说明</a></p >
<p><a href="/login">登录</a> <a href="/signup">注册</a> <a href="/static/usr/instructions.html">使用说明</a></p >
<p><b>{{random_ads|safe}}</b></p>
{% endif %}
<div class="alert alert-success" role="alert">共有文章 <span class="badge bg-success"> {{number_of_essays}} </span></div>

View File

@ -2,10 +2,10 @@
<body>
<form action="/reset" method='POST'>
旧密码:
<input type="password" name="old-psd" />
<input type="password" name="old-password" />
<br/>
新密码:
<input type="password" name="new-psd" />
<input type="password" name="new-password" />
<br/>
<input type="submit" name="submit" value="提交" />
<input type="button" name="submit" value="放弃修改" onclick="window.location.href='/{{ username }}'"/>