English 中文(简体)
页: 1
原标题:Python - Spotify API - No Authorization Code received with <Response [200]>

I have looked at several posts here about issues very close to this one including one that is exactly the same but no one gave an answer so I am going to give it a go. I am very new to Python. My current homework is to connect to Spotify using their API. According to the documentation on authorization code flow in Spotify. the response to the authorization request should provide two items: code and state.

After I send my request

def authenticate_user():
auth_code = requests.get(ENPOINT_USER_AUTH, {
     client_id : CLIENT_ID,
     response_type :  code ,
     redirect_uri :  https://www.example.com/ ,
     scope :  playlist-modify-private 
})

print(f Auth code: {auth_code} )

我收到了一部《奥特法典》:和;Response [200]> 然而,答复并不包括法典或州。 不过,在答复中,我可以把斜线复制到浏览器上,再把我引向一辆带有该代码的电灯车。

My issue here is, I want to save that code into a variable in my Python code. This copy-pasting into a browser can t be the way to do this.

我的另一个问题是,我确实不知道打背服务器/转机是什么,如何利用或设置信息以提取这种信息,或者在我的假刑法中如何做到这一点。

基本上,我对许多开端人表示歉意。 但是,时间是研究和阅读时间,我确实希望提出一些意见。

This is what the redirect URL looks like after pasting the URL I get in the response.

https://www.example.com/?code=AQAqA0eYYk......JLVUomOR0ziDTcIupZoU

我希望这一点是明确的,我是明智的。

事先感谢你。

吴 Oh和我知道Spotipy,它本应简化事情,但我不感兴趣。 我想学会利用欧洲复兴开发银行。

www.un.org/Depts/DGACM/index_spanish.htm 简明扼要: 我如何能够从“URL”的回复中获取这一“代码”,并将它从我的《规则》中从方案上变成一个变量?

问题回答

我将翻两版(完整和简单),以获得

Full Version

该代码为Flaskrequests_oauthlib>。

Developer Dashboard

https://developer.spotify.com/dashboard

Save as full_code.py file name.

from flask import Flask, request, redirect
from requests_oauthlib import OAuth2Session
from requests.auth import HTTPBasicAuth
import os
import requests
import json

app = Flask(__name__)

AUTH_URL =  https://accounts.spotify.com/authorize 
TOKEN_URL =  https://accounts.spotify.com/api/token 
PORT = 3000 # replace <your redirect port>
REDIRECT_URI =  http://localhost:{}/callback .format(PORT) # my configuration is  http://localhost:3000/callback  in dashboard
CLIENT_ID =  <your client id> 
CLIENT_SECRET =  <your client secret> 
# You can add your required scopes
SCOPE = [
     user-read-currently-playing ,
     playlist-modify-private 
]
@app.route("/login")
def login():
    spotify = OAuth2Session(client_id = CLIENT_ID, scope=SCOPE, redirect_uri=REDIRECT_URI)
    authorization_url, state = spotify.authorization_url(AUTH_URL)
    return redirect(authorization_url)

@app.route("/callback", methods=[ GET ])
def callback():
    code = request.args.get( code )
    response = requests.post(TOKEN_URL,
        auth = HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET),
        data = {
             grant_type :  authorization_code ,
             code : code,
             redirect_uri : REDIRECT_URI
        })
    # Save Access Token to environment variable
    os.environ[ ACCESS_TOKEN ] = response.json()[ access_token ]
    headers = {
        # Get Access Token from environment variable
         Authorization : "Bearer {}".format(os.environ[ ACCESS_TOKEN ])
    }

    # get playlist API call with <your playlist id>
    url =  https://api.spotify.com/v1/playlists/{} .format( 37i9dQZF1DX0tnKPLNG9Ld )
    response = requests.get(url, headers=headers)
    results = response.json()
    songs = []
    for item in results[ tracks ][ items ]:
        if (item is not None and item[ track ][ artists ][0] is not None):
            # display format <artists name : song title>
            songs.append(item[ track ][ artists ][0][ name ]  + " : " + item[ track ][ name ])
    return json.dumps(songs)

if __name__ ==  __main__ :
    app.run(port = PORT,debug = True)

送达

python full_code.py

然后由浏览器开放URL

http://localhost:3000/login

成果 enter image description here

Simple Version

http://spotipy.readthedocs.io/en/2.22.1/#"rel=“nofollow noreferer”

Save as simple_code.py file name.

import spotipy
from spotipy.oauth2 import SpotifyOAuth

PORT = 3000 # replace <your redirect port>
REDIRECT_URI =  http://localhost:{}/callback .format(PORT) # my configuration is  http://localhost:3000/callback  in dashboard
CLIENT_ID =  <your client id> 
CLIENT_SECRET =  <your client secret> 
PLAYLIST_ID =  37i9dQZF1DX0tnKPLNG9Ld  # <your playlist id>

sp = spotipy.Spotify(
    auth_manager = SpotifyOAuth(
        client_id = CLIENT_ID,
        client_secret = CLIENT_SECRET,
        redirect_uri = REDIRECT_URI,
        # You can add your required scopes
        scope=[ user-read-currently-playing , playlist-modify-private ]))

def Get_Playlist(playlist_id):
    # get playlist API call
    results = sp.playlist(playlist_id)
    for item in results[ tracks ][ items ]:
        if (item is not None and item[ track ][ artists ][0] is not None):
            # artists name : song title
            print(item[ track ][ artists ][0][ name ]  + "	" + " : " + item[ track ][ name ])

Get_Playlist(PLAYLIST_ID)

送达

python simple_code.py

成果

“在座的影像描述”/</a

但是,答复不包括法典或州。

这很可能包括那些人,但你不会重印他们实际看到的正确方式。

请重印whole response<Response [200]>只是你打印时出现的缺省答复标本。

相反,它将印刷答复中所载的个人数据要素:

print(auth_code.json())




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...