WTF Forms
wtf.py
from flask_wtf import FlaskForm from wtform import StringField, PasswordField, SubmmitField app.config["SECRET_KEY"] = "12345678" class register(flaskform): username = StringField("用户名:", render_kw={"placeholder":"占位符"}) password = PasswordField("密码:") password2 = PassswordField("确认密码:") submit = SubmitField("提交")
from flask import Flask, render_template from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField app = Flask(__name__) class register(FlaskForm): username = StringField("用户名:", render_kw={'placeholder': "我是占位符"}) password = PasswordField("密码:") password2 = PasswordField("确认密码") submit = SubmitField("注册") @app.route("/",methods=["POST", "GET"]) def index(): registerform = register() return render_template("demo4_template.html", form=registerform) if __name__ == '__main__': app.run()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {# <form method="post">#} {# <label>用户名:</label><input type="text" name="username" placeholder= "Please enter a user name" > < br /> #} {# < label > Password: </ label > < INPUT type = "password" name = "password" placeholder = "Please enter the password" > < br /> # } {# < label > confirm password: </ label > < iNPUT type = "password" name = "password2" placeholder = "Please enter the confirmation password" > < br />#} {# <input type="submit" value="注册">#} {##} {#</form>#} <br/> <br/> <br/> <form method = "post"> {{ form.username.label }}{{ form.username }}<br/> {{ form.password.label }}{{ form.password }}<br/> {{ form.password2.label }}{{ form.password2 }}<br/> {{ form.submit}} </form> </body> </html>
CSRF
- When the client requests the interface data to the rear, the rear end is set to the value of the response csrf_token a cookie
- Add in the Form of a hidden form field value is also csrf_token
- When the user clicks submit, we will bring these two values initiates a request to the background
- Back-end receives a request to the following will be several events:
- Removed from the cookie csrf_token
- Removed from the form data values of hidden csrf_token
- comparing
- If the comparison value as after two, it is representative of a normal request, if not to take the same or less, representing a request not normal, the next step is not performed