Flask_form : CSRF Token 不匹配

use*_*113 4 python flask flask-wtforms

我在我的 Flask 应用程序中使用了 flask_form 并且现在已经被“CSRF 令牌不匹配”卡住了几个小时。

<form method="post" action="{{ url_for('auth.login') }}" role="form">
    {{ form.hidden_tag() }}
    {{ wtf.form_errors(form, hiddens="only") }}
    {{ wtf.form_field(form.email)}}
    {{ wtf.form_field(form.password)}}
    <p><button type="submit">Login</button></p>
</form>
Run Code Online (Sandbox Code Playgroud)

视图.py

@auth.route('/login', methods=['GET', 'POST'])
def login():

    form = LoginForm()
    if form.validate_on_submit():

        print('login form received on server and is valid')
        # check whether user exists in the database and whether
        # the password entered matches the password in the database
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data) and check_password_hash(user.pwd, form.password.data):
            # log employee in
            login_user(user) #,remember=True)

            # redirect to the home page after login
            return redirect(url_for('grapher.upload'))

        # when login details are incorrect
        else:
            flash('Invalid email or password.', 'info')

    # load login template
    return render_template('auth/login.html', form=form, title='Login')
Run Code Online (Sandbox Code Playgroud)

形式

class LoginForm(FlaskForm):
    email = StringField('Email', validators=[DataRequired(), Email(),    Length(min=1,max=254, message='The maximum length of this filed is 254 characters')])
    password = PasswordField('Password', validators=[DataRequired(), Length(max=20, message='Password maximium length is 20 characters.')])
Run Code Online (Sandbox Code Playgroud)

为什么我会收到这个错误?

use*_*576 5

我遇到了同样的问题,我刚刚弄清楚发生了什么:cookies!清除我的站点 cookie 立即解决了问题。


Ser*_*bin 2

您需要在表单中添加 CSRF 输入字段,如文档中所述:

<form method="post">
  {{ form.csrf_token }}
</form>
Run Code Online (Sandbox Code Playgroud)

每个 WTForms 验证都会检查 POST 请求数据中此令牌的可用性,除非明确禁用它。