How to use the boxsdk.Client function in boxsdk

To help you get started, we’ve selected a few boxsdk examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github akrherz / pyIEM / src / pyiem / box_utils.py View on Github external
filenames = [filenames]
    if isinstance(remotefilenames, string_types):
        remotefilenames = [remotefilenames]
    if remotefilenames is None:
        remotefilenames = [os.path.basename(f) for f in filenames]
    iemprops = get_properties()
    if "boxclient.access_token" not in iemprops:
        return []
    oauth = OAuth2(
        client_id=iemprops["boxclient.client_id"],
        client_secret=iemprops["boxclient.client_secret"],
        access_token=iemprops["boxclient.access_token"],
        refresh_token=iemprops["boxclient.refresh_token"],
        store_tokens=_store_tokens,
    )
    client = Client(oauth)
    folder_id = 0
    for token in remotepath.split("/"):
        if token.strip() == "":
            continue
        offset = 0
        found = False
        while not found:
            LOG.debug("folder(%s).get_items(offset=%s)", folder_id, offset)
            items = list(
                client.folder(folder_id=folder_id).get_items(
                    limit=100, offset=offset
                )
            )
            for item in items:
                if (
                    item.type == "folder"
github jheld / diycrate / diycrate / file_operations.py View on Github external
def process_event(self, event, operation):
        """
        Wrapper to process the given event on the operation.
        :param event:
        :param operation:
        :return:
        """
        if operation == 'delete':
            crate_logger.debug('Doing a delete on {}'.format(event.pathname))
            folders_to_traverse = self.folders_to_traverse(event.path)
            crate_logger.debug(folders_to_traverse)
            client = Client(self.oauth)
            failed = False
            while not failed:
                try:
                    box_folder = client.folder(folder_id='0').get()
                except Exception:
                    crate_logger.warning("Error getting box root folder.", exc_info=True)
                    time.sleep(2)
                else:
                    failed = True
            cur_box_folder = box_folder
            # if we're modifying in root box dir, then we've already found the folder
            is_base = BOX_DIR in (event.path, event.path[:-1],)
            cur_box_folder = self.traverse_path(client, event, cur_box_folder, folders_to_traverse)
            last_dir = os.path.split(event.path)[-1]
            if not is_base:
                AssertionError(cur_box_folder['name'] == last_dir,
github jheld / diycrate / diycrate / item_queue_io.py View on Github external
if upload_queue.not_empty:
            callable_up = upload_queue.get()  # blocks
            # TODO: pass in the actual item being updated/uploaded, so we can do more intelligent retry mechanisms
            was_list = isinstance(callable_up, list)
            last_modified_time = oauth = None
            if was_list:
                last_modified_time, callable_up, oauth = callable_up
            args = callable_up.args if isinstance(callable_up, partial) else None
            num_retries = 15
            for x in range(15):
                try:
                    ret_val = callable_up()
                    if was_list:
                        item = ret_val  # is the new/updated item
                        if isinstance(item, File):
                            client = Client(oauth)
                            file_obj = client.file(file_id=item.object_id).get()
                            redis_set(r_c, file_obj, last_modified_time, box_dir_path=BOX_DIR)
                    break
                except BoxAPIException as e:
                    crate_logger.debug('{the_args}, {the_trace}'.format(the_args=args,
                                                                        the_trace=traceback.format_exc()))
                    if e.status == 409:
                        crate_logger.debug('Apparently Box says this item already exists...'
                                           'and we were trying to create it. Need to handle this better')
                        break
                except (ConnectionError, BrokenPipeError, ProtocolError, ConnectionResetError):
                    time.sleep(3)
                    crate_logger.debug('{the_args}, {the_trace}'.format(the_args=args,
                                                                        the_trace=traceback.format_exc()))
                    if x >= num_retries - 1:
                        crate_logger.debug('Upload giving up on: {}'.format(callable_up))
github CenterForOpenScience / osf.io / addons / box / models.py View on Github external
def _folder_data(self, folder_id):
        # Split out from set_folder for ease of testing, due to
        # outgoing requests. Should only be called by set_folder
        try:
            Provider(self.external_account).refresh_oauth_key(force=True)
        except InvalidGrantError:
            raise exceptions.InvalidAuthError()
        try:
            oauth = OAuth2(client_id=settings.BOX_KEY, client_secret=settings.BOX_SECRET, access_token=self.external_account.oauth_key)
            client = Client(oauth)
            folder_data = client.folder(self.folder_id).get()
        except BoxAPIException:
            raise exceptions.InvalidFolderError()

        folder_name = folder_data['name'].replace('All Files', '') or '/ (Full Box)'
        folder_path = '/'.join(
            [x['name'] for x in folder_data['path_collection']['entries'] if x['name']] +
            [folder_data['name']]
        ).replace('All Files', '') or '/'

        return folder_name, folder_path
github CenterForOpenScience / osf.io / addons / box / models.py View on Github external
'path': '/',
                'addon': 'box',
                'kind': 'folder',
                'name': '/ (Full Box)',
                'urls': {
                    # 'folders': node.api_url_for('box_folder_list', folderId=0),
                    'folders': api_v2_url('nodes/{}/addons/box/folders/'.format(self.owner._id),
                        params={'id': '0'}
                    )
                }
            }]

        try:
            Provider(self.external_account).refresh_oauth_key()
            oauth = OAuth2(client_id=settings.BOX_KEY, client_secret=settings.BOX_SECRET, access_token=self.external_account.oauth_key)
            client = Client(oauth)
        except BoxAPIException:
            raise HTTPError(http_status.HTTP_403_FORBIDDEN)

        try:
            metadata = client.folder(folder_id).get()
        except BoxAPIException:
            raise HTTPError(http_status.HTTP_404_NOT_FOUND)
        except MaxRetryError:
            raise HTTPError(http_status.HTTP_400_BAD_REQUEST)

        folder_path = '/'.join(
            [
                x['name']
                for x in metadata['path_collection']['entries']
            ] + [metadata['name']]
        )
github CenterForOpenScience / osf.io / addons / box / serializer.py View on Github external
def credentials_are_valid(self, user_settings, client):
        from addons.box.models import Provider as Box  # Avoid circular import
        if self.node_settings.has_auth:
            if Box(self.node_settings.external_account).refresh_oauth_key():
                return True

        if user_settings:
            oauth = OAuth2(client_id=settings.BOX_KEY, client_secret=settings.BOX_SECRET, access_token=user_settings.external_accounts[0].oauth_key)
            client = client or Client(oauth)
            try:
                client.user()
            except (BoxAPIException, IndexError):
                return False
        return True
github with-watson / watson-box-skills-lab-docs / src / storage.py View on Github external
def connect(self, token: str) -> 'Client':
        """Connect to box using a bearer token

            Args:
                token: The bearer token to use for this connection
        """
        if self.config['storage'] == 'box':
            auth = OAuth2(None, None, access_token=token)
            return Client(auth)
        else:
            raise Exception('Invalid Storage Option: ' +
                            self.config['storage'])
github jheld / diycrate / diycrate / application.py View on Github external
def start_cloud_threads(oauth):
    """

    :return:
    """
    client = Client(oauth)
    handler.oauth = oauth
    wm.add_watch(BOX_DIR, mask, rec=False)
    box_folder = client.folder(folder_id='0').get()
    download_thread.daemon = True
    download_thread.start()
    upload_thread.daemon = True
    upload_thread.start()
    # local trash can
    wm.add_watch(trash_directory, mask=in_moved_to | in_moved_from)
    if not long_poll_thread.is_alive():  # start before doing anything else
        long_poll_thread.start()
    # walk_and_notify_and_download_tree(BOX_DIR, box_folder, client)
    walk_thread._args = (BOX_DIR, box_folder, client,)
    walk_thread.start()
github jcleblanc / box-examples / python / representations_single_image / representations_single_image.py View on Github external
app = Flask(__name__)

# Configure JWT auth and fetch access token
auth = JWTAuth(
  client_id=config.client_id,
  client_secret=config.client_secret,
  enterprise_id=config.enterprise_id,
  jwt_key_id=config.jwt_key_id,
  rsa_private_key_file_sys_path=config.private_key_path,
  rsa_private_key_passphrase=config.private_key_passphrase
)

# Obtain client auth
access_token = auth.authenticate_instance()
client = Client(auth)
print access_token

@app.route('/')
def index():
  """Flask route for file download
  
  Search for a user by name and auth as that user. 
  Search for a multi page file by name and capture file ID.
  Make request for representational data for that file.
  Make request to download file page thumbnails
  
  Returns:
     A string containing the message to be displayed to the user
  """
  
  # Fetch user by name and auth app user