簡體   English   中英

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

[英]How to download files with 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

這個問題的第二部分:有沒有辦法改變這個程序(和下載程序)來處理文件夾中的所有文件,不管文件的名稱是什么?

我是編程新手,所以請原諒我在這方面缺乏技能/知識。

假設您的授權正確,您可以通過在現有代碼中添加幾行代碼來下載文件。 這會將數據從 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 - 自定義應用程序。 您可以從開發人員控制台創建憑據。

這是代碼。

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

您可以將文件和文件夾下載到 zip 文件中,如下所示:

name = 'test'
file = mock_client.file('466239504569')
folder = mock_client.folder('466239504580')
items = [file, folder]
output_file = open('test.zip', 'wb')
status = client.download_zip(name, items, output_file)
print('The status of the zip download is {0}'.format(status['state']))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM