当尝试访问所有数据时,Flask WTForm 数据 return csrf_token

Flask WTForm data return csrf_token when try to access all data

我正在使用 Flask WTForm,并尝试使用 form.data 从 Flask Flask WTForm 获取数据,但是 return csrf_token 作为字段之一。

我的文件结构如下

$ tree .
.
└── testing_app
    ├── __init__.py
    ├── forms.py
    ├── templates
    │   ├── index.html
    │   └── submit.html
    └── views.py

forms.py

from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired

class MyForm(FlaskForm):
    name = StringField('name', validators=[DataRequired()])

views.py

from flask import Flask, render_template, redirect

from testing_app import forms

app = Flask(__name__)

app.config['SECRET_KEY'] = b'randomkey'

@app.route('/submit', methods=('GET', 'POST'))
def submit():
    form = forms.MyForm()
    if form.validate_on_submit():
        app.logger.debug(form.data)
        return redirect('/')
    return render_template('submit.html', form=form)

@app.route('/', methods=('GET', 'POST'))
def index():
    return render_template('index.html')

index.html

<html>
    this is index page
</html>

submit.html

<form method="POST" action="/submit">
    {{ form.csrf_token }}
    {{ form.name.label }} {{ form.name(size=20) }}
    <input type="submit" value="Go">
</form>

我运行它使用

export FLASK_APP=testing_app/views.py
export FLASK_DEBUG=1
flask run

 * Serving Flask app "testing_app.views"
 * Forcing debug mode on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 245-821-651

当我转到 http://127.0.0.1:5000/submit 并单击名称为 testok 时,它会重定向到 http://127.0.0.1:5000/ 并将数据记录为

--------------------------------------------------------------------------------
DEBUG in views [/Users/nile2691/my_tests/testing_app/views.py:13]:
{'csrf_token': 'TOKEN', 'name': 'test'}
--------------------------------------------------------------------------------
127.0.0.1 - - [25/Oct/2018 15:03:34] "POST /submit HTTP/1.1" 302 -
127.0.0.1 - - [25/Oct/2018 15:03:34] "GET / HTTP/1.1" 200 -

没有 csrf_token 有什么方法可以得到 data 吗?

我知道,我可以访问 form.name,但在我必须尝试的地方,它有 15 个字段,我试图避免对每个字段都做。

我也可以

for key, value in form.data.items():
    if key == 'csrf_token`:
        continue
    # process with other data

但如果我们在 Form 中添加 SubmitFieldform.data 也会 return。

我正在寻找 flask 方法,以便从表单中仅获取 stringselection 字段。

如果数据在 Flask-WTF 中有效,您可以访问所有数据,因为

form.name_of_input_field.data

在你的例子中是:

form = forms.MyForm()
if form.validate_on_submit():
    app.logger.debug(form.name.data) # not form.data
    return redirect('/')
return render_template('submit.html', form=form)

看看我的例子: create article form permalink to creating article

表单对象有一个 _fields 属性,它包含表单中的所有字段。如果你遍历它,你将可以访问字段名称、数据和类型,你可以构建你自己的数据字典,只包含你想要的字段类型。以下应该有效。

data = {field.name: field.data for field in form._fields.values() if type(field) in (StringField, SelectField)}