Flask 实现用户注册/登录表单

Flask是一个使用 Python 编写的轻量级 Web 应用框架。其 WSGI 工具箱采用 Werkzeug ,模板引擎则使用 Jinja2

Flask 框架实现的一个用户注册与登录页面,经过美化的页面,可以直接应用到项目中。

实现用户注册

1.在flask目录的static下新建sytle.css文件。

body {
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: -webkit-center;
    line-height: 0.5;
    background: aliceblue;
}
.form-bg{
    background: #00b4ef;
}
.form-horizontal{
    background: #fff;
    padding-bottom: 10px;
    border-radius: 15px;
    text-align: center;
}
.form-horizontal .heading{
    display: block;
    font-size: 35px;
    font-weight: 700;
    padding: 35px 0;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 30px;
}
.form-horizontal .form-group{
    padding: 0 40px;
    margin: 0 0 25px 0;
    position: relative;
}
.form-horizontal .form-control{
    background: #f0f0f0;
    border: none;
    border-radius: 20px;
    box-shadow: none;
    padding: 0 20px 0 45px;
    height: 40px;
    transition: all 0.3s ease 0s;
}
.form-horizontal .form-control:focus{
    background: #e0e0e0;
    box-shadow: none;
    outline: 0 none;
}
.form-horizontal .form-group i{
    position: absolute;
    top: 12px;
    left: 60px;
    font-size: 17px;
    color: #c8c8c8;
    transition : all 0.5s ease 0s;
}
.form-horizontal .form-control:focus + i{
    color: #00b4ef;
}
.form-horizontal .fa-question-circle{
    display: inline-block;
    position: absolute;
    top: 12px;
    right: 60px;
    font-size: 20px;
    color: #808080;
    transition: all 0.5s ease 0s;
}
.form-horizontal .fa-question-circle:hover{
    color: #000;
}
.form-horizontal .text{
    float: left;
    margin-left: 7px;
    line-height: 20px;
    padding-top: 5px;
    text-transform: capitalize;
}
.form-horizontal .btn{
    font-size: 14px;
    color: #fff;
    border-radius: 100px;
    padding: 10px 70px;
    border: none;
    text-transform: capitalize;
    transition: all 0.5s ease 0s;
}
@media only screen and (max- 479px){
    .form-horizontal .form-group{
        padding: 0 25px;
    }
    .form-horizontal .form-group i{
        left: 45px;
    }
    .form-horizontal .btn{
        padding: 10px 20px;
    }
}

2.在templates目录下新建一个 register.html

<html>
<head>
    <link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
    <link href="http://cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
    <link href="/static/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-offset-3 col-md-6">
                <form action="/register" method="post" class="form-horizontal">
                    <span class="heading">用 户 注 册</span>
                    <div class="form-group">
                        {{ form.username }}
                        <i class="fa fa-user"></i>
                        <a href="/login" class="fa fa-question-circle"></a>
                    </div>
                    <div class="form-group">
                        {{ form.email }}
                        <i class="fa fa-envelope"></i>
                    </div>
                    <div class="form-group">
                        {{ form.password }}
                        <i class="fa fa-lock"></i>
                    </div>
                    <div class="form-group">
                        {{ form.RepeatPassword }}
                        <i class="fa fa-unlock-alt"></i>
                    </div>
                    {{ form.submit }}
                </form>
            </div>
        </div>
    </div>
</body>
</html>

3.在app.py里面写入。

from flask import Flask, render_template, request, redirect
from wtforms import Form,validators,widgets
from wtforms.fields import simple,html5

app = Flask(__name__, template_folder="templates")
class RegisterForm(Form):
    username = simple.StringField(
        #label='注册用户:',
        validators=[
            validators.DataRequired(message='用户名不能为空'),
            validators.Length(min=6, max=18, message='用户名长度必须大于%(min)d且小于%(max)d')
        ],
        widget=widgets.TextInput(),
        render_kw={'class': 'form-control',
                   "placeholder":"输入注册用户名"}
    )
    email = simple.StringField(
        #label='用户邮箱:',
        validators=[validators.DataRequired(message='邮箱不能为空'),validators.Email(message="邮箱格式输入有误")],
        render_kw={'class':'form-control',
                   "placeholder":"输入Email邮箱"}
    )
    password = simple.PasswordField(
        #label='用户密码:',
        validators=[
            validators.DataRequired(message='密码不能为空'),
            validators.Length(min=5, message='用户名长度必须大于%(min)d'),
            validators.Regexp(regex="[0-9a-zA-Z]{5,}",message='密码不允许使用特殊字符')
        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control',
                   "placeholder":"输入用户密码"}
    )
    RepeatPassword = simple.PasswordField(
        #label='重复密码:',
        validators=[
            validators.DataRequired(message='密码不能为空'),
            validators.Length(min=5, message='密码长度必须大于%(min)d'),
            validators.Regexp(regex="[0-9a-zA-Z]{5,}",message='密码不允许使用特殊字符'),
            validators.EqualTo("password",message="两次密码输入必须一致,龟孙")
        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control',
                   "placeholder":"再次输入密码"}
    )
    submit = simple.SubmitField(
        label="用 户 注 册",
        render_kw={ "class":"btn btn-success" }
    )

@app.route('/register', methods=['GET', 'POST'])
def Register():
    if request.method == 'GET':
        RetForm = RegisterForm()
        return render_template('register.html', form=RetForm)
    else:
        RetForm = RegisterForm(formdata=request.form)
        if RetForm.validate():
            print('接收到数据:', RetForm.data)
            return '''<script>alert('您的注册请求已提交!');</script>'''
        else:
            print(RetForm.errors)
        return render_template('register.html', form=RetForm)

if __name__ == '__main__':
    app.run()

效果如下。

实现用户登录

login.html

<html>
<head>
    <link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
    <link href="http://cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
    <link href="/static/style.css" rel="stylesheet" type="text/css" />
</head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-offset-3 col-md-6">
                    <form action="/login" method="post" class="form-horizontal">
                        <span class="heading">用 户 登 录</span>
                        <div class="form-group">
                            {{ form.username }}
                            <i class="fa fa-user"></i>
                        </div>
                        <div class="form-group help">
                            {{ form.password }}
                            <i class="fa fa-lock"></i>
                            <a href="#" class="fa fa-question-circle"></a>
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-success">登 录 后 台</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </body>
</html>

app.py

from flask import Flask, render_template, request, redirect
from wtforms import Form,validators,widgets
from wtforms.fields import simple,html5

app = Flask(__name__, template_folder="templates")

class LoginForm(Form):
    username = simple.StringField(
        validators=[
            validators.DataRequired(message=''),
            validators.Length(min=4, max=15, message=''),
            validators.Regexp(regex="[0-9a-zA-Z]{4,15}", message='')
        ],
        widget=widgets.TextInput(),
        render_kw={"class":"form-control",
                   "placeholder":"请输入用户名或电子邮件"}
    )
    password = simple.PasswordField(
        validators=[
            validators.DataRequired(message=''),
            validators.Length(min=5, max=15,message=''),
            validators.Regexp(regex="[0-9a-zA-Z]{5,15}",message='')
        ],
        widget=widgets.PasswordInput(),
        render_kw={"class":"form-control",
                   "placeholder":"请输入密码"}
    )

@app.route("/login",methods=['GET','POST'])
def Login():
    if request.method == 'GET':
        RetForm = LoginForm()
        return render_template('login.html', form=RetForm)
    else:
        RetForm = LoginForm(formdata=request.form)
        if RetForm.validate():
            temp = RetForm.data
            print("接收到数据:",temp)
            return '''<script type="text/javascript">alert('登录完成!');</script>'''
        return render_template('login.html', form=RetForm)

if __name__ == '__main__':
    app.run()

其他wtforms常用标签

submit.html

<!--name:index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <title>页面选择</title>
</head>
<body>
<form method="post">
    <p>{{ form.gender.label }} {{form.gender}} {{form.gender.errors[0] }}</p>
    <p>{{ form.city.label }} {{form.city}} {{form.city.errors[0] }} </p>
    <p>{{ form.hobby.label }} {{form.hobby}} {{form.hobby.errors[0] }}</p>
    <p>{{ form.favor.label }} {{form.favor}} {{form.favor.errors[0] }}</p>
    <input type="submit" value="提交表格">
</form>
</body>
</html>

app.py

# name:app.py
from flask import Flask, render_template, request, redirect
from wtforms import Form,validators,widgets
from wtforms.fields import simple,html5,core

app = Flask(__name__,template_folder="templates")

class RegisterForm(Form):
    gender = core.RadioField(
        label="性别:",choices=((0,"男"),(1,"女"),(0,"两面派")),coerce=int  #限制是int类型的
    )
    city = core.SelectField(
        label="选择城市:",
        choices=(
            ("shandong","山东省"),("shanghai","上海市"),
            ("beijingshi","北京市"),("neimenggu","内蒙古")
        ),
        render_kw={'class': 'btn btn-primary dropdown-toggle'}
    )
    hobby = core.SelectMultipleField(
        label='爱好:',
        choices=((1, '唱'),(2, '跳'),(3,'rap'),(4,'篮球')),
        coerce=int,
        render_kw = {'class': 'form-control'}
    )
    favor = core.SelectMultipleField(
        label="特长:",
        choices=((1, 'Python把妹'),(2, '渗透把妹'),(3,"运维把妹"),(4,"科学把妹")),
        widget = widgets.ListWidget(prefix_label=False),
        option_widget = widgets.CheckboxInput(),
        coerce = int, default = [1, 2 , 4],
    )

@app.route('/submit',methods=["GET","POST"])
def submit():
    if request.method=="GET":
        form = RegisterForm(data={'gender': 1}) # 指定性别的默认值是1
        return render_template("submit.html",form=form)
    else:
        form = RegisterForm(formdata=request.form)
        if form.validate():
            print('提交的值为:', form.data)
            return '''<script type="text/javascript">alert('您的请求已提交!');</script>'''
        else:
            print("提交数据错误..")
        return render_template('submit.html', form=form)

if __name__ == '__main__':
    app.run()


版权声明: 本博客,文章与代码均为学习时整理的笔记,博客中除去明确标注有参考文献的文章,其他文章【均为原创】作品,转载请务必【添加出处】,您添加出处是我创作的动力!

警告:如果您恶意转载本人文章,则您的整站文章,将会变为我的原创作品,请相互尊重!
原文地址:https://www.cnblogs.com/LyShark/p/12106632.html