Flask,无法 return 用户选择的静态文件

Flask, unable to return static file as chosen by user

我正在创建一个 json 数据的可视化效果,该数据由用户从下拉框中选择。下拉框由文件夹 app/static/Crews 中的 json 个文件的名称填充。 javascript d3 代码调用一个使用所选 json 文件的函数,

d3.json("/data", function(error, graph)

这是我用来填充下拉框的代码,

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

这是我必须获取 json 文件的函数。

def get_data(json_fileCrew):
        json = send_from_directory ("/myproject/app/static/Crews" , json_fileCrew)
        return json

我在 views.py 中使用

调用它
@app.route("/data", methods=['GET']) 
def data():
        u = userInput()
        json = u.get_data()
        return json

我收到这个错误

    json = u.get_data()
  File "\project\myproject\forms.py", line 34,
in get_data
    json = send_from_directory ("/myproject/app/static/Crews" , json_fileCrew)
  File "C:\Python34\lib\site-packages\flask\helpers.py", line 612, in send_from_
directory
    filename = safe_join(directory, filename)
  File "C:\Python34\lib\site-packages\flask\helpers.py", line 574, in safe_join
    filename = posixpath.normpath(filename)
  File "C:\Python34\lib\posixpath.py", line 335, in normpath
    initial_slashes = path.startswith(sep)
AttributeError: 'userInput' object has no attribute 'startswith'

我不明白为什么会出现此错误。我想查看文件夹和 return 与用户选择的文件同名的 json 文件(例如 1981.json)。

EDIT 这是 userInput 的完整代码 class

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

    def get_data(json_fileCrew):
        json = send_from_directory ("/myproject/app/static/Crews",json_fileCrew)
        return json

我也尝试了下面的代码,但没有用。

 if os.path.isfile(os.path.join(crewPath, json_fileCrew)):
            return send_from_directory(crewPath, json_fileCrew)

get_data 方法是...一种方法。所以它得到的第一个参数是 self,即使你调用那个参数 "json_fileCrew"。您似乎希望该方法访问 SelectField 的表单值。您可以通过 self.json_fileCrew.data.

的方法访问它
class UserInput(Form):
    filename = SelectField(choices=[(f, f) for f in crew_files])

    def get_data(self):
        return send_from_directory(crew_path, self.filename.data)

表单收不到json数据,get_data收不到returnjson数据,不清楚你为什么以这种方式命名它们。

您使用了一些非常规的变量名。请参阅 PEP 8 了解大多数 Python 程序员期望的标准格式。