启用CSRF保护的Flask-WTF SelectField

时间:2013-05-29 12:37:26

标签: python flask csrf

提交包含动态填充的SelectField的表单时遇到问题。出于某种原因,当Flask尝试验证CSRF令牌时,它总是在SelectField在表单中时失败。当我从表单中删除SelectField时,它会成功验证CSRF令牌。

有没有人遇到过这种行为?

修改

形式:

class AddToReportForm(Form):
    selectReportField = SelectField(u'Reports',choices=[('test1','test')])

    def __init__(self, *args, **kwargs):
        """
        Initiates a new user form object
        :param args: Python default
        :param kwargs: Python default
        """
        Form.__init__(self, *args, **kwargs)




    def validate(self,id_list):
        rv = Form.validate(self)

        if not rv:
            print False
            #Check for the CSRF Token, if it's not there abort.
            return False

        print True
        return True

的Jinja2:

<form  method=post name="test">
{{ form.hidden_tag()}}




    {{ form.selectReportField }}
    <a href="#" onclick="$(this).closest('form').submit()" class="button save">Add to report</a>

</form>

渲染:

form = AddToReportForm()
return render_template('random',title='add reports',form=form

3 个答案:

答案 0 :(得分:3)

你在哪里设置SECRET_KEY?它必须在Form类中可用:

class AddToReportForm(Form):
    selectReportField = SelectField(u'Reports',choices=[('test1','test')])
    SECRET_KEY = "myverylongsecretkey"

    def __init__(self, *args, **kwargs):
        """
        Initiates a new user form object
        :param args: Python default
        :param kwargs: Python default
        """
        Form.__init__(self, *args, **kwargs)
    def validate(self,id_list):
        rv = Form.validate(self)

        if not rv:
            print False
            #Check for the CSRF Token, if it's not there abort.
            return False
        return True

或在应用程序引导程序中:

app = Flask(__name__)
app.secret_key = 'myverylongsecretkey'

或在构造函数中:

form = AddToReportForm(secret_key='myverylongsecretkey')
return render_template('random',title='add reports',form=form)

答案 1 :(得分:2)

我仍然看不到SelectField和CSRF之间的任何联系。 validate方法没什么可疑的,额外的参数会使下面的测试用例发生变化,但是现在看起来似乎工作正常:

from flask import Flask, render_template_string
from flaskext.wtf import Form, SelectField

app = Flask(__name__)
app.debug = True
app.secret_key = 's3cr3t'


class AddToReportForm(Form):
    selectReportField = SelectField(u'Reports', choices=[('test1', 'test')])


@app.route('/test', methods=['GET', 'POST'])
def test():
    form = AddToReportForm()
    if form.validate_on_submit():
        print 'OK'
    return render_template_string('''\
<form method=post name="test">
{{ form.hidden_tag()}}
{{ form.selectReportField }}
<input type="submit">
</form>
''', form=form)


app.run(host='0.0.0.0')

答案 2 :(得分:0)

推荐用途:

app.secret_key = 'key here' # key user defined