【问题标题】:Smartsheet download attachment via Python通过 Python 下载 Smartsheet 附件
【发布时间】:2021-06-14 20:42:44
【问题描述】:

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

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

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

【问题讨论】:

    标签: python api smartsheet-api


    【解决方案1】:

    看起来那个库还没有实现处理附件的逻辑。

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

    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

    【讨论】:

    • 你知道如何将附件下载为文件吗?
    【解决方案2】:

    您可以使用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)
    

    【讨论】:

      【解决方案3】:

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

      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
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-20
        • 2021-03-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多