Flask_form:CSRF令牌不匹配

时间:2017-09-12 08:24:14

标签: 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>

views.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')

表格

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.')])

为什么我会收到此错误?

3 个答案:

答案 0 :(得分:3)

我遇到了同样的问题,我只是想知道发生了什么:饼干!清除我的Cookie即可立即解决该问题。

答案 1 :(得分:2)

您需要在表单中添加CSRF输入字段,如docs

中所述
<form method="post">
  {{ form.csrf_token }}
</form>

每个WTForms验证都会检查此请求数据在POST请求数据中的可用性,除非它是explicitly disabled

答案 2 :(得分:2)

我发现原因之一是APPLICATION_ROOT的设置不正确。

知道“ CSRF令牌不匹配” 错误会花费多少时间,我将发布部分答案。