本文整理汇总了Python中dropbox.Dropbox.files_upload方法的典型用法代码示例。如果您正苦于以下问题:Python Dropbox.files_upload方法的具体用法?Python Dropbox.files_upload怎么用?Python Dropbox.files_upload使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类dropbox.Dropbox
的用法示例。
在下文中一共展示了Dropbox.files_upload方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DropboxHelper
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_upload [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: dropBox
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_upload [as 别名]
def dropBox (self, FILE, token, account_id):
try:
dbx = Dropbox(token)
head, tails = os.path.split(FILE)
with open(FILE, 'r') as f_in:
mode = WriteMode('overwrite', None) #ADD SOME EXCEPTIONS HERE TO CATCH IF IT DOESNT UPLAD
dbx.files_upload(f_in, '/'+tails, mode=mode)
except Exception as e:
return str(e)
示例3: TestDropbox
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_upload [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('')
示例4: dropboxClient
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_upload [as 别名]
#.........这里部分代码省略.........
return False
# check max size
import sys
record_max = self.fields.metadata['record_max_bytes']
record_size = sys.getsizeof(record_data)
error_prefix = '%s(record_key="%s", record_data=b"...")' % (title, record_key)
if record_size > record_max:
raise ValueError('%s exceeds maximum record data size of %s bytes.' % (error_prefix, record_max))
# TODO: apply session upload for files greater than record_max
# construct upload kwargs
upload_kwargs = {
'f': record_data,
'path': '/%s' % record_key,
'mute': True,
'mode': self.objects.WriteMode.overwrite
}
# modify file time
import re
if re.search('\\.drep$', record_key):
from labpack.records.time import labDT
drep_time = labDT.fromEpoch(1)
upload_kwargs['client_modified'] = drep_time
elif last_modified:
from labpack.records.time import labDT
mod_time = labDT.fromEpoch(last_modified)
upload_kwargs['client_modified'] = mod_time
# send upload request
try:
self.dropbox.files_upload(**upload_kwargs)
except:
raise DropboxConnectionError(title)
return True
def _walk(self, root_path=''):
''' an iterator method which walks the file structure of the dropbox collection '''
title = '%s._walk' % self.__class__.__name__
if root_path:
root_path = '/%s' % root_path
try:
response = self.dropbox.files_list_folder(path=root_path, recursive=True)
for record in response.entries:
if not isinstance(record, self.objects.FileMetadata):
continue
yield record.path_display[1:]
if response.has_more:
while response.has_more:
response = self.dropbox.files_list_folder_continue(response.cursor)
for record in response.entries:
if not isinstance(record, self.objects.FileMetadata):
continue
yield record.path_display[1:]
except:
raise DropboxConnectionError(title)
def exists(self, record_key):
'''
a method to determine if a record exists in collection
:param record_key: string with key of record
示例5: DropboxStorage
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_upload [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
#.........这里部分代码省略.........
示例6: DPBXBackend
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_upload [as 别名]
#.........这里部分代码省略.........
lookup = e.error.get_path_lookup()
if lookup.is_not_found():
return log.ErrorCode.backend_not_found
@command()
def _put(self, source_path, remote_filename):
remote_dir = urllib.unquote(self.parsed_url.path.lstrip('/'))
remote_path = '/' + os.path.join(remote_dir, remote_filename).rstrip()
file_size = os.path.getsize(source_path.name)
progress.report_transfer(0, file_size)
if file_size < DPBX_UPLOAD_CHUNK_SIZE:
# Upload whole file at once to avoid extra server request
res_metadata = self.put_file_small(source_path, remote_path)
else:
res_metadata = self.put_file_chunked(source_path, remote_path)
# A few sanity checks
if res_metadata.path_display != remote_path:
raise BackendException('dpbx: result path mismatch: %s (expected: %s)' %
(res_metadata.path_display, remote_path))
if res_metadata.size != file_size:
raise BackendException('dpbx: result size mismatch: %s (expected: %s)' %
(res_metadata.size, file_size))
def put_file_small(self, source_path, remote_path):
if not self.user_authenticated():
self.login()
file_size = os.path.getsize(source_path.name)
f = source_path.open('rb')
try:
log.Debug('dpbx,files_upload(%s, [%d bytes])' % (remote_path, file_size))
res_metadata = self.api_client.files_upload(f.read(), remote_path,
mode=WriteMode.overwrite,
autorename=False,
client_modified=None,
mute=True)
log.Debug('dpbx,files_upload(): %s' % res_metadata)
progress.report_transfer(file_size, file_size)
return res_metadata
finally:
f.close()
def put_file_chunked(self, source_path, remote_path):
if not self.user_authenticated():
self.login()
file_size = os.path.getsize(source_path.name)
f = source_path.open('rb')
try:
buf = f.read(DPBX_UPLOAD_CHUNK_SIZE)
log.Debug('dpbx,files_upload_session_start([%d bytes]), total: %d' %
(len(buf), file_size))
upload_sid = self.api_client.files_upload_session_start(buf)
log.Debug('dpbx,files_upload_session_start(): %s' % upload_sid)
upload_cursor = UploadSessionCursor(upload_sid.session_id, f.tell())
commit_info = CommitInfo(remote_path, mode=WriteMode.overwrite,
autorename=False, client_modified=None,
mute=True)
res_metadata = None
progress.report_transfer(f.tell(), file_size)
requested_offset = None
示例7: range
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_upload [as 别名]
#!/usr/bin/python
from ipaddress import ip_address
from os import environ
from subprocess import check_output
from dropbox import Dropbox
from dropbox.files import WriteMode
startIP=ip_address(u'80.73.48.0')
for ipCounter in range(0,4096):
ip = (startIP+ipCounter).__str__()
print(ip)
xmlMessage = check_output("nmap -oX - -F -sV "+ip,shell=True)
# read the dropbox access key from the environment variable DBX_KEY
dbxAccessKey = environ["DBX_KEY"]
# connect to dropbox
dbx=Dropbox(dbxAccessKey)
# upload scan file
dbx.files_upload(xmlMessage, "/NewScans/SCAN_"+ip+".xml", WriteMode.overwrite, True, None , True)
示例8: DropBoxStorage
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_upload [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
示例9: rpiImageDbxClass
# 需要导入模块: from dropbox import Dropbox [as 别名]
# 或者: from dropbox.Dropbox import files_upload [as 别名]
#.........这里部分代码省略.........
# Select only images and only the ones for the current imgid (camid)
foundImg = False
for f in self.ls_ref.entries:
if 'media_info' in f._all_field_names_ and \
f.media_info is not None:
if self.imgid in f.path_lower:
img = '.%s' % f.path_lower
foundImg = True
if not img in self.imageDbList:
self.imageDbList.append(img)
if not foundImg:
self.imageDbList = []
### Store the hash of the folder
self._imageDbCursor = self.ls_ref.cursor
if len(self.imageDbList) > 0:
logging.debug("%s::: _lsImage():: imageDbList[0..%d]: %s .. %s" % (self.name, len(self.imageDbList)-1, self.imageDbList[0], self.imageDbList[-1]) )
else:
logging.debug("%s::: _lsImage():: imageDbList[]: empty" % self.name)
except ApiError as e:
raise rpiBaseClassError("_lsImage(): %s" % e.error, ERRLEV2)
def _putImage(self, from_path, to_path, overwrite=False):
"""
Copy local file to remote file.
Stores the uploaded files names in self.imageUpldFIFO.
Examples:
_putImage('./path/test.jpg', '/path/dropbox-upload-test.jpg')
"""
try:
mode = (WriteMode.overwrite if overwrite else WriteMode.add)
with open(from_path, "rb") as from_file:
self._dbx.files_upload( from_file, '/' + os.path.normpath(to_path), mode)
if not overwrite:
self.imageUpldFIFO.append(from_path)
logging.debug("%s::: _putImage(): Uploaded file from %s to remote %s" % (self.name, from_path, to_path))
except IOError:
raise rpiBaseClassError("_putImage(): Local img file %s could not be opened." % from_path, ERRCRIT)
except ApiError as e:
raise rpiBaseClassError("_putImage(): %s" % e.error, ERRLEV2)
def _mkdirImage(self, path):
"""
Create a new remote directory.
Examples:
_mkdirImage('/dropbox_dir_test')
"""
try:
self._dbx.files_create_folder('/' + os.path.normpath(path))
logging.debug("%s::: Remote output folder /%s created." % (self.name, path))
except ApiError as e:
noerr = False
# dropbox.files.CreateFolderError
if e.error.is_path():
# dropbox.files.WriteError
we = e.error.get_path()
if we.is_conflict():
# dropbox.files.WriteConflictError
wce = we.get_conflict()
# union tag is 'folder'
if wce.is_folder():
logging.info("%s::: Remote output folder /%s already exist!" % (self.name, path))
noerr = True
if not noerr:
raise rpiBaseClassError("_mkdirImage(): Remote output folder /%s was not created! %s" % (path, e.error), ERRCRIT)
else:
pass
def _mvImage(self, from_path, to_path):
"""
Move/rename a remote file or directory.
Examples:
_mvImage('./path1/dropbox-move-test.jpg', '/path2/dropbox-move-test.jpg')
"""
try:
self._dbx.files_move( '/' + os.path.normpath(from_path), '/' + os.path.normpath(to_path) )
logging.debug("%s::: _mvImage(): Moved file from %s to %s" % (self.name, from_path, to_path))
except ApiError as e:
raise rpiBaseClassError("_mvImage(): Image %s could not be moved to %s! %s" % (from_path, to_path, e.error), ERRLEV2)