Skip to content

Latest commit

 

History

History
498 lines (374 loc) · 20.6 KB

folders.md

File metadata and controls

498 lines (374 loc) · 20.6 KB

Folders

Folder objects represent a folder from a user's account. They can be used to iterate through a folder's contents, collaborate a folder with another user or group, and perform other common folder operations (move, copy, delete, etc.).

Get Information About a Folder

To retrieve information about a folder, first call client.folder(folder_id) to initialize the Folder object. Then, call folder.get(*, fields=None, etag=None, **kwargs) to retrieve data about the folder. This method returns a new `Folder object with fields populated by data from the API, leaving the original object unmodified.

You can pass a list of fields to retrieve from the API in order to filter to just the necessary fields or add ones not returned by default.

folder = client.folder(folder_id='22222').get()
print(f'Folder "{folder.name}" has {folder.item_collection["total_count"]} items in it')

Get the User's Root Folder

To get the current user's root folder, call client.root_folder() to initialize the appropriate Folder object.

root_folder = client.root_folder().get()

Get the Items in a Folder

To retrieve the items in a folder, call folder.get_items(limit=None, offset=0, marker=None, use_marker=False, sort=None, direction=None, fields=None). This method returns a BoxObjectCollection that allows you to iterate over all the Item objects in the collection.

items = client.folder(folder_id='22222').get_items()
for item in items:
    print(f'{item.type.capitalize()} {item.id} is named "{item.name}"')

Update a Folder

To update a folder's information, call folder.update_info(*, data, etag=None, **kwargs) with a dict of properties to update on the folder. This method returns a new updated Folder object, leaving the original object unmodified.

updated_folder = client.folder(folder_id='22222').update_info(data={
    'name': '[ARCHIVED] Planning documents',
    'description': 'Old planning documents',
})
print('Folder updated!')

Create a Folder

A folder can be created by calling folder.create_subfolder(name) on the parent folder with the name of the subfolder to be created. This method returns a new Folder representing the created subfolder.

subfolder = client.folder('0').create_subfolder('My Stuff')
print(f'Created subfolder with ID {subfolder.id}')

Copy a Folder

A folder can be copied into a new parent folder by calling folder.copy(parent_folder, name=None) with the destination folder and an optional new name for the file in case there is a name conflict in the destination folder. This method returns a new Folder object representing the copy of the folder in the destination folder.

folder_id = '22222'
destination_folder_id = '44444'

folder_to_copy = client.folder(folder_id)
destination_folder = client.folder(destination_folder_id)

folder_copy = folder_to_copy.copy(parent_folder=destination_folder)
print(f'Folder "{folder_copy.name}" has been copied into folder "{folder_copy.parent.name}"')

Move a Folder

To move a folder from one parent folder into another, call folder.move(parent_folder, name=None) with the destination folder to move the folder into. You can optionally provide a name parameter to automatically rename the folder in case of a name conflict in the destination folder. This method returns the updated Folder object in the new folder.

folder_id = '11111'
destination_folder_id = '44444'

folder_to_move = client.folder(folder_id)
destination_folder = client.folder(destination_folder_id)

moved_folder = folder_to_move.move(parent_folder=destination_folder)
print(f'Folder "{moved_folder.name}" has been moved into folder "{moved_folder.parent.name}"')

Rename a File

A folder can be renamed by calling folder.rename(name). This method returns the updated Folder object with a new name.

folder = client.folder(folder_id='11111')

renamed_folder = folder.rename("new-name")
print(f'Folder was renamed to "{renamed_folder.name}"')

Delete a Folder

Calling the folder.delete(recursive=True, etag=None) method will delete the folder. Depending on enterprise settings, this will either move the folder to the user's trash or permanently delete the folder. This method returns True to signify that the deletion was successful.

By default, the method will delete the folder and all of its contents; to fail the deletion if the folder is not empty, set the recursive parameter to False.

client.folder(folder_id='22222').delete()

Find a Folder for a Shared Link

To find a folder given a shared link, use the client.get_shared_item method.

folder = client.get_shared_item('https://app.box.com/s/gjasdasjhasd', password='letmein')

Create or update a Shared Link

A shared link for a folder can be generated or updated by calling folder.get_shared_link(access=None, etag=None, unshared_at=None, allow_download=None, allow_preview=None, password=None, vanity_name=None, **kwargs). This method returns a unicode string containing the shared link URL.

folder_id = '11111'

url = client.folder(folder_id).get_shared_link(access='open', allow_download=False)
print(f'The folder shared link URL is: {url}')

Get a Shared Link

To check for an existing shared link on a folder, simply call folder.shared_link

This method returns a unicode string containing the shared link URL.

folder_id = '11111'
shared_link = client.folder(folder_id).get().shared_link
url = shared_link['url']

Remove a Shared Link

A shared link for a folder can be removed by calling folder.remove_shared_link(etag=None, **kwargs).

folder_id = '11111'
client.folder(folder_id).remove_shared_link()

Set Metadata

To set metadata on a folder call the folder.metadata(scope='global', template='properties') to specify the scope and template key of the metadata template to attach. Then, call the [metadata.set(data)][metadata_set] method with the key/value pairs to attach. This method returns a dict containing the applied metadata instance.

Note: This method will unconditionally apply the provided metadata, overwriting the existing metadata for the keys provided. To specifically create or update metadata, see the create() or update() methods.

metadata = {
    'foo': 'bar',
}
applied_metadata = client.folder(folder_id='11111').metadata(scope='enterprise', template='testtemplate').set(metadata)
print(f'Set metadata in instance ID {applied_metadata["$id"]}')

Metadata can be added to a folder either as free-form key/value pairs or from an existing template. To add metadata to a folder, first call folder.metadata(scope='global', template='properties') to specify the scope and template key of the metadata template to attach (or use the default values to attach free-form keys and values). Then, call metadata.create(data) with the key/value pairs to attach. This method can only be used to attach a given metadata template to the folder for the first time, and returns a dict containing the applied metadata instance.

Note: This method will only succeed if the provided metadata template is not currently applied to the folder, otherwise it will fail with a Conflict error.

metadata = {
    'foo': 'bar',
    'baz': 'quux',
}

applied_metadata = client.folder(folder_id='22222').metadata().create(metadata)
print(f'Applied metadata in instance ID {applied_metadata["$id"]}')

Updating metadata values is performed via a series of discrete operations, which are applied atomically against the existing folder metadata. First, specify which metadata will be updated by calling folder.metadata(scope='global', template='properties'). Then, start an update sequence by calling metadata.start_update() and add update operations to the returned MetadataUpdate. Finally, perform the update by calling metadata.update(metadata_update). This final method returns a dict of the updated metadata instance.

Note: This method will only succeed if the provided metadata template has already been applied to the folder; If the folder does not have existing metadata, this method will fail with a Not Found error. This is useful you know the file will already have metadata applied, since it will save an API call compared to set().

folder = client.folder(folder_id='22222')
folder_metadata = folder.metadata(scope='enterprise', template='myMetadata')

updates = folder_metadata.start_update()
updates.add('/foo', 'bar')
updates.update('/baz', 'murp', old_value='quux')  # Ensure the old value was "quux" before updating to "murp"

updated_metadata = folder_metadata.update(updates)
print('Updated metadata on folder!')
print(f'foo is now {updated_metadata["foo"]} and baz is now {updated_metadata["baz"]}')

Get Metadata

To retrieve the metadata instance on a folder for a specific metadata template, first call folder.metadata(scope='global', template='properties') to specify the scope and template key of the metadata template to retrieve, then call metadata.get() to retrieve the metadata values attached to the folder. This method returns a dict containing the applied metadata instance.

metadata = client.folder(folder_id='22222').metadata(scope='enterprise', template='myMetadata').get()
print(f'Got metadata instance {metadata["$id"]}')

Remove Metadata

To remove a metadata instance from a folder, call folder.metadata(scope='global', template='properties') to specify the scope and template key of the metadata template to remove, then call metadata.delete() to remove the metadata from the folder. This method returns True to indicate that the removal succeeded.

client.folder(folder_id='11111').metadata(scope='enterprise', template='myMetadata').delete()

Get All Metadata

To retrieve all metadata attached to a folder, call folder.get_all_metadata(). This method returns a [BoxObjectCollection][box_object_collection] that can be used to iterate over the dicts representing each metadata instance attached to the folder.

folder_metadata = client.folder(folder_id='22222').get_all_metadata()
for instance in folder_metadata:
    if 'foo' in instance:
        print(f'Metadata instance {instance["id"]} has value "{instance["foo"]}" for foo')

Get Metadata For Folder Items

When fetching folder items, you may wish to retrieve metadata for the items simultaneously to avoid needing to make an API call for each item. You can retrieve up to 3 metadata instances per item by passing the special metadata.<scope>.<templateKey> field to folder.get_items(limit=None, offset=0, marker=None, use_marker=False, sort=None, direction=None, fields=None). The metadata is available as a multi-level dict on the returned Item objects.

fields = [
    'type',
    'id',
    'name',
    'metadata.enterprise.vendorContract',
]
items = client.folder(folder_id='22222').get_items(fields=fields)
for item in items:
    if item.metadata:
        metadata = item.metadata['enterprise']['vendorContract']
        print(f'{item.type.capitalize()} {item.id} is a vendor contract with vendor name {metadata["vendorName"]}')

Set a Classification

It is important to note that this feature is available only if you have Governance.

To add classification to a Folder, call folder.set_classification(classification). This method returns the classification type on the Folder object. If a classification already exists then this call will update the existing classification with the new ClassificationType.

from boxsdk.object.item import ClassificationType

classification = client.folder(folder_id='11111').set_classification(ClassificationType.PUBLIC)
print(f'Classification Type is: {classification}')

The set method will always work no matter the state your Folder is in. For cases already where a classification value already exists set_classification(classification) may make multiple API calls.

Alternatively, if you already know you have a classification and you are simple updating it, you can use the update_classification(classification). This will ultimately help you save one extra API call.

classification = client.folder(folder_id='11111').update_classification(ClassificationType.NONE)
print(f'Classification Type is: {classification}')

Retrieve a Classification

To retrieve a classification from a Folder, call folder.get_classification(). This method returns the classification type on the Folder object.

classification = client.folder(folder_id='11111').get_classification()
print(f'Classification Type is: {classification}')

Remove a Classification

To remove a classification from a Folder, call folder.remove_classification().

client.folder(folder_id='11111').remove_classification()

Create a Folder Lock

To lock a folder, call [client.folders(folder_id).create_lock()][create-folder-lock] with the ID of the folder. This prevents the folder from being moved and/or deleted.

lock = client.folders(folder_id).create_lock()
print(f'Created a lock with ID {lock.folder.id}')

Get Folder Locks

To retrieve a list of the locks on a folder, call [`client.folders(folder_id).get_locks()][get-folder-locks] with the ID of the folder. Currently only one lock can exist per folder. Folder locks define access restrictions placed by folder owners to prevent specific folders from being moved or deleted.

locks = client.folders(folder_id).get_locks()
lock = locks.next()
print(f'A lock on a folder with ID {lock.folder.id}')

Delete a Folder Lock

To remove a folder lock, call [client.folder_lock(folder_lock_id).delete()][delete-folder-lock] with the ID of the folder lock.

client.folder_lock(folder_lock_id='22222').delete()