2014-01-12 98 views
2
from flask import Flask, render_template, request 
from sys import argv 
import requests 
import json 

app = Flask(__name__) 

def decrementList(words): 
    for w in [words] + [words[:-x] for x in range(1,len(words))]: 
     url = 'http://ws.spotify.com/search/1/track.json?q=' 
     request = requests.get(url + "%20".join(w)) 

     json_dict = json.loads(request.content) 
     track_title = ' '.join(w) 

     for track in json_dict["tracks"]: 
      if track["name"].lower() == track_title.lower() and track['href']: 
       return "http://open.spotify.com/track/" + track["href"][14:], words[len(w):] 

    return "Sorry, no more track matches found!" 

@app.route('/') 
def home(): 
    message = request.args.get('q').split() 
    first_arg = ' '.join(message) 

    results = [] 
    while message: 
     href, new_list = decrementList(message) 
     message = new_list 
     results.append(href) 

    return render_template('home.html', first_arg=first_arg, results=results) 

if __name__ == '__main__': 
    app.run(debug=True) 

在上面的代碼,當我運行這個程序瓶從我家裏功能得到一個錯誤AttributeError: 'NoneType' object has no attribute 'split。當我刪除它時,我也在' '.join(message)上發生錯誤。現在,當這兩個都被刪除我刷新頁面和代碼運行,但沒有正確的輸出。接下來,我添加了拆分並重新加入,並刷新了頁面,代碼完美無缺,就像沒有錯誤一樣。我怎樣才能得到這個正常運行,無需刪除,刷新和添加連接和拆分?瓶AttributeError的:「NoneType」對象有沒有屬性「分裂」

回答

3

查詢字符串中沒有"q"時,將得到NoneNone沒有名爲split的方法,但字符串有。

message = request.args.get('q').split() 

應該是:

message = request.args.get('q', '').split() 
+0

啊好感謝 – metersk

相關問題