flask实现一个简单的注册界面报错
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
<!-- {
{ form.hidden_tag() }}-->
{
{form.username.label}}
{
{form.username}}
<br>
{
{form.password.label}}
{
{form.password}}
<br>
{
{form.password2.label}}
{
{form.password2}}
<br>
{
{form.submit}}
</form>
</body>
</html>
from flask import Flask, render_template, request
from wtforms import StringField, PasswordField, SubmitField
from flask_wtf import FlaskForm
from wtforms.validators import DataRequired, EqualTo
app = Flask(__name__)
app.config['SECRET_KEY'] = 'abc123'
class Register(FlaskForm):
username = StringField(label='Username', validators=[DataRequired("用户名不能为空")])
password = PasswordField(label='password', validators=[DataRequired("密码不能为空")])
password2 = PasswordField(label='password2', validators=[DataRequired("密码不能为空"), EqualTo('password')])
submit = SubmitField(label='Sign Up')
@app.route('/register', methods=[ 'GET','POST'])
def register():
form = Register()
if request.method == 'POST':
print(999)
if form.validate_on_submit():
print("验证成功")
username = form.username.data
password = form.password.data
password2 = form.password2.data
print(username, password, password2)
else:
print(form.errors)
print("验证失败")
elif request.method == 'GET':
return render_template('register.html', form=form)
return render_template('register.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
-
{'csrf_token': ['The CSRF token is missing.']}
表示在表单提交时,缺少 CSRF(跨站请求伪造)令牌。 -
当使用
Flask-WTF
时,为了防止 CSRF 攻击,默认会启用 CSRF 保护。这意味着在表单中需要包含一个 CSRF 令牌,并且在表单提交时,服务器会验证这个令牌是否存在且有效。在你的
register.html
模板中,确保使用form.hidden_tag()
来包含 CSRF 令牌。