oauth2.0 TypeError:使用base 64时无法调用“module”对象

33qvvth1  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(126)

我正在使用Spotify API,我得到了时间错误TypeError: 'module' object is not callable
特别是处理授权流的代码部分

def get_info(code):
    auth_string = f'{os.getenv("Spotify_Client_ID")}:{os.getenv("Spotify_Client_Secret")}'
    auth_bytes = auth_string.encode('utf-8')
    auth_base64 = str(base64(auth_bytes), 'utf-8')

字符串

@app.route('/callback')
@cross_origin()
def getToken(): 
  print("INSIDE CALLBACK *****")
  code = request.args.get('code')

  if code:
        access_token, refresh_token , expires_in = get_info(code)
        if access_token:
            return f"Authentication successful! Access Token: {access_token}"
        else:
            return "Failed to obtain access token."
  else: 
   return "Authorization code not found in callback request."


我尝试将授权格式更改为base64.b64encode(auth_bytes).decode('utf-8'),但没有成功

bis0qfac

bis0qfac1#

使用“OAuth2Session”而不是“base64”处理授权基础要容易得多。
演示代码

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

app = Flask(__name__)

AUTH_URL = 'https://accounts.spotify.com/authorize'
TOKEN_URL = 'https://accounts.spotify.com/api/token'
PORT = 3000
REDIRECT_URI = f'http://localhost:{PORT}/callback' # my case is 'http://localhost:3000/callback'
CLIENT_ID = "<your client id>"
CLIENT_SECRET = "<your client secret>"
SCOPE = [
    "user-read-email",
    "playlist-read-collaborative"
]

@app.route("/login")
def login():
    spotify = OAuth2Session(CLIENT_ID, scope=SCOPE, redirect_uri=REDIRECT_URI)
    authorization_url, state = spotify.authorization_url(AUTH_URL)
    return redirect(authorization_url)

def get_info(code):
    res = requests.post(TOKEN_URL,
        auth = HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET),
        data = {
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': REDIRECT_URI
        })
    data = res.json()
    return data['access_token'], data['refresh_token'], data['expires_in']

@app.route("/callback", methods=['GET'])
def getToken():
    print("INSIDE CALLBACK *****")
    code = request.args.get('code')
    if code:
        access_token, refresh_token , expires_in = get_info(code)
        if access_token:
            return f"Authentication successful! Access Token: {access_token}"
        else:
            return "Failed to obtain access token."
    else: 
        return "Authorization code not found in callback request."
if __name__ == '__main__':
    app.run(port=PORT,debug=True)

字符串
运行它

python get-token.py


通过浏览器登录

http://localhost:3000/login


结果


的数据


6rqinv9w

6rqinv9w2#

好吧我解决的方法是我只是改变了

str(base64(auth_bytes), 'utf-8')

字符串

auth_base64 = base64.b64encode(auth_bytes).decode('utf-8')

相关问题