Flask框架運用WTForms實現用戶註冊的示例詳解

WTForms 是用於web開發的靈活的表單驗證和呈現庫,它可以與您選擇的任何web框架和模板引擎一起工作,並支持數據驗證、CSRF保護、國際化等,運用WTForms框架並配合Flask可實現一個帶有基本表單驗證功能的用戶註冊與登錄頁面,經過美化的頁面可以直接應用到項目中。

  • WTForms 需要額外安裝PIP包
  • pip install WTForms email_validator

實現用戶註冊頁面

templates目錄下新建index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel='stylesheet' href="https://cdn.lyshark.com/javascript/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow"  rel="external nofollow" >
    <link href="https://cdn.lyshark.com/javascript/font-awesome/4.7.0/css/font-awesome.min.css" rel="external nofollow"  rel="external nofollow"  rel="stylesheet">
    <link href="https://cdn.lyshark.com/javascript/other/my_login.css" rel="external nofollow"  rel="external nofollow"  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" rel="external nofollow"  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>

Flask 後端部分使用如下代碼:

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

app = Flask(import_name=__name__,
            static_url_path='/python',   # 配置靜態文件的訪問url前綴
            static_folder='static',      # 配置靜態文件的文件夾
            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('index.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('index.html', form=RetForm)

if __name__ == '__main__':
    app.run(host="127.0.0.1", port=80, debug=False)

代碼運行效果如下:

實現用戶登錄頁面

templates目錄下新建index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel='stylesheet' href="https://cdn.lyshark.com/javascript/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow"  rel="external nofollow" >
    <link href="https://cdn.lyshark.com/javascript/font-awesome/4.7.0/css/font-awesome.min.css" rel="external nofollow"  rel="external nofollow"  rel="stylesheet">
    <link href="https://cdn.lyshark.com/javascript/other/my_login.css" rel="external nofollow"  rel="external nofollow"  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="#" rel="external nofollow"  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>

Flask 後端部分使用如下代碼:

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

app = Flask(import_name=__name__,
            static_url_path='/python',   # 配置靜態文件的訪問url前綴
            static_folder='static',      # 配置靜態文件的文件夾
            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('index.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('index.html', form=RetForm)

if __name__ == '__main__':
    app.run(host="127.0.0.1", port=80, debug=False)

代碼運行效果如下:

到此這篇關於Flask框架運用WTForms實現用戶註冊的示例詳解的文章就介紹到這瞭,更多相關Flask WTForms用戶註冊內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: