You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spotipy技术求助:匹配redirect_uris后localhost仍无法连接

问题描述

我正在使用Spotipy API开发一款简易应用,此前个人使用正常,现拓展为支持用户通过Spotify账号登录。但生成授权链接并在浏览器打开后,localhost拒绝连接。

我使用SpotifyOAuth方法,传入client_id、client_secret及redirect_uri(http://localhost:8888/callback),调用get_authorize_url()获取链接后通过webbrowser.open打开。已确认凭证与redirect_uri在开发者设置和程序中完全一致,不清楚问题根源,恳请技术帮助。

代码片段:

sp_oauth = SpotifyOAuth(client_id= cred.client_id, client_secret= cred.client_secret,redirect_uri= cred.redirect_url, scope='user-top-read')
url = sp_oauth.get_authorize_url()
webbrowser.open(url)
排查解决方案
  • 启动本地回调服务:redirect_uri指向的localhost:8888需要有HTTP服务监听该端口,否则回调请求会被拒绝。你当前代码只生成了授权链接,但没有启动本地服务处理回调。可以用Spotipy内置的get_access_token()方法替代手动打开浏览器,它会自动启动本地HTTP服务器完成流程:
    sp_oauth = SpotifyOAuth(client_id=cred.client_id, client_secret=cred.client_secret, redirect_uri=cred.redirect_url, scope='user-top-read')
    token_info = sp_oauth.get_access_token()
    
    也可以自己用Flask等框架搭建简单服务监听8888端口的/callback路径。
  • 检查端口占用:用系统命令确认8888端口是否被其他程序占用。Windows执行netstat -ano | findstr :8888,Linux/macOS执行lsof -i :8888,如果被占用,要么关闭占用程序,要么更换redirect_uri的端口(同时更新Spotify开发者后台的对应设置)。
  • 排查防火墙拦截:本地防火墙或安全软件可能阻止了本地服务的连接,临时关闭后再测试。
  • 校验变量值:确认cred.redirect_url变量的实际值确实是http://localhost:8888/callback,避免变量赋值时的拼写错误。

内容的提问来源于stack exchange,提问作者pythoner360

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 20:50:29