使用py-trello下载Trello卡片附件时遭遇401未授权错误
解决Trello附件下载401未授权问题
直接请求attachment.url会触发401错误,原因是该地址是附件的原始链接,未携带Trello认证信息,私有看板的附件还需要通过API授权端点访问。以下是修正方案:
修正后的完整代码
from trello import TrelloClient import requests # 替换为你的实际密钥和令牌 personal_token = '你的API Key' account_token = '用户访问令牌' # 初始化客户端时,token参数传用户令牌,api_secret留空(若用的是用户令牌而非应用密钥) client = TrelloClient(api_key=personal_token, token=account_token) board = client.get_board('你的看板ID') cards = board.all_cards() for card in cards: for attachment in card.get_attachments(): # 使用Trello官方下载API,携带认证参数 download_api_url = f"https://api.trello.com/1/cards/{card.id}/attachments/{attachment.id}/download?key={personal_token}&token={account_token}" response = requests.get(download_api_url) if response.status_code == 200: with open(attachment.name, 'wb') as file: file.write(response.content) print(f"已下载:{attachment.name}") else: print(f"下载失败[{response.status_code}]:{response.text}") # 移除原代码中的break,才能遍历所有卡片及附件
核心注意事项
- 必须使用Trello API的
/1/cards/{cardId}/attachments/{attachmentId}/download端点下载,而非直接访问attachment.url。 - 确认
account_token是用户访问令牌(创建时需勾选看板读写权限),而非应用密钥。 - 检查API Key和令牌的有效性,以及是否有权限访问目标看板。
内容的提问来源于stack exchange,提问作者Simon O'Doherty
相关产品推荐
相关产品推荐

