当前位置: 首页>>代码示例>>Python>>正文


Python dropbox.Dropbox方法代码示例

本文整理汇总了Python中dropbox.Dropbox方法的典型用法代码示例。如果您正苦于以下问题:Python dropbox.Dropbox方法的具体用法?Python dropbox.Dropbox怎么用?Python dropbox.Dropbox使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在dropbox的用法示例。


在下文中一共展示了dropbox.Dropbox方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import dropbox [as 别名]
# 或者: from dropbox import Dropbox [as 别名]
def __init__(self, id, params):
		super(Dropbox_Dropper, self).__init__(id, params)
		try:
			self.access_token = params["access_token"]
		except KeyError as k: # if config parameters are missing
			logging.error("Dropxbox: Error while trying to initialize notifier, it seems there is a config parameter missing: %s" % k)
			self.corrupted = True
			return

		try:
			self.dbx = dropbox.Dropbox(self.access_token)
		except Exception as e:
			logging.error("Dropbox: Error while connecting to Dropbox service: %s" % e)
			self.corrupted = True
			return

		self.data_dir = "/var/tmp/secpi/alarms/" #change this maybe?

		logging.info("Dropbox initialized") 
开发者ID:SecPi,项目名称:SecPi,代码行数:21,代码来源:dropbox_dropper.py

示例2: notify

# 需要导入模块: import dropbox [as 别名]
# 或者: from dropbox import Dropbox [as 别名]
def notify(self, info):
		if not self.corrupted:
			#info_str = "Recieved alarm on sensor %s from worker %s: %s"%(info['sensor'], info['worker'], info['message'])
			latest_subdir = self.get_latest_subdir()

			dropbox_dir = "/%s" % latest_subdir.split("/")[-1] #pfui
			#self.dbx.files_create_folder(dropbox_dir) # shouldn't be necessary, automatically created 
			for file in os.listdir(latest_subdir):
				if os.path.isfile("%s/%s" % (latest_subdir, file)):
					f = open("%s/%s" % (latest_subdir, file), "rb")
					data = f.read()
					try:
						logging.info("Dropbox: Trying to upload file %s to %s" % (file, dropbox_dir))
						res = self.dbx.files_upload(data, "%s/%s" % (dropbox_dir, file))
						logging.info("Dropbox: Upload of file %s succeeded" % file)
					except dropbox.exceptions.ApiError as d:
						logging.error("Dropbox: API error: %s" % d)
					except Exception as e: # currently this catches wrong authorization, we should change this
						logging.error("Dropbox: Wasn't able to upload file: %s" % e)
					f.close()
		else:
			logging.error("Dropbox: Wasn't able to notify because there was an initialization error") 
开发者ID:SecPi,项目名称:SecPi,代码行数:24,代码来源:dropbox_dropper.py

示例3: command_dropbox_connect

# 需要导入模块: import dropbox [as 别名]
# 或者: from dropbox import Dropbox [as 别名]
def command_dropbox_connect(args):
    import dropbox

    if args.spellbook_name is not None:
        print('ERR: sync is only for all books')
        return

    app_key = 'ow3gosk8pb9bhkr'
    app_secret = 'w3eqoqx5scb64pd'
    flow = dropbox.DropboxOAuth2FlowNoRedirect(app_key, app_secret)
    # Have the user sign in and authorize this token
    authorize_url = flow.start()
    print('1. Go to: ' + authorize_url)
    print('2. Click "Allow" (you might have to log in first)')
    print('3. Copy the authorization code.')
    code = collect_str("the authorization code here")

    # This will fail if the user enters an invalid authorization code
    access_token, user_id = flow.finish(code)

    client = dropbox.Dropbox(access_token)
    print('successfully linked account: ', client.users_get_current_account().name.display_name)
    with open(DROPBOX_TOKEN_PATH, 'w') as fout:
        fout.write(access_token) 
开发者ID:donpiekarz,项目名称:spellbook,代码行数:26,代码来源:application.py

示例4: db_sync

# 需要导入模块: import dropbox [as 别名]
# 或者: from dropbox import Dropbox [as 别名]
def db_sync():
    import dropbox
    dbx = dropbox.Dropbox(db_load_token())
    repo = db_repo_load()
    for book in dbx.files_list_folder('').entries:
        if book.name not in repo:
            db_download(dbx, book.name)
        elif repo[book.name] != book.rev:
            db_merge(dbx, book.name, book.rev)
            db_update(dbx, book.name, book.rev)
            repo.pop(book.name)
        elif repo[book.name] == book.rev:
            # TODO: prevent uploading unchanged files
            db_update(dbx, book.name, book.rev)
            repo.pop(book.name)
        else:
            print('dead end: %s' % book.name)

    for spellbook_name in repo:
        if repo[spellbook_name] is None:
            db_upload(dbx, spellbook_name)

    for spellbook_name in db_repo_removed_list():
        db_remove(dbx, spellbook_name) 
开发者ID:donpiekarz,项目名称:spellbook,代码行数:26,代码来源:application.py

示例5: _get_metadata

# 需要导入模块: import dropbox [as 别名]
# 或者: from dropbox import Dropbox [as 别名]
def _get_metadata(self, image_file=None, dbx_metadata=None):
        """this is a wrapper around the main client.get_metadata to first parse
           a Dropbox FileMetadata into a dicionary, then pass it on to the 
           primary get_metadata function.

           Parameters
           ==========
           image_file: the full path to the image file that had metadata
                       extracted
           metadata: the Dropbox FileMetadata to parse.

        """
        metadata = dict()

        if dbx_metadata is not None:
            for key in dbx_metadata.__dir__():
                value = getattr(dbx_metadata, key)
                if isinstance(value, (str, datetime.datetime, bool, int, float)):
                    metadata[key.strip("_")] = value

        return self.get_metadata(image_file, names=metadata) 
开发者ID:singularityhub,项目名称:sregistry-cli,代码行数:23,代码来源:__init__.py

示例6: _update_secrets

# 需要导入模块: import dropbox [as 别名]
# 或者: from dropbox import Dropbox [as 别名]
def _update_secrets(self):
        """update secrets will look for a dropbox token in the environment at
           SREGISTRY_DROPBOX_TOKEN and if found, create a client. If not,
           an error message is returned and the client exits.
        """

        # Retrieve the user token. Exit if not found
        token = self._required_get_and_update("SREGISTRY_DROPBOX_TOKEN")

        # Create the dropbox client
        self.dbx = Dropbox(token)

        # Verify that the account is valid
        try:
            self.account = self.dbx.users_get_current_account()
        except:
            bot.exit("Account invalid. Exiting.") 
开发者ID:singularityhub,项目名称:sregistry-cli,代码行数:19,代码来源:__init__.py

示例7: get_dropbox_client

# 需要导入模块: import dropbox [as 别名]
# 或者: from dropbox import Dropbox [as 别名]
def get_dropbox_client(username, setup=True, stdin=None, stdout=None):
    """
	checks wether a dropbox.dropbox.Dropbox is available for username.
	If it is, it is returned.
	Otherwise, if setup is True, a command-line setup is shown.
	The setup uses stdin and stout, both defaulting to the sys.std*.
	If no client was found and setup is False, None will be returned.
	"""
    if stdout is None:
        stdout = sys.stdout
    if stdin is None:
        stdin = sys.stdin
    data = load_dropbox_data(username)
    if data is None:
        stdout.write("\n")
        if not setup:
            return None
        dropbox_setup(username, stdin, stdout)
        data = load_dropbox_data(username)
    token = data["access_token"]
    dbclient = dropbox.dropbox.Dropbox(token)
    return dbclient 
开发者ID:ywangd,项目名称:stash,代码行数:24,代码来源:dbutils.py

示例8: copy

# 需要导入模块: import dropbox [as 别名]
# 或者: from dropbox import Dropbox [as 别名]
def copy(self, from_path: str, to_path: str, allow_shared_folder=True, autorename=False,
             allow_ownership_transfer=False):
        """
        Copy a file or folder to a different location in the user's Dropbox. If the source path is a folder all
        its contents will be copied.

        :param from_path: Source path
        :param to_path: Destination path
        :param bool allow_shared_folder: If true, :meth:`files_copy` will copy
            contents in shared folder, otherwise
            ``RelocationError.cant_copy_shared_folder`` will be returned if
            ``from_path`` contains shared folder. This field is always true for
            :meth:`files_move`.
        :param bool autorename: If there's a conflict, have the Dropbox server
            try to autorename the file to avoid the conflict.
        :param bool allow_ownership_transfer: Allow moves by owner even if it
            would result in an ownership transfer for the content being moved.
            This does not apply to copies.
        """

        dbx = self._get_instance()
        dbx.files_copy_v2(from_path, to_path, allow_shared_folder=allow_shared_folder,
                          autorename=autorename, allow_ownership_transfer=allow_ownership_transfer) 
开发者ID:BlackLight,项目名称:platypush,代码行数:25,代码来源:dropbox.py

示例9: move

# 需要导入模块: import dropbox [as 别名]
# 或者: from dropbox import Dropbox [as 别名]
def move(self, from_path: str, to_path: str, allow_shared_folder=True, autorename=False,
             allow_ownership_transfer=False):
        """
        Move a file or folder to a different location in the user's Dropbox. If the source path is a folder all its
        contents will be moved.

        :param from_path: Source path
        :param to_path: Destination path
        :param bool allow_shared_folder: If true, :meth:`files_copy` will copy
            contents in shared folder, otherwise
            ``RelocationError.cant_copy_shared_folder`` will be returned if
            ``from_path`` contains shared folder. This field is always true for
            :meth:`files_move`.
        :param bool autorename: If there's a conflict, have the Dropbox server
            try to autorename the file to avoid the conflict.
        :param bool allow_ownership_transfer: Allow moves by owner even if it
            would result in an ownership transfer for the content being moved.
            This does not apply to copies.
        """

        dbx = self._get_instance()
        dbx.files_move_v2(from_path, to_path, allow_shared_folder=allow_shared_folder,
                          autorename=autorename, allow_ownership_transfer=allow_ownership_transfer) 
开发者ID:BlackLight,项目名称:platypush,代码行数:25,代码来源:dropbox.py

示例10: backup

# 需要导入模块: import dropbox [as 别名]
# 或者: from dropbox import Dropbox [as 别名]
def backup():
    with open(LOCALFILE, 'rb') as f:
        # We use WriteMode=overwrite to make sure that the settings in the file
        # are changed on upload
        print("Uploading " + LOCALFILE + " to Dropbox as " + BACKUPPATH + "...")
        try:
            dbx.files_upload(f.read(), BACKUPPATH, mode=WriteMode('overwrite'))
        except ApiError as err:
            # This checks for the specific error where a user doesn't have
            # enough Dropbox space quota to upload this file
            if (err.error.is_path() and
                    err.error.get_path().reason.is_insufficient_space()):
                sys.exit("ERROR: Cannot back up; insufficient space.")
            elif err.user_message_text:
                print(err.user_message_text)
                sys.exit()
            else:
                print(err)
                sys.exit()

# Change the text string in LOCALFILE to be new_content
# @param new_content is a string 
开发者ID:dropbox,项目名称:dropbox-sdk-python,代码行数:24,代码来源:backup-and-restore-example.py

示例11: dbxStruct

# 需要导入模块: import dropbox [as 别名]
# 或者: from dropbox import Dropbox [as 别名]
def dbxStruct(self, obj):
    structname = obj.__class__.__name__
    data = {}

    for key in dir(obj):
      if not key.startswith('_'):
        if isinstance(getattr(obj, key), list):
          tmpdata = []
          for item in getattr(obj, key):
            tmpdata.append(self.dbxStruct(item))
          data.update({key: tmpdata})
        else:
          data.update({key: getattr(obj, key)})

    if structname == 'FolderMetadata':
      data.update({'.tag': 'folder'})
    if structname == 'FileMetadata':
      data.update({'.tag': 'file'})

    return data

  # Get Dropbox metadata of path. 
开发者ID:realriot,项目名称:ff4d,代码行数:24,代码来源:ff4d.py

示例12: release

# 需要导入模块: import dropbox [as 别名]
# 或者: from dropbox import Dropbox [as 别名]
def release(self, path, fh):
    path = path.encode('utf-8')
    if debug == True: appLog('debug', 'Called: release() - Path: ' + path + ' FH: ' + str(fh))

    # Check to finish Dropbox upload.
    if type(self.openfh[fh]['f']) is dict and 'upload_id' in self.openfh[fh]['f'] and self.openfh[fh]['f']['upload_id'] != "":
      # Flush still existing data in buffer.
      if self.openfh[fh]['f']['buf'] != "":
        if debug == True: appLog('debug', 'Flushing write buffer to Dropbox')
        result = self.dbxChunkedUpload(self.openfh[fh]['f']['buf'], self.openfh[fh]['f']['upload_id'], self.openfh[fh]['f']['offset'])
      if debug == True: appLog('debug', 'Finishing upload to Dropbox')
      result = self.dbxCommitChunkedUpload(path, self.openfh[fh]['f']['upload_id'], self.openfh[fh]['f']['offset'])

    # Remove outdated data from cache if handle was opened for writing.
    if self.openfh[fh]['mode'] == 'w':
      self.removeFromCache(os.path.dirname(path))

    self.releaseFH(fh)
    if debug == True: appLog('debug', 'Released filehandle: ' + str(fh))

    return 0

  # Truncate a file to overwrite it. 
开发者ID:realriot,项目名称:ff4d,代码行数:25,代码来源:ff4d.py

示例13: readdir

# 需要导入模块: import dropbox [as 别名]
# 或者: from dropbox import Dropbox [as 别名]
def readdir(self, path, fh):
    path = path.encode('utf-8')
    if debug == True: appLog('debug', 'Called: readdir() - Path: ' + path)

    # Fetch folder informations.
    fusefolder = ['.', '..']
    metadata = self.getDropboxMetadata(path, True)

    # Loop through the Dropbox API reply to build fuse structure.
    for item in metadata['entries']:
      # Append entry to fuse foldercontent.
      folderitem = os.path.basename(item['path'])
      fusefolder.append(folderitem)

    # Loop through the folder content.
    for item in fusefolder:
      yield item

  # Get properties for a directory or file. 
开发者ID:realriot,项目名称:ff4d,代码行数:21,代码来源:ff4d.py

示例14: _get_file

# 需要导入模块: import dropbox [as 别名]
# 或者: from dropbox import Dropbox [as 别名]
def _get_file(self):
        if self._file is None:
            self._file = SpooledTemporaryFile()
            # As dropbox==9.3.0, the client returns a tuple
            # (dropbox.files.FileMetadata, requests.models.Response)
            file_metadata, response = \
                self._storage.client.files_download(self.name)
            if response.status_code == 200:
                with BytesIO(response.content) as file_content:
                    copyfileobj(file_content, self._file)
            else:
                # JIC the exception isn't catched by the dropbox client
                raise DropBoxStorageException(
                    "Dropbox server returned a {} response when accessing {}"
                    .format(response.status_code, self.name)
                )
            self._file.seek(0)
        return self._file 
开发者ID:jschneier,项目名称:django-storages,代码行数:20,代码来源:dropbox.py

示例15: backup_with_overwriting

# 需要导入模块: import dropbox [as 别名]
# 或者: from dropbox import Dropbox [as 别名]
def backup_with_overwriting(dropbox, local_dir_path_obj, target_dropbox_dir):

    print('Backing up contents of local folder: {} to Dropbox folder {} ...\n'.format(
        local_dir_path_obj, target_dropbox_dir))

    print('Data will be overwritten\n')

    # Walk the local folder
    for path_obj in tree(local_dir_path_obj):
        if path_obj.is_file():
            # target paths on Dropbox must start with a "/"
            destination_path = '/' + target_dropbox_dir + '/' + str(path_obj)
            try:
                with path_obj.open('rb') as f:
                    print('UPLOAD: {} --> {}'.format(path_obj, destination_path))
                    dbx.files_upload(f.read(),
                                     destination_path,
                                     mode=dropbox.files.WriteMode.overwrite,
                                     mute=True)
            except Exception as e:
                print('Failed to upload {}, reason: {}\n'.format(path_obj, e))
                continue
    print('\nDone') 
开发者ID:PacktPublishing,项目名称:Python-for-Everyday-Life,代码行数:25,代码来源:backup.py


注:本文中的dropbox.Dropbox方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。