python-3.x 从Trello卡下载附件

rur96b6h  于 2023-11-20  发布在  Python
关注(0)|答案(1)|浏览(120)

我试图下载所有的附件从我的卡上Trello板使用py-trello
下面是示例代码(删除了私有信息):

from trello import TrelloClient
import requests

personal_token = ''
account_token = ''

client = TrelloClient(api_key=personal_token, api_secret=account_token)

board = client.get_board('')

cards = board.all_cards()
for card in cards:
    for attachment in card.get_attachments():
        response = requests.get(attachment.url)

        if response.status_code == 200:
               with open(attachment.name, 'wb') as file:
                   file.write(response.content)
        else:
            print(response.status_code, response.text)
    
        break
    break

字符串
问题是,当我尝试使用requests获取URL时,我得到了401 Unauthorised错误。我已经尝试添加基本的身份验证如下:

basic = HTTPBasicAuth(personal_token, account_token)


同样的问题。我也试着像这样将它添加到URL:

url = f'{url}?key={personal_token}&token={account_token}'


我看了一下py-trello的代码,但是我不能很容易地看到它是否有下载附件的功能。

x0fgdtte

x0fgdtte1#

问题是令牌必须在头部中发送。文件名也必须从URL中获取。
下面是更新后的代码:

from trello import TrelloClient
import requests

personal_token = ''
account_token = ''

client = TrelloClient(api_key=personal_token, api_secret=account_token)

board = client.get_board('')

headers = {
    "Authorization": f'OAuth oauth_consumer_key="{personal_token}", oauth_token="{account_token}"'
}

cards = board.all_cards()
for card in cards:
    for attachment in card.get_attachments():
        response = requests.get(attachment.url)
        file_name = attachment.url.split('/')[-1]

        if response.status_code == 200:
               with open(file_name, 'wb') as file:
                   file.write(response.content)
        else:
            print(response.status_code, response.text)
    
        break
    break

字符串

相关问题