使用表单在服务器上选择文件时出现错误请求错误

Bad request error when chosing file on server with form

from flask.ext.wtf import Form
from flask import send_from_directory
from wtforms import StringField, BooleanField
from wtforms import SelectField

import os
from os import listdir
from os.path import isfile, join

crewPath =  ("/myproject/app/static/Crews")

filenamesCrew = [f for f in listdir(crewPath) if isfile(join(crewPath,f)) ]

class userInput(Form):
    json_fileCrew = SelectField(u"json_fileCrew", choices=[(f, f) for f in filenamesCrew])

    def get_data(self):
        json = send_from_directory (crewPath, self.json_fileCrew.data)
        return json

@app.route('/CastCrew', methods=['GET', 'POST'])
def castCrew():
    form = userInput(request.form["crewYear"])
    return render_template('CastCrew.html', title = 'Cast Crew View', form = form)

@app.route("/data", methods=['GET', 'POST']) #the javascript will call this
def data():
    form = userInput(request.form["crewYear"])
    return form.get_data()
<form class = "form" action="/data" method="post" name="crewYear">
    {{ form.hidden_tag() }} <!--CSFR config -->
    <p>Please choose a year:<br>
    {{ form.json_fileCrew }}<br></p>
    <p><input type="submit" value="Submit"></p>
</form>

我在提交表单时遇到 "Bad Request" 错误。我该如何解决这个问题?

项目文件布局:

---app
        ---views.py
        ---forms.py
        ---static
               ---Crews (about 100 .json files in this folder)
                     ---1981.json
               ---css
               ---js
        ---templates
             ---base.html
             ---crew.html

我根据下面的答案修改了代码,但是当我点击按钮时仍然出现 404 Not Found 错误。

眼前的问题是您将 request.form["crewYear"] 的值传递给您的表单,而不是整个 request.form


您的代码有很多 小问题。您不需要使用 send_from_directory,因为有一个更具体的函数可以从静态目录发送。您应该填充表单初始化中的 select 字段,否则它不会反映应用程序启动后添加的任何文件。您应该使用 app.static_folder 而不是对路径进行硬编码。你有两条路线做同样的事情。

import os
from flask import current_app
from flask_wtf import Form
from wtforms.field import SelectField

class CrewForm(Form):
    filename = SelectField()

    def __init__(self, *args, **kwargs):
        root = os.path.join(current_app.static_folder, 'Crews')
        choices = [(f, f) for f in os.listdir(root) if os.path.isfile(os.path.join(root, f))]
        self.filename.kwargs['choices'] = choices
        super(CrewForm, self).__init__(*args, **kwargs)

@app.route('/crew', methods=['GET', 'POST'])
def crew():
    form = CrewForm()

    if form.validate_on_submit():
        return current_app.send_static_file('Crews/{}'.format(form.filename.data))

    return render_template('crew.html', form=form)
<form method="post">
    {{ form.hidden_tag() }}
    {{ form.filename }}
    <input type="submit" value="Get Data"/>
</form>

考虑阅读 Flask 教程和 Flask-WTF 文档,因为它们清楚地解释了如何使用表单。阅读 PEP 8 也会有所帮助,因为您的代码风格非常不一致。