使用Flask WTF-Forms手动生成CSRF令牌 [英] Generating a CSRF token manually with Flask WTF-Forms

查看:64
本文介绍了使用Flask WTF-Forms手动生成CSRF令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想使用python代码创建并填写Flask WTF-Form.但是,当我使用python代码创建表单时,该表单不会自动生成CSRF令牌.有什么办法可以手动执行此操作吗?

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?

有问题的表格:

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():
        ...

推荐答案

通过在本地生成令牌并将令牌传递给表单,您将有效地禁用CSRF保护.仅在用户提交先前生成的令牌时有效.

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.

由于您没有使用CSRF保护,请禁用它.您还可以传递 request.args 作为数据源.

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)

如果要对此表单使用CSRF,则表单需要发送 csrf_token 字段,该字段可以使用 {{form.csrf_token}} 呈现 {{form.hidden_​​tag()}} .

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() }}.

这篇关于使用Flask WTF-Forms手动生成CSRF令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆