本文整理汇总了Python中dropbox.Dropbox.files_delete方法的典型用法代码示例。如果您正苦于以下问题:Python Dropbox.files_delete方法的具体用法?Python Dropbox.files_delete怎么用?Python Dropbox.files_delete使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类dropbox.Dropbox
的用法示例。
在下文中一共展示了Dropbox.files_delete方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DropboxHelper
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_delete [as 别名]
class DropboxHelper(object):
def __init__(self, access_token):
self.dropbox = Dropbox(oauth2_access_token=access_token)
def upload(self, filename, file_path):
with open(file_path, 'rb') as f:
try:
self.dropbox.files_upload(f.read(), '/' + filename)
except Exception:
os.remove(file_path)
raise CommandError('Unable to upload file to Dropbox. Maybe access token is invalid.')
def delete_all_files(self):
for i in self.dropbox.files_list_folder('').entries:
self.dropbox.files_delete(i.path_lower)
def download_last_backup(self, dir_path):
entries = self.dropbox.files_list_folder('').entries
if len(entries) == 0:
raise CommandError('We could not find any backup.')
entry = entries[-1]
full_path = dir_path + entry.path_lower
self.dropbox.files_download_to_file(full_path, entry.path_lower)
return full_path, entry.content_hash
示例2: TestDropbox
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_delete [as 别名]
class TestDropbox(unittest.TestCase):
def setUp(self):
self.dbx = Dropbox(oauth2_token)
def test_bad_auth(self):
# Test malformed token
malformed_token_dbx = Dropbox(MALFORMED_TOKEN)
with self.assertRaises(BadInputError) as cm:
malformed_token_dbx.files_list_folder('')
self.assertIn('token is malformed', cm.exception.message)
# Test reasonable-looking invalid token
invalid_token_dbx = Dropbox(INVALID_TOKEN)
with self.assertRaises(AuthError) as cm:
invalid_token_dbx.files_list_folder('')
self.assertEqual(cm.exception.error['error']['.tag'],
'invalid_access_token')
def test_rpc(self):
self.dbx.files_list_folder('')
# Test API error
random_folder_path = '/' + \
''.join(random.sample(string.ascii_letters, 15))
with self.assertRaises(ApiError) as cm:
self.dbx.files_list_folder(random_folder_path)
self.assertIsInstance(cm.exception.error, ListFolderError)
def test_upload_download(self):
# Upload file
timestamp = str(datetime.datetime.utcnow())
random_filename = ''.join(random.sample(string.ascii_letters, 15))
random_path = '/Test/%s/%s' % (timestamp, random_filename)
test_contents = string.ascii_letters
self.dbx.files_upload(test_contents, random_path)
# Download file
metadata, resp = self.dbx.files_download(random_path)
self.assertEqual(string.ascii_letters, resp.text)
# Cleanup folder
self.dbx.files_delete('/Test/%s' % timestamp)
@require_team_token
def test_team(self, token):
dbxt = DropboxTeam(token)
dbxt.team_groups_list()
r = dbxt.team_members_list()
if r.members:
# Only test assuming a member if there is a member
dbxt.as_user(r.members[0].profile.team_member_id).files_list_folder('')
示例3: delete
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_delete [as 别名]
def delete():
if access_token:
dbx = Dropbox(access_token)
path_lower = request.json["path_lower"]
loop = 0
result = False
while not result and loop <= 9:
try:
metadata = dbx.files_delete(path_lower)
result = True
except ApiError:
pass
loop += 1
if not result:
return redirect(url_for("files", _external=True, _scheme="https"))
return json.dumps({"success": True}), 200, {"ContentType": "application/json"}
else:
return redirect(url_for("oauth2_start", _external=True, _scheme="https"))
示例4: DPBXBackend
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_delete [as 别名]
#.........这里部分代码省略.........
f.close()
@command()
def _get(self, remote_filename, local_path):
remote_dir = urllib.unquote(self.parsed_url.path.lstrip('/'))
remote_path = '/' + os.path.join(remote_dir, remote_filename).rstrip()
log.Debug('dpbx,files_download(%s)' % remote_path)
res_metadata, http_fd = self.api_client.files_download(remote_path)
log.Debug('dpbx,files_download(%s): %s, %s' % (remote_path, res_metadata, http_fd))
file_size = res_metadata.size
to_fd = None
progress.report_transfer(0, file_size)
try:
to_fd = local_path.open('wb')
for c in http_fd.iter_content(DPBX_DOWNLOAD_BUF_SIZE):
to_fd.write(c)
progress.report_transfer(to_fd.tell(), file_size)
finally:
if to_fd:
to_fd.close()
http_fd.close()
# It's different from _query() check because we're not querying metadata again.
# Since this check is free, it's better to have it here
local_size = os.path.getsize(local_path.name)
if local_size != file_size:
raise BackendException("dpbx: wrong file size: %d (expected: %d)" % (local_size, file_size))
local_path.setdata()
@command()
def _list(self):
# Do a long listing to avoid connection reset
remote_dir = '/' + urllib.unquote(self.parsed_url.path.lstrip('/')).rstrip()
log.Debug('dpbx.files_list_folder(%s)' % remote_dir)
resp = self.api_client.files_list_folder(remote_dir)
log.Debug('dpbx.list(%s): %s' % (remote_dir, resp))
res = []
while True:
res.extend([entry.name for entry in resp.entries])
if not resp.has_more:
break
resp = self.api_client.files_list_folder_continue(resp.cursor)
# Warn users of old version dpbx about automatically renamed files
self.check_renamed_files(res)
return res
@command()
def _delete(self, filename):
remote_dir = urllib.unquote(self.parsed_url.path.lstrip('/'))
remote_path = '/' + os.path.join(remote_dir, filename).rstrip()
log.Debug('dpbx.files_delete(%s)' % remote_path)
self.api_client.files_delete(remote_path)
# files_permanently_delete seems to be better for backup purpose
# but it's only available for Business accounts
# self.api_client.files_permanently_delete(remote_path)
@command()
def _close(self):
"""close backend session? no! just "flush" the data"""
log.Debug('dpbx.close():')
@command()
def _query(self, filename):
remote_dir = urllib.unquote(self.parsed_url.path.lstrip('/'))
remote_path = '/' + os.path.join(remote_dir, filename).rstrip()
log.Debug('dpbx.files_get_metadata(%s)' % remote_path)
info = self.api_client.files_get_metadata(remote_path)
log.Debug('dpbx.files_get_metadata(%s): %s' % (remote_path, info))
return {'size': info.size}
def check_renamed_files(self, file_list):
bad_list = [x for x in file_list if DPBX_AUTORENAMED_FILE_RE.search(x) is not None]
if len(bad_list) == 0:
return
log.Warn('-' * 72)
log.Warn('Warning! It looks like there are automatically renamed files on backend')
log.Warn('They were probably created when using older version of duplicity.')
log.Warn('')
log.Warn('Please check your backup consistency. Most likely you will need to choose')
log.Warn('largest file from duplicity-* (number).gpg and remove brackets from its name.')
log.Warn('')
log.Warn('These files are not managed by duplicity at all and will not be')
log.Warn('removed/rotated automatically.')
log.Warn('')
log.Warn('Affected files:')
for x in bad_list:
log.Warn('\t%s' % x)
log.Warn('')
log.Warn('In any case it\'s better to create full backup.')
log.Warn('-' * 72)
示例5: dropboxClient
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_delete [as 别名]
#.........这里部分代码省略.........
# return results list
if len(results_list) == max_results:
return results_list
return results_list
def delete(self, record_key):
''' a method to delete a file
:param record_key: string with name of file
:return: string reporting outcome
'''
title = '%s.delete' % self.__class__.__name__
# validate inputs
input_fields = {
'record_key': record_key
}
for key, value in input_fields.items():
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
# validate existence of file
if not self.exists(record_key):
exit_msg = '%s does not exist.' % record_key
return exit_msg
# remove file
current_dir = os.path.split(record_key)[0]
try:
file_path = '/%s' % record_key
self.dropbox.files_delete(file_path)
except:
raise DropboxConnectionError(title)
# remove empty directories in path to file
try:
while current_dir:
folder_path = '/%s' % current_dir
response = self.dropbox.files_list_folder(folder_path)
if not response.entries:
self.dropbox.files_delete(folder_path)
current_dir = os.path.split(current_dir)[0]
else:
break
except:
raise DropboxConnectionError(title)
exit_msg = '%s has been deleted.' % record_key
return exit_msg
def remove(self):
'''
a method to remove all records in the collection
NOTE: this method removes all the files in the collection, but the
collection folder itself created by oauth2 cannot be removed.
only the user can remove the app folder
:return: string with confirmation of deletion
'''
title = '%s.remove' % self.__class__.__name__
示例6: DropboxStorage
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_delete [as 别名]
class DropboxStorage(Storage):
"""
A storage class providing access to resources in a Dropbox Public folder.
"""
def __init__(self, location='/Public'):
self.client = Dropbox(ACCESS_TOKEN)
self.account_info = self.client.users_get_current_account()
self.location = location
self.base_url = 'https://dl.dropboxusercontent.com/'
def _get_abs_path(self, name):
return os.path.realpath(os.path.join(self.location, name))
def _open(self, name, mode='rb'):
name = self._get_abs_path(name)
remote_file = DropboxFile(name, self, mode=mode)
return remote_file
def _save(self, name, content):
name = self._get_abs_path(name)
directory = os.path.dirname(name)
if not self.exists(directory) and directory:
self.client.files_create_folder(directory)
# response = self.client.files_get_metadata(directory)
# if not response['is_dir']:
# raise IOError("%s exists and is not a directory." % directory)
abs_name = os.path.realpath(os.path.join(self.location, name))
foo = self.client.files_upload(content.read(), abs_name)
return name
def delete(self, name):
name = self._get_abs_path(name)
self.client.files_delete(name)
def exists(self, name):
name = self._get_abs_path(name)
try:
self.client.files_get_metadata(name)
except ApiError as e:
if e.error.is_path() and e.error.get_path().is_not_found(): # not found
return False
raise e
return True
def listdir(self, path):
path = self._get_abs_path(path)
response = self.client.files_list_folder(path)
directories = []
files = []
for entry in response.entries:
if type(entry) == FolderMetadata:
directories.append(os.path.basename(entry.path_display))
elif type(entry) == FileMetadata:
files.append(os.path.basename(entry.path_display))
return directories, files
def size(self, name):
cache_key = 'django-dropbox-size:{}'.format(filepath_to_uri(name))
size = cache.get(cache_key)
if not size:
size = self.client.files_get_metadata(name).size
cache.set(cache_key, size, CACHE_TIMEOUT)
return size
def url(self, name):
if name.startswith(self.location):
name = name[len(self.location) + 1:]
name = os.path.basename(self.location) + "/" + name
if self.base_url is None:
raise ValueError("This file is not accessible via a URL.")
myurl = urlparse.urljoin(self.base_url, filepath_to_uri(name))
if "static" not in self.location:
# Use a dynamic URL for "non-static" files.
try:
new_name = os.path.dirname(self.location) + "/" + name
fp = filepath_to_uri(new_name)
cache_key = 'django-dropbox-size:{}'.format(fp)
myurl = cache.get(cache_key)
if not myurl:
try:
shared_link = self.client.sharing_create_shared_link(fp)
myurl = shared_link.url + '&raw=1'
logger.debug("shared link: {0}, myurl: {1}".format(shared_link, myurl))
except Exception,e:
logger.exception(e)
if myurl is None:
temp_link = self.client.files_get_temporary_link(fp)
myurl = temp_link.link
logger.debug("temp link: {0}, myurl: {1}".format(temp_link, myurl))
cache.set(cache_key, myurl, SHARE_LINK_CACHE_TIMEOUT)
except Exception,e:
logger.exception(e)
return myurl
#.........这里部分代码省略.........
示例7: DropBoxStorage
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_delete [as 别名]
class DropBoxStorage(Storage):
"""DropBox Storage class for Django pluggable storage system."""
def __init__(self, oauth2_access_token=None, root_path=None):
oauth2_access_token = oauth2_access_token or setting('DROPBOX_OAUTH2_TOKEN')
self.root_path = root_path or setting('DROPBOX_ROOT_PATH', '/')
if oauth2_access_token is None:
raise ImproperlyConfigured("You must configure a token auth at"
"'settings.DROPBOX_OAUTH2_TOKEN'.")
self.client = Dropbox(oauth2_access_token)
def _full_path(self, name):
if name == '/':
name = ''
return safe_join(self.root_path, name).replace('\\', '/')
def delete(self, name):
self.client.files_delete(self._full_path(name))
def exists(self, name):
try:
return bool(self.client.files_get_metadata(self._full_path(name)))
except ApiError:
return False
def listdir(self, path):
directories, files = [], []
full_path = self._full_path(path)
metadata = self.client.files_get_metadata(full_path)
for entry in metadata['contents']:
entry['path'] = entry['path'].replace(full_path, '', 1)
entry['path'] = entry['path'].replace('/', '', 1)
if entry['is_dir']:
directories.append(entry['path'])
else:
files.append(entry['path'])
return directories, files
def size(self, name):
metadata = self.client.files_get_metadata(self._full_path(name))
return metadata['bytes']
def modified_time(self, name):
metadata = self.client.files_get_metadata(self._full_path(name))
mod_time = datetime.strptime(metadata['modified'], DATE_FORMAT)
return mod_time
def accessed_time(self, name):
metadata = self.client.files_get_metadata(self._full_path(name))
acc_time = datetime.strptime(metadata['client_mtime'], DATE_FORMAT)
return acc_time
def url(self, name):
media = self.client.files_get_temporary_link(self._full_path(name))
return media.link
def _open(self, name, mode='rb'):
remote_file = DropBoxFile(self._full_path(name), self)
return remote_file
def _save(self, name, content):
self.client.files_upload(content, self._full_path(name))
return name