Flask AttributeError:'NoneType'对象没有属性'split'

时间:2014-01-12 03:47:52

标签: python flask nonetype

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)

在上面的代码中,当我运行此Flask应用程序时,我从home函数中收到错误AttributeError: 'NoneType' object has no attribute 'split。当我删除它时,我也会在' '.join(message)上收到错误消息。现在,当这两个都被删除时,我刷新页面并运行代码,但没有正确的输出。接下来,我添加了拆分并重新加入并刷新页面,代码完美无缺,就像它应该没有错误一样。如何在不必删除,刷新和添加连接并拆分的情况下正常运行?

1 个答案:

答案 0 :(得分:3)

如果查询字符串中没有"q",您将获得NoneNone没有名为split的方法,但字符串已包含。{/ p>

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

应该是:

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