首頁 > 軟體

Flask框架運用WTForms實現使用者註冊的範例詳解

2022-12-23 14:00:31

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使用者註冊內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com