调用Spotify获取最近播放曲目接口仅返回部分数据的问题求助
调用Spotify获取最近播放曲目接口仅返回部分数据的问题求助
看起来你的问题大概率是响应内容的解析方式导致的截断,或者是没有完整获取到响应体。给你几个排查和解决的方向:
1. 改用请求库内置的JSON解析方法
从代码里的get方法来看,你应该是用requests库发送的请求。现在你手动用json.loads(tracks.content)解析字节流响应,这种方式很容易因为编码、压缩(比如gzip)等细节问题导致内容截断或解析错误。换成库内置的.json()方法会更可靠:
def get_recent_tracks(token,unix_time): url = "https://api.spotify.com/v1/me/player/recently-played" headers = get_auth_header(token) parameters = { "limit": 50, # 接口最大限制是50 "after" : unix_time } response = requests.get(url, params=parameters, headers=headers) # 直接使用requests内置的JSON解析 return response.json()
2. 验证响应体是否完整接收
你可以先检查响应的内容长度,确认是不是真的只收到了部分数据:
def get_recent_tracks(token,unix_time): url = "https://api.spotify.com/v1/me/player/recently-played" headers = get_auth_header(token) parameters = { "limit": 50, # 接口最大限制是50 "after" : unix_time } response = requests.get(url, params=parameters, headers=headers) # 对比响应头声明的长度和实际接收的内容长度 declared_length = response.headers.get('Content-Length') actual_length = len(response.content) print(f"接口声明的内容长度: {declared_length}") print(f"实际接收的内容长度: {actual_length}") # 也可以把原始内容写入文件,直观检查是否截断 with open("response_raw.txt", "wb") as f: f.write(response.content) return response.json()
如果两者长度不一致,说明网络传输中响应没完整接收,可以尝试开启流模式手动读取所有内容:
response = requests.get(url, params=parameters, headers=headers, stream=True) response.raw.decode_content = True # 自动处理gzip压缩的响应 full_content = b''.join(response.iter_content(chunk_size=1024)) recent_tracks_json = json.loads(full_content)
3. 排查解析前的原始内容
先不要急于解析成JSON,直接打印原始响应文本,确认是接口真的返回了截断内容,还是解析环节出了问题:
def get_recent_tracks(token,unix_time): url = "https://api.spotify.com/v1/me/player/recently-played" headers = get_auth_header(token) parameters = { "limit": 50, # 接口最大限制是50 "after" : unix_time } response = requests.get(url, params=parameters, headers=headers) # 打印原始文本,检查是否截断 print("原始响应文本:", response.text) return response.json()
补充说明
你提到响应状态码是200,令牌也正常,那基本排除权限和请求格式问题。最可能的原因就是手动解析字节流时的编码/压缩处理不当,改用response.json()应该能解决大部分这类问题。
备注:内容来源于stack exchange,提问作者willow
相关产品推荐
相关产品推荐

