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