在窗体上选择服务器上的文件时出现错误的请求错误 [英] Bad request error when chosing file on server with form

查看:193
本文介绍了在窗体上选择服务器上的文件时出现错误的请求错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从flask.ext.wtf导入表格
从wtforms导入send_from_directory
从wtforms导入StringField,BooleanField
导入SelectField

从os导入os
从os.path导入listdir
导入isfile,连接

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

filenamesCrew = [f for listdir(crewPath)if iffile(join(crewPath,f))]
$ b $ class class UserInput(Form):
json_fileCrew = SelectField (),$ j
$ b def get_data(self):
json = send_from_directory(crewPath,self.json_fileCrew.data)$ {json_fileCrew,choices = [(f,f)for f in filenamesCrew] b $ b返回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'])#javascript将会调用这个
def data():
form = userInput(request.form [crewYear])
返回form.get_data()
pre>

 < form class =formaction =/ datamethod =post name =crewYear> 
{{form.hidden_​​tag()}}<! - CSFR config - >
< p>请选择一年:< br>
{{form.json_fileCrew}}< br>< / p>
< p>< input type =submitvalue =Submit>< / p>
< / form>

我在提交表单时遇到错误的请求错误。



项目文件的布局: > --- app
---views.py
---forms.py
--- static
---船员(约100个.json文件在这个文件夹中)
--- 1981.json
--- css
--- js
---模板
--- base.html
- --crew.html

我按照下面的答案修改了代码,但仍然收到404 Not Found Error我点击按钮。

解决方案

直接的问题是您传递请求的值。 form [crewYear] 到表单中,而不是整个 request.form






您的代码存在很多小问题。您不需要使用 send_from_directory ,因为从静态目录发送了更具体的功能。您应该以init的形式填充选择字段,否则将不会反映在应用程序启动后添加的任何文件。您应该使用 app.static_folder ,而不是硬编码路径。

 导入os $ b $ from烧瓶导入current_app $ b $ from flask_wtf从wtforms.field导入Form 
导入SelectField
$ b $ class CrewForm(Form):
filename = SelectField()
$ b $ def __init __(self,* args ,** kwargs):
root = os.path.join(current_app.static_folder,'Crews')
choices = [(f,f)for os.listdir(root)if os。 path.isfile(os.path.join(root,f))]
self.filename.kwargs ['choices'] = options
super(CrewForm,self).__ init __(* args,** kwargs)

@ app.route('/ crew',methods = ['GET','POST'])
def crew():
form = CrewForm
$ b $ if form.validate_on_submit():
return current_app.send_static_file('Crews / {}'。format(form.filename.data))

return render_template ('crew.html',form = form)



 &升t; form method =post> 
{{form.hidden_​​tag()}}
{{form.filename}}
< input type =submitvalue =Get Data/>
< / form>

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


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>

I am getting a "Bad Request" error when I submit the form. How do I fix this?

The layout of project files:

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

I modified code according answer below but I still get a 404 Not Found Error when I click the button.

解决方案

The immediate problem is that you're passing the value of request.form["crewYear"] to your form, rather than the entire request.form.


There are a lot of minor problems with your code. You don't need to use send_from_directory, since there's a more specific function to send from the static directory. You should populate the select field in the form init, otherwise it will not reflect any files added after the app starts. You should use app.static_folder rather than hard coding the path. You have two routes that do the same thing.

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>

Consider reading the Flask tutorial and Flask-WTF docs, as they clearly explain how to use forms. Reading PEP 8 would also be beneficial, as your code style is very inconsistent.

这篇关于在窗体上选择服务器上的文件时出现错误的请求错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆