def __init__(self, app_key, app_secret, store, prefix = "/"): self.app_key = app_key self.app_secret = app_secret self.path_prefix = prefix self.cursor = None self.db = store self.api_client = None try: serialized_token = open(self.TOKEN_FILE).read() if serialized_token.startswith('oauth2:'): access_token = serialized_token[len('oauth2:'):] self.api_client = client.DropboxClient(access_token) print("Loaded OAuth 2 access token.") else: print("Malformed access token in %r." % (self.TOKEN_FILE,)) except IOError: sys.stdout.write("An access token file could not be loaded.\n") flow = client.DropboxOAuth2FlowNoRedirect(self.app_key, self.app_secret) authorize_url = flow.start() sys.stdout.write("1. Go to: " + authorize_url + "\n") sys.stdout.write("2. Click \"Allow\" (you might have to log in first).\n") sys.stdout.write("3. Copy the authorization code.\n") code = raw_input("Enter the authorization code here: ").strip() try: access_token, user_id = flow.finish(code) except rest.ErrorResponse, e: self.stdout.write('Error: %s\n' % str(e)) return with open(self.TOKEN_FILE, 'w') as f: f.write('oauth2:' + access_token) self.api_client = client.DropboxClient(access_token)
def __init__(self, app_key, app_secret): cmd.Cmd.__init__(self) self.app_key = app_key self.app_secret = app_secret self.current_path = '' self.prompt = "Dropbox> " self.api_client = None try: serialized_token = open(self.TOKEN_FILE).read() if serialized_token.startswith('oauth1:'): access_key, access_secret = serialized_token[len('oauth1:' ):].split( ':', 1) sess = session.DropboxSession(self.app_key, self.app_secret) sess.set_token(access_key, access_secret) self.api_client = client.DropboxClient(sess) print "[loaded OAuth 1 access token]" elif serialized_token.startswith('oauth2:'): access_token = serialized_token[len('oauth2:'):] self.api_client = client.DropboxClient(access_token) print "[loaded OAuth 2 access token]" else: print "Malformed access token in %r." % (self.TOKEN_FILE, ) except IOError: pass # don't worry if it's not there
def __init__(self): self.api_client = None self.config = ConfigParser.RawConfigParser() self.config.read('dropbox_collector_for_sumologic.ini') try: self.app_key = self.config.get('app_key', 'APP_KEY') self.app_secret = self.config.get('app_key', 'APP_SECRET') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): print( "Config file does not have entries for App Key and App Secret") print("Check the installation instructions to generate them") return try: serialized_token = self.config.get('token', 'TOKEN') if serialized_token.startswith('oauth1'): access_key, access_secret = serialized_token[len('oauth1:' ):].split( ':', 1) sess = session.DropboxSession(self.app_key, self.app_secret) sess.set_token(access_key, access_secret) self.api_client = client.DropboxClient(sess) elif serialized_token.startswith('oauth2:'): access_token = serialized_token[len('oauth2:'):] self.api_client = client.DropboxClient(access_token) else: print "Malformed access token in %r." % (self.TOKEN_FILE, ) except ConfigParser.NoSectionError: pass
def main(): if APP_KEY == '' or APP_SECRET == '': sys.stderr.write("ERROR: Set your APP_KEY and APP_SECRET at the top of %r.\n" % __file__) sys.exit(1) prog_name, args = sys.argv[0], sys.argv[1:] if len(args) != 2: sys.stderr.write("Usage: %s <oauth1-access-token-key> <oauth1-access-token-secret>\n") sys.exit(1) access_token_key, access_token_secret = args sess = session.DropboxSession(APP_KEY, APP_SECRET) sess.set_token(access_token_key, access_token_secret) c = client.DropboxClient(sess) sys.stdout.write("Creating OAuth 2 access token...\n") oauth2_access_token = c.create_oauth2_access_token() sys.stdout.write("Using OAuth 2 access token to get account info...\n") c2 = client.DropboxClient(oauth2_access_token) pprint.pprint(c2.account_info(), stream=sys.stdout) sys.stdout.write("Disabling OAuth 1 access token...\n") c.disable_access_token()
def upload_to_dropbox(backupConfig, backupArchive): print("Login to dropbox...") try: try: from dropbox import client, rest, session except ImportError, e: print("Dropbox sdk not found, please download and install the \ latest dropbox sdk from https://www.dropbox.com/developers/reference/sdk" ) raise e sess = session.DropboxSession(backupConfig.dropboxAppKey, backupConfig.dropboxAppSecret, backupConfig.dropboxAccessType) if backupConfig.dropboxAccessToken == gEmptyStr or not backupConfig.dropboxAccessToken: requestToken = sess.obtain_request_token() url = sess.build_authorize_url(requestToken) # Make the user sign in and authorize this token print("url: %s" % url) print( "Please visit this website and press the 'Allow' button, then hit 'Enter' here." ) raw_input() accessToken = sess.obtain_access_token(requestToken) # encrypt access token dropboxAccessTokenAesKey = aes.generateRandomKey(16) accessTokenKey = aes.encryptData(dropboxAccessTokenAesKey, accessToken.key) accessTokenSecret = aes.encryptData(dropboxAccessTokenAesKey, accessToken.secret) backupConfig.configParser.set( backupConfig.DropboxSection, "access_token", "%s:%s:%s" % (accessTokenKey.encode("hex"), accessTokenSecret.encode("hex"), dropboxAccessTokenAesKey.encode("hex"))) client = client.DropboxClient(sess) else: # read access token if not backupConfig.dropboxAccessToken or backupConfig.dropboxAccessToken == gEmptyStr: raise Exception("Cannot read access_token in config file %s" % backupConfig.configPath) accessTokenKey, accessTokenSecret, dropboxAccessTokenAesKey = backupConfig.dropboxAccessToken.split( ":") accessTokenKey = aes.decryptData( binascii.unhexlify(dropboxAccessTokenAesKey), binascii.unhexlify(accessTokenKey)) accessTokenSecret = aes.decryptData( binascii.unhexlify(dropboxAccessTokenAesKey), binascii.unhexlify(accessTokenSecret)) sess.set_token(accessTokenKey, accessTokenSecret) # init client client = client.DropboxClient(sess) # send backup file with open(backupArchive) as f: print("Upload %s to dropbox..." % (backupArchive)) response = client.put_file( "%s/%s" % (backupConfig.dropboxBackupDir, os.path.basename(allBackupArchive)), f)
def login(self): serialized_token = open(self.TOKEN_FILE).read() if serialized_token.startswith('oauth1:'): access_key, access_secret = serialized_token[len('oauth1:' ):].split(':', 1) sess = session.DropboxSession(self.app_key, self.app_secret) sess.set_token(access_key, access_secret) self.api_client = client.DropboxClient(sess) print "[loaded OAuth 1 access token]" elif serialized_token.startswith('oauth2:'): access_token = serialized_token[len('oauth2:'):] self.api_client = client.DropboxClient(access_token) print "[loaded OAuth 2 access token]" else: raise ("Malformed access token in %r." % (self.TOKEN_FILE, ))
def dropbox_callback(oauth_token=None, not_approved=False): from dropbox import client if not not_approved: if webnotes.conn.get_value("Backup Manager", None, "dropbox_access_key")==oauth_token: allowed = 1 message = "Dropbox access allowed." sess = get_dropbox_session() sess.set_request_token(webnotes.conn.get_value("Backup Manager", None, "dropbox_access_key"), webnotes.conn.get_value("Backup Manager", None, "dropbox_access_secret")) access_token = sess.obtain_access_token() webnotes.conn.set_value("Backup Manager", "Backup Manager", "dropbox_access_key", access_token.key) webnotes.conn.set_value("Backup Manager", "Backup Manager", "dropbox_access_secret", access_token.secret) webnotes.conn.set_value("Backup Manager", "Backup Manager", "dropbox_access_allowed", allowed) dropbox_client = client.DropboxClient(sess) try: dropbox_client.file_create_folder("files") except: pass else: allowed = 0 message = "Illegal Access Token Please try again." else: allowed = 0 message = "Dropbox Access not approved." webnotes.message_title = "Dropbox Approval" webnotes.message = "<h3>%s</h3><p>Please close this window.</p>" % message webnotes.conn.commit() webnotes.response['type'] = 'page' webnotes.response['page_name'] = 'message.html'
def save_to_dropbox(thefile): from dropbox import client, rest, session import pickle,os,sys APP_KEY = 'vj1wj79q76d25fe' APP_SECRET = '9xa061pw6x3zqgt' # ACCESS_TYPE = 'app_folder' ACCESS_TYPE = 'dropbox' try: sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE) token_file=open('config.dat') token_data=pickle.load(token_file) access_token=token_data['access_token'] access_secret=token_data['secret_token'] sess.set_token(access_token,access_secret) print "about to open client sesion" client = client.DropboxClient(sess) print "About to open the file" f=open(thefile,'rb') print "About to put the file" response=client.put_file('/'+thefile,f,True) print "about to print the response" print response['client_mtime'] except IOError as e: print "I/O error" except: print "Unexpected error:",sys.exc_info()[0] print sys.exc_info()[1] print sys.exc_info()[2]
def share(fileName, params=None, directDownload=False): if os.path.isdir(fileName) and findDropBox() not in fileName: return 'Sorry, I can share folders already uploaded to dropbox!' sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE) try: f = open('settings', 'r') key = enc(f.readline().rstrip(), False) secret = enc(f.readline().rstrip(), False) pathToShare = enc(f.readline(), False) dropboxPath = findDropBox() sess.set_token(key, secret) cl = client.DropboxClient(sess) if dropboxPath in fileName: filePath = os.path.relpath(fileName, dropboxPath) else: f = open(fileName) response = cl.put_file( os.path.join(pathToShare, os.path.basename(fileName)), f) filePath = response['path'] if directDownload is True and not os.path.isdir(fileName): result = cl.media(filePath) else: result = cl.share(filePath, params) return result['url'] except Exception, e: return 'Run assetup before!'
def settings(): from dropbox import client, rest, session from flask import session as flask_session flash('settings', 'btn') if (is_logged()): user = get_user() dropbox_session = user.get_dropbox_session() if (not dropbox_session): client = None sess = session.DropboxSession(dropbox_app_key(), dropbox_app_secret(), dropbox_access_type()) request_token = sess.obtain_request_token() url = sess.build_authorize_url( request_token, oauth_callback=dropbox_callback_url()) flask_session['session'] = sess flask_session['request_token'] = request_token else: client = client.DropboxClient(dropbox_session) url = None return render_template('users/settings.html', url=url, client=client) else: return redirect('/err_login')
def get_client(self): self.access_token = self.get_access_token() sess = session.DropboxSession(self.app_key, self.app_secret, self.access_type) sess.set_token(self.access_token.key, self.access_token.secret) dropbox_client = client.DropboxClient(sess) return dropbox_client
def callback(self, req_key): """ Call this when authentication has been established with browser. This will save the credentials for future use. Supply request_token to lookup object credentials from previous authentication. Returns: the request key (aka cookie to set to browser) Raises: rest.ErrorResponse: e.g. 'Token is disabled or invalid' """ req_tuple = tokens.get_request_pair(req_key) self.sess = session.DropboxSession(APP_KEY, APP_SECRET, access_type=ACCESS_TYPE) self.api_client = client.DropboxClient(self.sess) self.sess.set_request_token(req_tuple[0], req_tuple[1]) acc_pair = self.sess.obtain_access_token( ) #only works if request token is verified tokens.save_access_tokens(req_tuple[0], req_tuple[1], acc_pair.key, acc_pair.secret) log.debug("DELETE: saving: " + ` (req_tuple[0], req_tuple[1], acc_pair.key, acc_pair.secret) `) return req_key
def __init__(self, local_path, db_path): """ Parameters: local_path: The directory in which to store images on the Pi db_path: The remote directory located on the Dropbox account Returns: n/a """ self.current_path = db_path self.local_directory = local_path self.api_client = None self.cursor = None # Try to read in the current cursor if it exists. try: curfile = open(self.CURSOR_FILE, "r") self.cursor = curfile.read() curfile.close() except IOError: pass try: serialized_token = open(self.TOKEN_FILE).read() if serialized_token.startswith('oauth1:'): print "OAuth1 not supported." sys.exit() elif serialized_token.startswith('oauth2:'): access_token = serialized_token[len('oauth2:'):] self.api_client = client.DropboxClient(access_token) print "[loaded OAuth 2 access token]" else: print "Malformed access token in %r." % (self.TOKEN_FILE, ) except IOError: print "Not authorized. Use auth.sh to authenticate."
def __init__(self): try: accessToken = open("token_store.txt").read()[len('oauth2:'):] self.api_client = client.DropboxClient(accessToken) account_info = self.api_client.account_info() except: print "Please provide an oauth2 token in token_store.txt" sys.exit(1) # Metadata cache self.metadata = {} # File handles self.fileHandles = {} self.pathToHandle = {} # Current file number self.fileNumber = 1 print "Mounting %s's Dropbox account." % account_info['display_name'] print "Account Email Address: %s" % account_info['email'] # Pre-fill the metadata cache self.curDelta = None self.refreshDelta() # Start a new thread to keep the metadata cache up to date self.runMetaThread = True self.metaThread = Thread(target=self.refreshMeta) self.metaThread.daemon = True self.metaThread.start()
def test_oauth2_token_format_check(self): bad_tokens = [ '', '=', '=0123', '!AZaz09-_./~+', 'AZaz09-_./~+=.', 'abcdefg\n', 'abcdefg\t', 'abcdefg ', 'abc\ndefg', 'abc\tdefg', 'abc defg', '\nabcdefg', '\tabcdefg', ' abcdefg', ] good_tokens = [ '1=', '1', 'abcdefg', 'AZaz09-_./~+', 'AZaz09-_./~+=', 'AZaz09-_./~+==============', '.000000000000000000000000.', ] for t in bad_tokens: self.assertRaises(ValueError, client.DropboxClient, t) for t in good_tokens: client.DropboxClient(t)
def backup_to_dropbox(tokenfile=None, keyfile=None, targetdir=None): """ Copy backup files from myapp/backup folder to dropbox. By default this function looks for the dropbox access token in applications/my_app/private/dropbox_token.txt. It looks for the dropbox key and secret in applications/my_app/private/dropbox.keys. Either (or both) of these locations can be overridden with the 'tokenfile' and 'keyfile' keyword arguments. Writing it to this file means that permission only has to be given once per application. TODO: encrypt the dropbox token, possibly hashed in the db? """ #token = current.session.token # ???? tokenfile, keyfile, targetdir = filelocs(tokenfile, keyfile, targetdir) dropbox_session = dropbox_connect(tokenfile, keyfile) client = client.DropboxClient(dropbox_session) rootlen = len(targetdir) + 1 for base, dirs, files in os.walk(targetdir): for file in files: f = open(targetdir + '/' + file) client.put_file('f1/' + file, f) f.close() written = os.walk(targetdir) return {'base': written[0], 'dirs': written[1], 'files': written[2]}
def __init__(self, app_key, app_secret): cmd.Cmd.__init__(self) self.sess = StoredSession(app_key, app_secret, access_type=ACCESS_TYPE) self.api_client = client.DropboxClient(self.sess) self.current_path = '' #self.prompt = "Dropbox> " self.sess.load_creds() while 1: self.stdout.write("\nListening....") f = self.api_client.get_file("mobileread") message = f.read() if message <> " " and message <> "": self.stdout.write("Change Found\nMessage is:") self.stdout.write(message) multiprocessing.Process(target=self.run_process, args=(message, 10)).start() self.stdout.write("\ndeleting contents of mobileread....") self.api_client.put_file("mobileread", " ", True) else: self.stdout.write("No change found.") f.close()
def __init__(self, remote_dir, local_dir, cache_file, sleep=600, prg=None): self._logger = logging.getLogger(LOGGER) self.remote_dir = remote_dir.lower() if not self.remote_dir.startswith(dropboxpath.sep): self.remote_dir = dropboxpath.join(dropboxpath.sep, self.remote_dir) if self.remote_dir.endswith(dropboxpath.sep): self.remote_dir, _ = dropboxpath.split(self.remote_dir) self.local_dir = local_dir self.cache_file = cache_file self.sleep = int(sleep) # Can be string if read from conf. self.executable = prg self._tree = {} self._token = None self._cursor = None self._load_state() key, secret = decode_dropbox_key(APP_KEY) self.sess = DBSession(key, secret, access_type=ACCESS_TYPE) if self._token: self.sess.set_token(self._token[0], self._token[1]) else: self._token = self.sess.link() self.client = client.DropboxClient(self.sess)
def __init__(self, app_key, app_secret): self.app_key = app_key self.app_secret = app_secret self.current_path = '' self.parser = argparse.ArgumentParser() # create argparse entry for each command all_names = dir(self) cmd_names = [] for name in all_names: if name[:3] == 'do_': cmd_names.append(name[3:]) cmd_names.sort() self.parser.add_argument('command', action='store', choices=cmd_names) self.parser.add_argument('args', action='store', nargs='*') cmd_args = self.parser.parse_args() self.api_client = None try: token = open(self.TOKEN_FILE).read() self.api_client = client.DropboxClient(token) # find and execute the desired command getattr(self, 'do_' + cmd_args.command)(cmd_args.args) except IOError: pass # don't worry if it's not there
def __init__(self, *args, **kwargs): super(StubSFTPServer, self).__init__(*args, **kwargs) serialized_token = open(self.TOKEN_FILE).read() access_token = serialized_token[len('oauth2:'):] self.api_client = client.DropboxClient(access_token) self.current_path = self.ROOT
class DBox(): def __init__(self): self.logger = logging.getLogger('dbox') db = dbprovider.DB() self.api_client = None if TEST: access_token = TEST_TOKEN else: access_token = db.get_provider_token('dropbox') if access_token is None: flow = client.DropboxOAuth2FlowNoRedirect(CLIENT_ID, CLIENT_SECRET) authorize_url = flow.start() sys.stdout.write( "0. Make sure you are logged in at your account.\n") sys.stdout.write("1. Go to: " + authorize_url + "\n") sys.stdout.write( "2. Click \"Allow\" (you might have to log in first).\n") sys.stdout.write("3. Copy the authorization code.\n") code = raw_input("Enter the authorization code here: ").strip() try: access_token, user_id = flow.finish(code) db.set_provider_token('dropbox', access_token) self.logger.info('Successful login with user %s' % str(user_id)) except rest.ErrorResponse, e: self.logger.error('Error: %s\n' % str(e)) self.api_client = client.DropboxClient(access_token) self.logger.info("Successful client connection") # Dropbox tokens are valid forever db.shutdown_database()
def put_file(self, widget, data): #An object of the Authenticator class from oAuth authentication of our App config = auth.Authenticator.load_config("testing.ini") dba = auth.Authenticator(config) access_token = oauth.OAuthToken('k280uqm85ltjhop', 'bvsi4uto9muxmis') print access_token #An object of Client is created db_client = client.DropboxClient(config['server'], config['content_server'], config['port'], dba, access_token) root = config['root'] # Writes the data entered in the text box to the file print "Send button is clicked..." text = self.entry.get_text() # This location of file is to be taken from the user's laptop # A script which finds the location of the Dropbox folder # needs to be run myfile = open('ourfile.txt', 'w') myfile.truncate() myfile.write(text) myfile.close() f = open("ourfile.txt") resp = db_client.put_file(root, "/", f) #assert resp assert_equal(resp.status, 200)
def connect_to_dropbox(): """Authorizes the app with Dropbox. Returns False if we can't connect""" # No I will not care about scope. global dropbox_client global dropbox_info access_token = '' # Do we have access tokens? while len(access_token) == 0: try: token_file = open(DROPBOX_TOKEN_FILE, 'r') except IOError: # Re-build the file and try again, maybe? get_new_dropbox_tokens() token_file = open(DROPBOX_TOKEN_FILE, 'r') access_token = token_file.read() token_file.close() # Hopefully now we have token_key and token_secret... dropbox_client = client.DropboxClient(access_token) # Double-check that we've logged in try: dropbox_info = dropbox_client.account_info() except: # If we're at this point, someone probably deleted this app in their DB # account, but didn't delete the tokens file. Clear everything and try again. os.unlink(DROPBOX_TOKEN_FILE) access_token = '' connect_to_dropbox() # Who doesn't love a little recursion?
def setup(self): if (APP_KEY == '' or APP_SECRET == ''): xbmcgui.Dialog().ok(utils.getString(30010), utils.getString(30058), utils.getString(30059)) return user_token_key, user_token_secret = self.getToken() sess = session.DropboxSession(APP_KEY, APP_SECRET, "app_folder") if (user_token_key == '' and user_token_secret == ''): token = sess.obtain_request_token() url = sess.build_authorize_url(token) #print url in log utils.log("Authorize URL: " + url) xbmcgui.Dialog().ok(utils.getString(30010), utils.getString(30056), utils.getString(30057)) #if user authorized this will work user_token = sess.obtain_access_token(token) self.setToken(user_token.key, user_token.secret) else: sess.set_token(user_token_key, user_token_secret) self.client = client.DropboxClient(sess) try: utils.log(str(self.client.account_info())) except: #this didn't work, delete the token file self.deleteToken()
def log_in_or_out(login): global drop_client if not drop_client: if not os.path.isfile(TOKEN): request_token = sess.obtain_request_token() url = sess.build_authorize_url(request_token, oauth_callback=None) print "url:", url print "Please visit this website and press the 'Allow' button, then hit 'Enter' here." raw_input() # This will fail if the user didn't visit the above URL and hit 'Allow' access_token = sess.obtain_access_token(request_token) f = open(TOKEN, 'w') f.write('%s|%s' % (access_token.key, access_token.secret)) f.close() elif not login: os.remove(TOKEN) else: f = open(TOKEN, 'r') token_key, token_secret = f.read().split('|') sess.set_token(token_key, token_secret) drop_client = client.DropboxClient(sess) else: pass
def __init__(self, user): log.debug('initializing dropbox connection for: %s' % user) self.dbox_client = None # Get Access Token and Secret try: social_user = UserSocialAuth.objects.get(user=user, provider='dropbox') except UserSocialAuth.DoesNotExist: social_user = None if social_user: try: token = social_user.tokens['access_token'].split('&')[0].split( '=')[1] secret = social_user.tokens['access_token'].split( '&')[1].split('=')[1] # Set Access Token on Session dbox_session = session.DropboxSession( settings.DROPBOX_APP_ID, settings.DROPBOX_API_SECRET, 'app_folder') dbox_session.set_token(secret, token) self.dbox_client = client.DropboxClient(dbox_session) except Exception, e: log.warn(e)
def get_user(self): request = self.request if not current.session.dropbox_request_token: return None elif not current.session.dropbox_access_token: request_token = current.session.dropbox_request_token self.sess.set_request_token(request_token[0], request_token[1]) access_token = self.sess.obtain_access_token(self.sess.token) current.session.dropbox_access_token = \ (access_token.key,access_token.secret) else: access_token = current.session.dropbox_access_token self.sess.set_token(access_token[0], access_token[1]) user = Storage() self.client = client.DropboxClient(self.sess) data = self.client.account_info() display_name = data.get('display_name', '').split(' ', 1) user = dict(email=data.get('email', None), first_name=display_name[0], last_name=display_name[-1], registration_id=data.get('uid', None)) if not user['registration_id'] and self.on_login_failure: redirect(self.on_login_failure) return user
def get_account_info(): output = [] for access_token in json.loads( wf.get_password('dropbox_access_tokens')).values(): api_client = client.DropboxClient(access_token) output.append(api_client.account_info()) return output
def backup_to_dropbox(): from dropbox import client, session from frappe.utils.backups import new_backup from frappe.utils import get_files_path, get_backups_path if not frappe.db: frappe.connect() sess = session.DropboxSession(frappe.conf.dropbox_access_key, frappe.conf.dropbox_secret_key, "app_folder") sess.set_token( frappe.db.get_value("Dropbox Backup", None, "dropbox_access_key"), frappe.db.get_value("Dropbox Backup", None, "dropbox_access_secret")) dropbox_client = client.DropboxClient(sess) # upload database backup = new_backup(ignore_files=True) filename = os.path.join(get_backups_path(), os.path.basename(backup.backup_path_db)) upload_file_to_dropbox(filename, "/database", dropbox_client) frappe.db.close() # upload files to files folder did_not_upload = [] error_log = [] upload_from_folder(get_files_path(), "/files", dropbox_client, did_not_upload, error_log) upload_from_folder(get_files_path(is_private=1), "/private/files", dropbox_client, did_not_upload, error_log) frappe.connect() return did_not_upload, list(set(error_log))
def dropbox_client(): access_token_file = os.path.join(os.environ["HOME"], ".dropbox-tools-access-token") sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE) try: with open(access_token_file) as f: access_token = OAuthToken.from_string(f.read()) sess.set_token(access_token.key, access_token.secret) except (IOError, EOFError, KeyError): request_token = sess.obtain_request_token() url = sess.build_authorize_url(request_token) print "Please visit\n\n %s\n\nand press the 'Allow' button, then hit 'Enter' here." % url raw_input() # This will fail if the user didn't visit the above URL and hit 'Allow' access_token = sess.obtain_access_token(request_token) # dropbox access tokens don't have serialisation methods on them, my_token = OAuthToken(access_token.key, access_token.secret) with open(access_token_file, "w") as f: f.write(my_token.to_string()) conn = client.DropboxClient(sess) print "linked account:", conn.account_info()["display_name"] return conn