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

2024-05-11 20:13:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这是上传程序:

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

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

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


Tags: 文件theto程序srcboxtokenid
3条回答

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

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

我建议你看看Box SDK

从他们的文档中可以看到,在与客户进行身份验证之后,您只需要运行以下行:

client.file(file_id='SOME_FILE_ID').content()

Box SDK文档中有更多信息。如果这不能满足您的需要,因为您想创建自己的Box SDK,那么请等待其他人对您的问题给出特定的响应。谢谢。

我知道很久以前就有人问过这个问题,但我相信很多人都在寻找解决问题的方法。

请查看Box SDK了解更多详细信息。

我正在使用OAuth2.0自定义应用程序。您可以从developer console创建凭据。

这是密码。

from boxsdk import OAuth2, Client
#from boxsdk import Folder

auth = OAuth2(
    client_id='fbxxxxxxxxxxxxxxxxxxxxxxxxxxxxx9',
    client_secret='bPxxxxxxxxxxxxxxxxxxxxxxxxx4Or',
    access_token='QExxxxxxxxxxxxxxxxxxxxxxxxxxwt',
)
client = Client(auth)

root_folder = client.root_folder().get()

items = root_folder.get_items()
for item in items:
    print('{0} {1} is named "{2}"'.format(item.type.capitalize(), item.id, item.name))
    with open(item.name, 'wb') as open_file:
        client.file(item.id).download_to(open_file)
        open_file.close()

希望这对你有帮助。多亏了Python boxsdk 2.0.0 Doc

相关问题 更多 >