使用flask的WTF表單html
1 #! /usr/bin/env python 2 # *-* coding: utf-8 *-* 3 4 from flask import Flask, render_template, request, flash, make_response 5 from flask_wtf import FlaskForm 6 from wtforms.fields import * 7 from wtforms.validators import DataRequired, EqualTo 8 9 app = Flask(__name__) 10 # 開啓session 11 app.secret_key = "aasdfsdf" 12 # app.config["SECRET_KEY"] = "abcd" 13 app.config["WTF_CSRF_ENABLED"] = False 14 15 16 @app.route('/') 17 def hello_world(): 18 return 'Hello World!' 19 20 21 class Login(FlaskForm): 22 username = StringField(label="用戶名", validators=[DataRequired("請輸入用戶名")]) 23 password = PasswordField(label="密碼", validators=[DataRequired("請輸入密碼")]) 24 password2 = PasswordField(label="密碼", validators=[DataRequired("請輸入密碼"), EqualTo('password', "密碼輸入不一致")]) 25 submit = SubmitField(label="提交") 26 27 28 @app.route("/login", methods=["GET", "POST"]) 29 def login(): 30 login_form = Login() 31 if request.method == 'POST': 32 if login_form.validate_on_submit(): 33 username = request.form.get("username") 34 password = request.form.get("password") 35 password2 = request.form.get("password2") 36 print(username, password, password2) 37 # return make_response("success") 38 return "success" 39 else: 40 print("error") 41 flash("參數錯誤請從新輸入") 42 # return render_template("demo004.html", form=login_form) 43 44 # else: 45 # print("get") 46 # return render_template("demo004.html", form=login_form) 47 return render_template("demo004.html", form=login_form) 48 49 50 # 定義根路由視圖函數,生成表單對象,獲取表單數據,進行表單數據驗證 51 @app.route('/demo2', methods=["get", "post"]) 52 def demo2(): 53 register_form = Login() 54 # 驗證表單 55 if register_form.validate_on_submit(): 56 # 若是代碼能走到這個地方,那麼就代碼表單中全部的數據都能驗證成功 57 username = request.form.get("username") 58 password = request.form.get("password") 59 password2 = request.form.get("password2") 60 # 僞裝作註冊操做 61 print(username, password, password2) 62 return "success" 63 else: 64 if request.method == "POST": 65 flash("參數有誤或者不完整") 66 67 return render_template('demo004.html', form=register_form) 68 69 70 if __name__ == '__main__': 71 app.run(debug=True)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <form method="post"> 9 {{ form.username.label }}{{ form.username }}<br/> 10 {{ form.password.label }}{{ form.password }}<br/> 11 {{ form.password2.label }}{{ form.password2 }}<br/> 12 {{ form.submit }} 13 </form> 14 15 {% for message in get_flashed_messages() %} 16 {{ message }} 17 {% endfor %} 18 19 </body> 20 </html>