Generating a CSRF token manually with Flask WTF-Forms

荒凉一梦 提交于 2019-12-11 07:34:07

问题


I'd like to create and fill out a Flask WTF-Form using only python code. However, the form doesn't automatically generate a CSRF token when I create it with python code. Is there any way to do this manually?

The form in question:

from flask_wtf import Form
from wtforms import StringField
from wtforms.validators import DataRequired, URL

class URLForm(Form):
    url = StringField('url', validators=[DataRequired(), URL(), Level3Url()])

the code I use to generate the form:

from forms import URLForm
form = URLForm()
if 'url' in request.args:
    url = request.args.get('url')
    form.url.data = url
    if form.validate():
        ...

回答1:


You'd be effectively disabling CSRF protection by generating and passing a token to the form locally. It's only effective when the user submits a previously generated token.

Since you're not using CSRF protection, disable it. You can also pass request.args as the source of data.

form = URLForm(request.args, csrf_enabled=False)

If you want to use CSRF for this form, then the form needs to send the csrf_token field, which can be rendered with {{ form.csrf_token }} or {{ form.hidden_tag() }}.




回答2:


In newest version of flask_wtf (0.14.2) you can disable csrf token in this way.

form = URLForm(request.args, meta={'csrf': False})


来源:https://stackoverflow.com/questions/38231010/generating-a-csrf-token-manually-with-flask-wtf-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!