Flask 入门(4):添加注册页面

1. 前期准备

创建用户表

1
2
3
4
5
6
create table users 
(id INT(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100), email VARCHAR(100),
username VARCHAR(100),
password VARCHAR(100),
register_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP);

安装 Flask 的依赖包

1
2
3
pip install flask-mysqldb # flask 的 MySQL 依赖包
pip install flask-wtf # 验证框依赖包
pip install passlib # 密码加密

2. 设计注册页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{% extends 'layout.html' %}

{% block body %}
<h1>注册</h1>
{% from 'include/_formhelpers.html' import render_field %}
<form method="POST" action="">
<div class="form-group">
{{ render_field(form.name, class_='form-control') }}
</div>
<div class="form-group">
{{ render_field(form.email, class_='form-control') }}
</div>
<div class="form-group">
{{ render_field(form.username, class_='form-control') }}
</div>
<div class="form-group">
{{ render_field(form.password, class_='form-control') }}
</div>
<div class="form-group">
{{ render_field(form.confirm, class_='form-control') }}
</div>
<p><input type="submit", class="btn btn-primary" value="提交信息"></p>
</form>
{% endblock %}

3. 注册页面视图函数

初始化 MySQL 配置信息

1
2
3
4
5
6
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'myflaskapp'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)

首先,定义登录信息格式的类,如姓名、用户名、密码长度,密码确认以及确认密码,然后,创建视图函数,接入从页面通过 POST 方法传递过来的参数,并写入数据库中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class RegisterForm(Form):
name = StringField('姓名', [validators.Length(min=1,max=50)])
username = StringField('用户名', [validators.Length(min=4,max=25)])
email = StringField('电子邮箱', [validators.Length(min=6,max=50)])
password = PasswordField('登录密码', [validators.DataRequired(), validators.EqualTo('confirm', message='Password not match!')])
confirm = PasswordField('确认登录密码')


@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm(request.form)
if request.method == 'POST' and form.validate():
name = form.name.data
email = form.email.data
username = form.username.data
password = sha256_crypt.encrypt(str(form.password.data))

cur = mysql.connection.cursor()
cur.execute("insert into users(name, email, username, password) values (%s, %s, %s, %s)",
(name, email, username, password))
mysql.connection.commit()
cur.close()
return render_template('register.html', form=form)

完成上述步骤后,刷新页面,填写注册信息,点击“提交信息”,数据成功写入表中。

image

觉得还不错?赞助一下~
0%