为什么flask_wtf.FlaskForm上传文件时出现错误,提示文件未上传?

时间:2020-03-06 16:31:59

标签: python flask flask-restful

修改

如果我调用request.files['file']会得到文件对象,但是form.validate_on_submit()仍然会失败。如果请求中存在文件对象,为什么会失败?


我有三个文件:

forms.py

from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired

class ExcelForm(FlaskForm):
    excel_file = FileField(validators=[
        FileRequired()
    ])

webapp.py

from flask import Flask, render_template, redirect, url_for, request
from forms import ExcelForm
import pandas as pd

app = Flask(__name__)
app.config['SECRET_KEY'] = '314159265358'

@app.route('/', methods=['GET', 'POST'])
def upload():
    form = ExcelForm(request.form)

    if request.method == 'POST' and form.validate_on_submit():
        df = pd.read_csv(form.excel_file.data)
        print(df.head())

        return redirect(url_for('hello', name=form.excel_file.data))
    return render_template('upload.html', form=form)

@app.route('/hello/<name>')
def hello(name):
    return 'hello' + name

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)

templates \ upload.html

{% extends "layout.html" %}
{% block content %}
<form method = "POST" enctype = "multipart/form-data">
 {{ form.hidden_tag() }}
 <input type = "file" name = "file" />
 <input type = "submit"/>
</form>
{% endblock content %}

我可以毫无问题地访问localhost:5000/upload。我单击浏览按钮,选择我的文件,然后单击提交按钮。

webapp.py upload函数中,form.validate_on_submit()失败并给我一个错误,提示{'excel_file': ['This field is required.']}。有人可以告诉我我在做什么错吗?

我也不想将文件保存在本地以供以后读取。

1 个答案:

答案 0 :(得分:0)

您需要呈现flask-wtforms指定的表单字段。

实际上是从他们的文档中复制的...

{% extends "layout.html" %}
{% from "_formhelpers.html" import render_field %}
{% block content %}
<form method = "POST" enctype = "multipart/form-data">
    {{ form.hidden_tag() }}
    {{ render_field(form.file) }}
    {{ render_field(form.submit) }} <!-- add a submit button to your form -->
</form>
{% endblock content %}

然后创建宏

_formhelpers.html

{% macro render_field(field) %}
  <dt>{{ field.label }}
  <dd>{{ field(**kwargs)|safe }}
  {% if field.errors %}
    <ul class=errors>
    {% for error in field.errors %}
      <li>{{ error }}</li>
    {% endfor %}
    </ul>
  {% endif %}
  </dd>
{% endmacro %}