【问题标题】:Spotify API create playlist - error parsing JSONSpotify API 创建播放列表 - 解析 JSON 时出错
【发布时间】:2021-06-26 20:19:39
【问题描述】:

我有一个 Flask 应用程序,我想在其中使用 Spotify API 创建播放列表。我的问题类似于this Stackoverflow question。 不同之处在于我使用的是OAuthlib 而不是requests,并且在我的情况下发布的解决方案不起作用。

问题

在http请求中,当我设置data={'name': 'playlist_name', 'description': 'something'}时, 我收到回复:“错误”:{“状态”:400,“消息”:“解析 JSON 时出错。”}

但是当我按照上面提到的答案尝试这个:data=json.dumps({'name': 'playlist_name', 'description': 'something'}), 我在控制台中收到以下错误:“ValueError: no enough values to unpack (expected 2, got 1)”。

我该如何解决这个问题?这是我的应用的简化版本:

app.py

from flask import Flask, url_for, session
from flask_oauthlib.client import OAuth

import json

app = Flask(__name__)
app.secret_key = 'development'
oauth = OAuth(app)

spotify = oauth.remote_app(
    'spotify',
    consumer_key=CLIENT,
    consumer_secret=SECRET,
    request_token_params={'scope': 'playlist-modify-public playlist-modify-private'},
    base_url='https://accounts.spotify.com',
    request_token_url=None,
    access_token_url='/api/token',
    authorize_url='https://accounts.spotify.com/authorize'
)

@app.route('/', methods=['GET', 'POST'])
def index():
    callback = url_for(
        'create_playlist',
        _external=True
    )
    return spotify.authorize(callback=callback)


@app.route('/playlist', methods=['GET', 'POST'])
def create_playlist():
    resp = spotify.authorized_response()
    session['oauth_token'] = (resp['access_token'], '')


    username = USER
    return spotify.post('https://api.spotify.com/v1/users/' + username + '/playlists',
                                   data=json.dumps({'name': 'playlist_name', 'description': 'something'}))


@spotify.tokengetter
def get_spotify_oauth_token():
    return session.get('oauth_token')


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

【问题讨论】:

    标签: python flask spotify flask-oauthlib


    【解决方案1】:

    您正在使用data 参数,该参数采用dict 对象,但您将其转储为字符串,这不是必需的。此外,您必须将格式设置为 json,如下所示:

    @app.route('/playlist', methods=['GET', 'POST'])
    def create_playlist():
        resp = spotify.authorized_response()
        session['oauth_token'] = (resp['access_token'], '')
    
    
        username = USER
        return spotify.post('https://api.spotify.com/v1/users/' + username + '/playlists',
                                       data={'name': 'playlist_name', 'description': 'something'}, format='json')
    

    【讨论】:

    • 我试过这个并收到TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a OAuthResponse.:/
    • 啊,我错误地返回了 spotify.post(....),更正了。但不幸的是它也不起作用,现在我在解析 JSON 时遇到 http 400 错误。
    • 我用“格式”参数编辑了我的答案。请试试这个。
    • 现在我收到了AttributeError: 'dict' object has no attribute 'data'。我想先自己弄清楚,但似乎我真的做不到
    • 奇怪,但我再次检查,它的工作原理;播放列表已创建,我没有收到任何错误。谢谢!
    猜你喜欢
    • 2018-06-13
    • 1970-01-01
    • 2017-04-28
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多