调用Trello API下载附件时遭遇401权限错误求助
Trello附件下载返回401错误的解决方案
问题根源
Trello返回的附件url是网页预览地址,直接访问该地址不会携带你的API授权凭证,因此服务器返回401未授权错误。必须在下载请求中同样传递key和token参数,或者使用API提供的专属下载链接。
修正后的完整代码
import os import requests # 替换为你的目标卡片ID card_id = "替换为实际卡片ID" # 获取Trello卡片附件的API地址 url = f"https://api.trello.com/1/cards/{card_id}/attachments" # 请求头 headers = { "Accept": "application/json" } # 填入你的API密钥和Token query = { 'key': '你的API Key', 'token': '你的Token' } # 发送请求获取附件信息 response = requests.get(url, headers=headers, params=query) # 检查请求是否成功 if response.status_code == 200: # 解析JSON响应 attachments = response.json() # 遍历所有附件 for attachment in attachments: # 使用API返回的downloadUrl作为直接下载链接,比url更可靠 download_url = attachment.get('downloadUrl') if download_url: print(f"正在从URL下载图片: {download_url}") # 优先使用附件的原始名称作为文件名,避免URL分割的异常 image_name = attachment.get('name', download_url.split('/')[-1]) # 桌面路径 desktop_path = os.path.join(os.path.expanduser("~"), "Desktop", image_name) # 下载时携带授权参数,解决401问题 image_response = requests.get(download_url, stream=True, params=query) if image_response.status_code == 200: # 将图片保存到桌面 with open(desktop_path, 'wb') as f: for chunk in image_response.iter_content(1024): f.write(chunk) print(f"图片已保存至: {desktop_path}") else: print(f"下载图片时出错: {image_response.status_code}") else: print("未找到附件的下载URL。") else: print(f"获取附件信息时出错: {response.status_code}")
核心修改说明
- 补充了
requests库的导入(原代码遗漏该依赖) - 替换
url字段为downloadUrl,这是Trello提供的直接下载资源的专属链接 - 在下载图片的请求中添加
params=query,携带API授权凭证,解决未授权问题 - 优先使用附件的
name字段作为文件名,避免通过URL分割得到错误文件名
内容的提问来源于stack exchange,提问作者Рустам Рысаев
相关产品推荐
相关产品推荐

