本文整理汇总了Python中dropbox.Dropbox类的典型用法代码示例。如果您正苦于以下问题:Python Dropbox类的具体用法?Python Dropbox怎么用?Python Dropbox使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Dropbox类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_program
def get_program(self):
"""Retrieve a program file from the Mpala Tower Dropbox listings."""
# Must use Dropbox to get program files.
from dropbox import Dropbox
from posixpath import join
import os
# Set up the Dropbox connection. Not sure how access_tokens will work
access_token = os.environ.get('access_token')
dropbox_dir = os.environ.get('dropbox_dir')
client = Dropbox(access_token)
# If this is our first time with this file, set the program name and
# location.
self.program_location = join(
dropbox_dir,
program_location,
self.program_name
)
# Retrieve the REST object from Dropbox
prog_link = client.files_get_temporary_link(self.program_location)
response = requests.get(prog_link.link)
# Put the program file contents into an array for parsing
program_content = response.text
# Send that stuff back.
return program_content
示例2: display
def display():
if 'access_token' not in session:
abort(400)
access_token = session['access_token']
if 'job' in session:
job = get_job_from_key(session['job'], conn)
# Only rely on a previous result if the same user is logged in (same access_token)
if job is not None and access_token == job.meta.get('access_token', None):
return render_template('display.html', username=session['username'], quota=session['quota'], used=session['used'])
try:
client = Dropbox(access_token)
except Exception:
abort(401)
account = client.users_get_current_account()
session['username'] = account.name.display_name
space_usage = client.users_get_space_usage()
allocated, used = get_space_usage_info(space_usage)
total_bytes = used
session['used'] = human_readable(used)
session['quota'] = human_readable(allocated)
job = q.enqueue(walk_entire_dropbox, access_token, total_bytes)
job.meta['access_token'] = access_token
job.save()
update_progress(job, 0, "/")
session['job'] = job.key
return render_template('display.html', username=session['username'], quota=session['quota'], used=session['used'])
示例3: i_am_dropbox
def i_am_dropbox(token):
from dropbox import Dropbox
my_client = Dropbox(token)
file_list = my_client.files_list_folder('')
#WE DID NOT CHECK HASMORE!
folder_list = [x.name for x in file_list.entries if 'size' not in dir(x)]
#print folder_list
return folder_list
示例4: revision
def revision():
dbx = Dropbox(session['access_token'])
f = dbx.files_download(request.args['path'], request.args['rev'])
resp = make_response(f[1].content)
resp.headers["Content-Disposition"] = "attachment; filename=" + f[0].name
return resp
示例5: dropBox
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)
示例6: DropboxWriter
class DropboxWriter(FilebaseBaseWriter):
"""
Writes items to dropbox folder.
options available
- access_token (str)
Oauth access token for Dropbox api.
- filebase (str)
Base path to store the items in the share.
"""
supported_options = {
'access_token': {'type': six.string_types, 'env_fallback': 'EXPORTERS_DROPBOXWRITER_TOKEN'},
}
def __init__(self, *args, **kw):
from dropbox import Dropbox
super(DropboxWriter, self).__init__(*args, **kw)
access_token = self.read_option('access_token')
self.set_metadata('files_counter', Counter())
self.client = Dropbox(access_token)
def write(self, dump_path, group_key=None, file_name=False):
if group_key is None:
group_key = []
self._write_file(dump_path, group_key, file_name)
@retry_long
def _upload_file(self, input_file, filepath):
from dropbox import files
session_id = self.client.files_upload_session_start('')
current_offset = 0
while True:
data = input_file.read(2**20)
if not data:
break
self.client.files_upload_session_append(data, session_id.session_id, current_offset)
current_offset += len(data)
cursor = files.UploadSessionCursor(session_id.session_id, current_offset)
self.client.files_upload_session_finish(
'', cursor, files.CommitInfo(path='{}'.format(filepath)))
def _write_file(self, dump_path, group_key, file_name=None):
filebase_path, file_name = self.create_filebase_name(group_key, file_name=file_name)
with open(dump_path, 'r') as f:
self._upload_file(f, '{}/{}'.format(filebase_path, file_name))
self.get_metadata('files_counter')[filebase_path] += 1
def get_file_suffix(self, path, prefix):
number_of_keys = self.get_metadata('files_counter').get(path, 0)
suffix = '{}'.format(str(number_of_keys))
return suffix
示例7: upload
def upload(dropbox_helper_id, access_token, size, max_retries):
from .models import DropboxUploadHelper
helper = DropboxUploadHelper.objects.get(id=dropbox_helper_id)
def progress_callback(bytes_uploaded, helper=helper, size=size):
helper.progress = float(bytes_uploaded) / size
helper.save()
try:
dropbox_path = '/{}'.format(os.path.basename(helper.src))
path_display = upload_to_dropbox(access_token, dropbox_path, helper.src, progress_callback)
except Exception as e:
helper.failure_reason = str(e)
helper.save()
couch_user = CouchUser.get_by_username(helper.user.username)
if helper.failure_reason is None:
dbx = Dropbox(access_token)
path_link_metadata = dbx.sharing_create_shared_link_with_settings(
path_display,
SharedLinkSettings(
requested_visibility=RequestedVisibility.team_only,
),
)
context = {
'share_url': path_link_metadata.url,
'path': os.path.join(
'Apps',
settings.DROPBOX_APP_NAME,
path_link_metadata.name,
)
}
with localize(couch_user.get_language_code()):
subject = _('{} has been uploaded to dropbox!'.format(helper.dest))
html_content = render_to_string('dropbox/emails/upload_success.html', context)
text_content = render_to_string('dropbox/emails/upload_success.txt', context)
else:
context = {
'reason': helper.failure_reason,
'path': helper.dest
}
with localize(couch_user.get_language_code()):
subject = _('{} has failed to upload to dropbox'.format(helper.dest))
html_content = render_to_string('dropbox/emails/upload_error.html', context)
text_content = render_to_string('dropbox/emails/upload_error.txt', context)
send_HTML_email(
subject,
helper.user.email,
html_content,
text_content=text_content,
)
示例8: files
def files():
if access_token:
dbx = Dropbox(access_token)
else:
return redirect(url_for("oauth2_start", _external=True, _scheme="https"))
if request.args.get("days"):
days = int(request.args.get("days"))
else:
days = 100
time_delta = datetime.now() - timedelta(days=days)
file_objs = dbx.files_list_folder("", recursive=True).entries
files_json = process_files(file_objs, time_delta)
return render_template("files.html", selected_files=files_json[:50])
示例9: DropboxHelper
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
示例10: post
def post(self, whose):
token = request.get_json()['access_token']
db = Dropbox(token)
if whose == 'mine':
start = time.clock()
budgets = db.get_own_budgets()
end = time.clock()
flask_app.logger.debug("Get own budgets time elapsed: {time}s".format(time=(end - start)))
elif whose == 'theirs':
start = time.clock()
budgets = db.get_their_budgets()
end = time.clock()
flask_app.logger.debug("Get their budgets time elapsed: {time}s".format(time=(end - start)))
return budgets
示例11: revisions
def revisions():
# Shared Link from Dropbox Chooser
link = request.args["link"]
# Calling Dropbox API v1
metadata = requests.post(
"https://api.dropbox.com/1/metadata/link",
params={"link": link},
headers={"Authorization": "Bearer " + str(session["access_token"])},
).json()
# Calling Dropbox API v2
dbx = Dropbox(session["access_token"])
entries = dbx.files_list_revisions(metadata["path"]).entries
return render_template("revisions.html", path=metadata["path"], revisions=entries)
示例12: __init__
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)
示例13: TestDropbox
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('')
示例14: revisions
def revisions():
# Shared Link from Dropbox Chooser
link = request.args['link']
# Calling Dropbox API v1
metadata = requests.post('https://api.dropbox.com/1/metadata/link', params={'link': link},
headers={'Authorization': 'Bearer ' + str(session['access_token'])}).json()
# Calling Dropbox API v2
if not metadata.get('path'):
return redirect(url_for('index'))
else:
dbx = Dropbox(session['access_token'])
entries = sorted(dbx.files_list_revisions(metadata['path']).entries, key=lambda entry: entry.client_modified)
entries.reverse()
return render_template('revisions.html', path=metadata['path'], filename=os.path.split(metadata['path'])[1],
revisions=entries)
示例15: process_user
def process_user(uid):
'''Call /delta for the given user ID and process any changes.'''
# OAuth token for the user
token = redis_client.hget('tokens', uid)
# /delta cursor for the user (None the first time)
cursor = redis_client.hget('cursors', uid)
dbx = Dropbox(token)
has_more = True
trello_client = trello.TrelloClient(TRELLO_API_KEY, token=TRELLO_API_TOKEN)
while has_more:
if cursor is None:
result = dbx.files_list_folder(path='/remote_workspace')
else:
result = dbx.files_list_folder_continue(cursor)
for entry in result.entries:
# Ignore deleted files, folders, and non-markdown files
if (isinstance(entry, DeletedMetadata) or isinstance(entry, FolderMetadata)):
continue
card = get_card_by_name(trello_client, entry.name.encode('utf-8'))
if(card == False):
trello_post(trello_client, entry.name.encode('utf-8'))
continue
card.set_pos("top")
card.comment("update! revision: %s" % entry.rev)
revs = dbx.files_list_revisions(entry.path_lower)
if(card.list_id == "577db30f129e87073996cc1a" and len(revs.entries) >= 2):
card.change_list("577db3127b9a95030e956ab8")
# Update cursor
cursor = result.cursor
redis_client.hset('cursors', uid, cursor)
# Repeat only if there's more to do
has_more = result.has_more