Flask 入门(5):添加登陆页面

在上一篇文章中,我们完成了注册页面的设计,在这篇笔记中将记录登陆页面的设计过程。登陆页面主要涉及到密码验证、信息提示。

登陆过程的逻辑设计,拿到用户的登陆名和密码,从数据库中查找到对应的信息进行比对,分为三种情形:账号不存在、密码不正确和密码正确。登陆逻辑处理完毕后,再着手对登陆页面login.html的设计。

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
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password_candidate = request.form['password']

cur = mysql.connection.cursor()
result = cur.execute("select * from users where username = %s ", [username])

if result:
data = cur.fetchone()
password = data['password']
if sha256_crypt.verify(password_candidate, password):
app.logger.info('密码正确')
session['logged_in'] = True
session['username'] = username
flash('你已经成功登陆', 'success')

else:
app.logger.info('密码不正确')
error = '登陆失败,密码不正确'
return render_template('login.html', error=error)

else:
app.logger.info('账号不存在')
error = '账号不存在'
return render_template('login.html', error=error)

cur.close()

return render_template('login.html')

设计登陆页面,一般有现成的模板,直接拿过来用即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{% extends 'layout.html' %}

{% block body %}
<h1>登陆</h1>
<form action="" method="POST">
<div class="form-group">
<label>用户名</label>
<input type="text" name="username" class="form-control" value={{ request.form.username }}>
</div>
<div class="form-group">
<label>密码</label>
<input type="password" name="password" class="form-control" value={{ request.form.password }}>
</div>
<button type="submit" class="btn btn-primary">提交信息</button>
</form>
{% endblock %}

然后,我们还要对登陆的结果给予反馈,这里还新建了_messager.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul class=flashes>
{% for category, message in messages %}
<div class="alert alert-{{ category }}">{{ message }}</div>
{% endfor %}
</ul>
{% endif %}
{% endwith %}

{% if error %}
<div class="alert alert-danger">{{ error }}</div>
{% endif %}

{% if msg %}
<div class="alert alert-success">{{ msg }}</div>
{% endif %}
------本文结束,欢迎收藏本站、分享、评论或联系作者!------
点击查看
赠人玫瑰 手有余香
0%