【问题标题】:Flask AttributeError: 'NoneType' object has no attribute 'split'Flask AttributeError:“NoneType”对象没有属性“split”
【发布时间】:2014-01-12 03:47:52
【问题描述】:
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) 也会出现错误。现在,当这两个都被删除时,我刷新页面并且代码运行,但没有正确的输出。接下来,我添加了拆分并重新加入并刷新了页面,代码运行良好,就像它应该没有错误一样。如何在无需删除、刷新和添加连接和拆分的情况下使其正常运行?

【问题讨论】:

    标签: python flask nonetype


    【解决方案1】:

    当查询字符串中没有"q"时,你会得到None.None没有名为split的方法,但是字符串有。

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

    应该是:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-13
      • 2016-09-11
      • 2022-11-13
      • 1970-01-01
      • 1970-01-01
      • 2014-12-29
      • 2020-06-25
      相关资源
      最近更新 更多