如何访问重定向URI返回的参数?Spotify授权码获取问题
解决Spotify授权码流程中获取code的问题
你的核心问题在于:requests.get发起的是后端HTTP请求,和你用webbrowser.open打开的浏览器会话完全独立。浏览器里用户完成授权后的重定向操作,requests无法捕获到,所以self.mostRecentResponse只会保留初始授权页面的请求结果,拿不到带code的重定向URI。
下面给你几种不用Flask这类框架的解决方案:
方案1:用Python内置HTTP服务器监听本地回调
把redirect_uri设为本地地址(比如http://localhost:8888/callback),然后启动一个临时HTTP服务器监听这个端口,用户授权后Spotify会跳转到这个本地地址,服务器就能捕获到code参数。
示例代码:
import webbrowser import requests from http.server import BaseHTTPRequestHandler, HTTPServer import threading import urllib.parse class SpotifyCallbackHandler(BaseHTTPRequestHandler): code = None def do_GET(self): # 解析请求路径中的参数 parsed_path = urllib.parse.urlparse(self.path) query_params = urllib.parse.parse_qs(parsed_path.query) if 'code' in query_params: # 提取code SpotifyCallbackHandler.code = query_params['code'][0] # 返回成功页面给用户 self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(b'授权成功!可以关闭这个页面了。') # 关闭服务器 self.server.shutdown() class SpotifyAuth: AUTH_URL = 'https://accounts.spotify.com/authorize' _CLIENT_ID = '你的client_id' SCOPE = '需要的权限范围' def getRandomString(self): # 实现你的随机字符串生成逻辑 return 'random_state_123' def getPermissions(self): # 启动本地服务器 server_address = ('', 8888) httpd = HTTPServer(server_address, SpotifyCallbackHandler) # 用线程启动服务器,避免阻塞主线程 server_thread = threading.Thread(target=httpd.serve_forever) server_thread.daemon = True server_thread.start() params = { "response_type": "code", "client_id": self._CLIENT_ID, "scope": self.SCOPE, "redirect_uri": "http://localhost:8888/callback", "state": self.getRandomString(), "show_dialog": "false" } auth_url = requests.Request('GET', self.AUTH_URL, params=params).prepare().url webbrowser.open(auth_url) # 等待服务器获取code server_thread.join() print(f"获取到的code: {SpotifyCallbackHandler.code}") return SpotifyCallbackHandler.code # 使用示例 auth = SpotifyAuth() auth.getPermissions()
方案2:用封装好的第三方库(推荐)
直接用spotipy库,它已经封装了Spotify的授权流程,不用自己处理回调和code提取:
首先安装库:
pip install spotipy
示例代码:
import spotipy from spotipy.oauth2 import SpotifyOAuth sp = spotipy.Spotify(auth_manager=SpotifyOAuth( client_id='你的client_id', client_secret='你的client_secret', redirect_uri='http://localhost:8888/callback', scope='需要的权限范围' )) # 直接使用API,auth_manager会自动处理授权和token刷新 current_user = sp.current_user() print(current_user)
方案3:手动复制code(体验较差)
如果只是临时测试,可以把redirect_uri设为一个你能访问的网页(比如你原来用的youtube.com),用户授权后,浏览器地址栏会出现带code的URL,让用户手动复制code,然后输入到你的程序中:
import requests import webbrowser class SpotifyAuth: AUTH_URL = 'https://accounts.spotify.com/authorize' _CLIENT_ID = '你的client_id' SCOPE = '需要的权限范围' def getRandomString(self): return 'random_state_123' def getPermissions(self): params = { "response_type": "code", "client_id": self._CLIENT_ID, "scope": self.SCOPE, "redirect_uri": "https://youtube.com", "state": self.getRandomString(), "show_dialog": "false" } auth_url = requests.Request('GET', self.AUTH_URL, params=params).prepare().url webbrowser.open(auth_url) # 让用户输入复制的code code = input("请输入浏览器地址栏中的code参数:") print(f"你输入的code: {code}") return code auth = SpotifyAuth() auth.getPermissions()
内容的提问来源于stack exchange,提问作者yipjones2
相关产品推荐
相关产品推荐

