11

I have currently the upload portion of my code working, how would I go about converting this into a program that will download the respective files from the box folder?

This is the upload program:

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

This is the sample curl request that the Box API documentation gives for downloading files.

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

Part two of this question: Is there a way to alter this program (and the download program) to process all of the files within a folder no matter what the name of the file is?

I am new to programming, so please forgive my lack of skills/knowledge in this area.

Steve-O
  • 387
  • 1
  • 4
  • 10

4 Answers4

7

Assume you are getting your authorization correct you can download file by adding few lines to code to your Existing code. This will copy data from box file to local file here name is FileFromBox.xlx

with open('FileFromBox.xls', 'wb') as open_file:
    client.file('FileId_of_box_file').download_to(open_file)
    open_file.close()
Rohit
  • 624
  • 6
  • 18
  • thank you. `FileFromBox.xls` is really the local name of the file (destination). The actual remote name might be available from the attachment name (content-disposition) field in the response headers? A good practice is also to first download to a temporary name, and move/rename to the final location once the download is completed successfully. You might want to look at [downloading with `requests`](https://stackoverflow.com/questions/16694907/how-to-download-large-file-in-python-with-requests-py) if you don't want to use the Box client (since the uploader doesn't). – init_js Mar 16 '18 at 08:25
  • For those wanting to read the documentation on `download_to` it can be found here: http://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html?highlight=download_to#boxsdk.object.file.File.download_to – tommy.carstensen Apr 06 '18 at 12:48
  • 1
    You can remove the "open_file.close()". The "with" statement in Python (context manager) actually closes the file for you (even if an exception occurs in the with block). – Ismael EL ATIFI Jun 07 '18 at 13:33
  • @Rohit , In documentation they have given `Parameters: writeable_stream (file)` how do I define that parameter , as I am getting error `Nonetype object has no attribute readline` – Piyush S. Wanare Jun 12 '18 at 09:48
  • @PiyushS.Wanare Open any file like test.xls and then you can copy the content from Box file to this test.xls . In above code u can see this parameter is created with name FileFromBox.xls and content of box file is written to this file using download_to. Hope it helps you – Rohit Jun 14 '18 at 04:37
  • Actually it's printing whole file in console, but not writing any data in file i have given filename with whole path where file need to be created , file is getting created but it's empty file. – Piyush S. Wanare Jun 14 '18 at 05:44
  • I assume you are running commands directly not using Python BoxSDk. Please try using box sdk – Rohit Jun 19 '18 at 05:59
  • @Rohit, I have written same code which is working fine after upgrading all `pip` modules , now it's running without any error but `FileFromBox.csv` is an empty file not writing any data to file. – Piyush S. Wanare Jun 21 '18 at 05:23
7

I know this was asked long back, but still I believe many people are searching for the way to do it.

Please check Box SDK for more details.

And I'm using OAuth2.0 - Custom App. You can create the credentials from the developer console.

Here's the code.

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()

Hope this will help you. Thanks to the Python boxsdk 2.0.0 Doc.

  • How do you get the values for those three variables? client id, client secret, access token? Do I ask the authentication provider administrator or is this within Box itself? – JustBeingHelpful Jul 19 '21 at 11:41
  • Hi Mac, Sorry for the delay. You can go ahead and get it through the developer console, if you're using the org account probably should get access to your developer console. (https://app.box.com/developers/console) – Parvathirajan Natarajan Jul 22 '21 at 17:28
5

I would suggest you looking at Box SDK

As you can see in their docs, after authenticating with your client you only need to run the following line:

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

There is more information in Box SDK Docs. If this does not satisfy your necessities because you want to create your own Box SDK, then please wait for another person to give an specific response to your problem. Thanks.

Aitor Martin
  • 724
  • 1
  • 11
  • 26
-1

You can download a file & folders into a zip like below:

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']))
Debo Akeredolu
  • 140
  • 1
  • 8