Smartsheet 通过 Python 下载附件

Smartsheet download attachment via Python

我正在使用 simple-smartsheet 库从 Smartsheet 中的 sheet 读取数据,并在 sheet 的每一行下载现有附件.

我已经可以读取每一行的数据,但是我无法下载现有附件。

import config
from simple_smartsheet import Smartsheet

sheet = smartsheet.sheets.get(id=config.SHEET_ID) 
for row in sheet.rows:
    attachments = row.attachments
    print(attachments)
        

当执行上述命令时,我得到的结果是:

[]

simple-smartsheet

我使用 simple-smartsheet 库,因为它是唯一支持 python 版本 3.6+

的库

我的python版本3.7.5

看起来图书馆还没有实现处理附件的逻辑。

作为解决此问题的替代方法,我使用以下代码实现了一个解决方案:

import requests


#token = 'Your smartsheet Token'
#sheetId = 'Your sheet id'

r = requests.get('https://api.smartsheet.com/2.0/sheets/{sheetId}/rows/{rowId}/attachments', headers={'Authorization': f'Bearer {token}'})

response_json = r.json()

print(response_json)

有关处理附件 Smartsheets 的更多详细信息,请参阅 Get Attachments

您可以使用list_row_attachments查找属于某行的附件信息。

代码可能如下所示:

import config
from simple_smartsheet import Smartsheet

sheet = smartsheet.sheets.get(id=config.SHEET_ID) 
for row in sheet.rows:
    response = smartsheet_client.Attachments.list_row_attachments(
        config.SHEET_ID,
        row.id,
        include_all=True
    )
    attachments = response.data
    print(attachments)

我的解决方案不是很 pythonic,但有效,它包含 2 个步骤

  1. 获取附件链接
  2. 将文件保存到本地硬盘(我也在做备份)作为枢纽位置

1.获取附件列表:

    import smartsheet
    import urllib.request    
    smart = smartsheet.Smartsheet()
    att_list = smart.Attachments.list_all_attachments(<sheet_id>, include_all=True)

2.下载附件到本地磁盘,需要循环遍历附件列表,也可以自己加上条件来区分下载:

    for attach in att_list:
        att_id = attach.id  #get the id of the attachment
        att_name = attach.name  # get the name of the attachment
        retrieve_att = smart.Attachments.get_attachment(<sheet id>, att_id)  #downloads the atachment
        dest_dir = "C:\path\to\folder\"
        dest_file = destd+str(att_name)  # parsing the destination path
        dwnld_url = retrieve_att.url # this link gives you access to download the file for about 5 to 10 min. before expire
        urllib.request.urlretrieve(dwnld_url, dest_file) ## retrieving attachement and saving locally

现在你有了文件,你可以用它做任何你想做的事