0

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

问题

在http请求中,当我设置时data={'name': 'playlist_name', 'description': 'something'},我得到一个响应:“error”:{“status”:400,“message”:“Error parsing JSON。”}

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

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

应用程序.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()

4

1 回答 1

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')
于 2021-06-26T20:58:30.497 回答