2015-03-31 76 views
1

我正在創建一個由用戶從下拉框中選擇的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 

我使用

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

叫它views.py我得到這個錯誤

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' 

我不明白爲什麼我得到這個錯誤。我想查看文件夾並返回與用戶選擇的名稱相同的json文件(例如1981.json)。

編輯下面是userInput類

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) 
+0

userInput是表單所在的類,也是def get_data(json_fileCrew)所在的類。對不起,這從代碼中不是很清楚。 @davidism – gbhrea 2015-04-01 13:51:36

回答

0

get_data方法是...方法。因此,即使您將該參數稱爲「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不返回JSON數據,那麼,爲什麼你叫他們的方式目前還不清楚。

您正在使用一些非常規變量名稱。有關大多數Python程序員所期望的標準格式,請參閱PEP 8

+0

謝謝@davidism,我現在明白髮生了什麼事情。這擺脫了錯誤,但我現在在cmd提示符下獲得404 - 「GET/data HTTP/1.1」404 - – gbhrea 2015-04-01 15:35:05

+0

@gbhrea最好的猜測是您嘗試提供的文件不存在。嘗試調試您的代碼,例如逐步執行'send_from_directory'並查看嘗試提供服務的路徑。 – davidism 2015-04-01 15:38:57