【问题标题】:How to use 2 spotify endpoints, when one complement the other in Python?当 Python 中的一个与另一个互补时,如何使用 2 个 spotify 端点?
【发布时间】:2017-07-26 05:54:30
【问题描述】:

我正在学习使用 Python 和 Flask 使用 API,我目前正在使用 Spotify API,并且我想从具有此端点的艺术家那里获取热门曲目:https://api.spotify.com/v1/artists/{id } / Top-tracks,如您所见,我需要艺术家的 id 来获取他们的热门曲目,为此我使用了 SEARCH 端点 https://api.spotify.com/v1/search?q=name&type=artist ,这给了我一个包含艺术家数据的 JSON,我从那里得到了 id。

我现在的问题是,我如何使用 Top-Tracks 端点以及从 Search 端点获得的 id?我创建了一个名为“ide”的变量来存储艺术家的 ID,并能够将其连接到端点的 URL 中,但现在我不知道我的代码中的 Top-Tracks URL 的位置,或者我是否需要制作另一个函数,如何使用存储的 id 调用我的变量。

这是我的代码:

from flask import Flask, request, render_template, jsonify
import requests

app = Flask(__name__)

@app.route("/api/artist/<artist>")
def api_artist(artist):
    params = get_id(artist)
    return jsonify(params)

@app.route("/api/track/<artist>")
def api_track(artist):
    params = get_track(artist)
    return jsonify(params)

def get_id(artist):
    headers = { 
        "client_id": "xXxXx",
        "client_secret": "XxXxX"
    }

    response = requests.get("https://api.spotify.com/v1/search?q=" + artist +"&type=artist", headers=headers)

    if response.status_code == 200:
        print(response.text)
        list=[]
        response_dict = response.json()
        results = response_dict["artists"]
        items = results ["items"]
        for value in items:
            list.append(value["id"])

    params = {
        "id": list[0]
    }

    return list[0]

这是我尝试获得顶级曲目的方法,但它不起作用。

def get_track(artist):
    ide = list[0]
    can = requests.get("https://api.spotify.com/v1/artists/"+ ide + "/top-tracks?country=ES", headers=headers)
    return can

【问题讨论】:

  • 请确保在发布 Python 代码时准确地复制缩进。否则,您将在向人们展示的代码中引入新问题。
  • @khelwood 抱歉,感谢您的评论。
  • 响应的错误码(状态码)是什么?这是一个很好的第一条线索。看看 python 获取它的请求。
  • @FuzzyAmi NameError: 未定义全局名称“列表”

标签: python python-2.7 api flask spotify


【解决方案1】:

看起来它可能对learn a bit more about python scoping 有所帮助。 list[0]get_track 内部未定义的原因是它只能在您定义它的get_id 中访问。 get_track 的一个小改动可以让你访问get_track 中的 id:

def get_track(artist):
    # get the ID here so that you have access to it
    ide = get_id(artist)
    can = requests.get("https://api.spotify.com/v1/artists/"+ ide + "/top-tracks?country=ES", headers=headers)
    return can

希望有帮助!

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多