如何使用 Box API 和 Python 下载文件

新手上路,请多包涵

我目前有我的代码的上传部分工作,我将如何将其转换为一个程序,该程序将从 box 文件夹下载相应的文件?

这是上传程序:

 import requests
import json

#the user acces token
access_token =  'UfUNeHhv4gIxFCn5WEXHgBJwfG8gHT2o'
#the name of the file as you want it to appear in box
dst_filename = 'box_file'
#the actual file path
src_directory = 'C:\Python\cache\\'
#the name of the file to be transferred
src_filename = 'Wildlife.wmv'
#the id of the folder you want to upload to
parent_id = '0'
counter = 1

for counter in range(1, 6):
  src_file = (src_directory + src_filename + '-' + str(counter))
  print(src_file)
  box_filename = (dst_filename + '-' + str(counter))
  headers = { 'Authorization': 'Bearer {0}'.format(access_token)}
  url = 'https://upload.box.com/api/2.0/files/content'
  #open(src_file,'rb') - opens the source file with the buffered reader
  files = { 'filename': (box_filename, open(src_file,'rb')) }
  data = { "parent_id": parent_id }
  response = requests.post(url, data=data, files=files, headers=headers)
  #file_info = response.json()
  #print(file_info)
  print(response)
  print(url, data, files, headers)
  counter = counter + 1

这是 Box API 文档提供的用于下载文件的样本 curl 请求。

 curl -L https://api.box.com/2.0/files/FILE_ID/content \
-H "Authorization: Bearer ACCESS_TOKEN" \
-o FILE_PATH/file_name.txt

这个问题的第二部分:有没有办法改变这个程序(和下载程序)来处理文件夹中的所有文件,而不管文件的名称是什么?

我是编程新手,所以请原谅我在这方面缺乏技能/知识。

原文由 Steve-O 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
1 个回答

假设您获得了正确的授权,您可以通过在现有代码中添加几行代码来下载文件。这会将数据从 box 文件复制到本地文件,这里的名称是 FileFromBox.xlx

 with open('FileFromBox.xls', 'wb') as open_file:
    client.file('FileId_of_box_file').download_to(open_file)
    open_file.close()

原文由 Rohit 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题