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

时间:2015-05-21 16:15:28

标签: python flask flask-wtforms

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>

我提交表单时收到“错误请求”错误。我该如何解决这个问题?

项目文件的布局:

---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错误。

1 个答案:

答案 0 :(得分:6)

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

您的代码存在很多的小问题。您不需要使用send_from_directory,因为从静态目录发送更具体的函数。您应该在表单init中填充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也是有益的,因为你的代码风格非常不一致。