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 serve(queue, client): """ Serves the queue by retrieving current snapshot files. """ while True: task = queue.get() if not task: break else: path, filename = task snapshot_file = open(path) client.put_file(filename, snapshot_file) snapshot_file.close()
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 main(): #~ APP_KEY = 'vz2q46h298i5bqy' #~ APP_SECRET = 'f8xid4xf294wrv1' #~ ACCESS_TYPE = 'app_folder' data_serial = "text" width = 1000 height = 700 window_name = "test" number = 100 delay = 5 line_type = cv.CV_AA # change it to 8 to see non-antialiased graphics cpture = cv.CaptureFromCAM(1) cv.SetCaptureProperty(cpture, cv.CV_CAP_PROP_FRAME_WIDTH, 640/2) cv.SetCaptureProperty(cpture, cv.CV_CAP_PROP_FRAME_HEIGHT, 480/2) ulang=1 sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE) request_token = sess.obtain_request_token() url = sess.build_authorize_url(request_token) print "url:", url raw_input() access_token = sess.obtain_access_token(request_token) client = client.DropboxClient(sess) print "linked account:", client.account_info() nomorfile=0 namafile = "initiasinama" aktiv=0 ser.timeout = 5 print "standby" while (ulang==1): image = cv.QueryFrame(cpture) cv.NamedWindow(window_name, 1) cv.ShowImage(window_name, image) data = ser.read(1) if(data=="1"): print("alarm aktiv") aktiv = 1 if (data=="0"): print("password terautentifikasi") aktiv = 0 print("standby") if (aktiv==1): cv.SaveImage("photo.jpg",image) f=open('photo.jpg') namafile="photo"+elinsGetDate()+".jpg" nomorfile=nomorfile+1 response = client.put_file(namafile, f) f.close() print "uploaded: ", namafile
def dropbox_save(): dropbox_access_token = session.get(DROPBOX_ACCESS_KEY, None) if dropbox_access_token is None: return "please log into dropbox first" root = request.args.get('dir', '/') dropbox_client = get_client(dropbox_access_token) filepath = request.form.get('filepath', None) if filepath is None: return "You didn't specify a file path!" contents = request.form.get('contents', "") try: dropbox_client.put_file(filepath, contents, overwrite=True) return contents except Exception, e: return e.message
def upload_and_get_url(file_to_upload, extension): """ Takes a file and extension, uploads file to DBox at random URL with random flename+extension, returns the URL """ import string, random filename = binascii.b2a_hex(os.urandom(30))+extension put = client.put_file(filename, file_to_upload) share = client.share(filename, short_url=False) return {'url':share['url'].replace('https://www.dropbox.com/', 'https://dl.dropboxusercontent.com/'), 'filename':filename}
def main(): #~ APP_KEY = 'vz2q46h298i5bqy' #~ APP_SECRET = 'f8xid4xf294wrv1' #~ ACCESS_TYPE = 'app_folder' data_serial = "text" width = 1000 height = 700 window_name = "test" number = 100 delay = 5 line_type = cv.CV_AA # change it to 8 to see non-antialiased graphics cpture = cv.CaptureFromCAM(1) cv.SetCaptureProperty(cpture, cv.CV_CAP_PROP_FRAME_WIDTH, 640 / 2) cv.SetCaptureProperty(cpture, cv.CV_CAP_PROP_FRAME_HEIGHT, 480 / 2) ulang = 1 sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE) request_token = sess.obtain_request_token() url = sess.build_authorize_url(request_token) print "url:", url raw_input() access_token = sess.obtain_access_token(request_token) client = client.DropboxClient(sess) print "linked account:", client.account_info() nomorfile = 0 namafile = "initiasinama" aktiv = 0 ser.timeout = 5 print "standby" while (ulang == 1): image = cv.QueryFrame(cpture) cv.NamedWindow(window_name, 1) cv.ShowImage(window_name, image) data = ser.read(1) if (data == "1"): print("alarm aktiv") aktiv = 1 if (data == "0"): print("password terautentifikasi") aktiv = 0 print("standby") if (aktiv == 1): cv.SaveImage("photo.jpg", image) f = open('photo.jpg') namafile = "photo" + elinsGetDate() + ".jpg" nomorfile = nomorfile + 1 response = client.put_file(namafile, f) f.close() print "uploaded: ", namafile
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 uploadfile(): root = Tkinter.Tk() #select the file of your choice file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a file') print "Before Encryption" print file out="encrypted.txt.gpg" encrypted_ascii_data = gpg.encrypt_file(file,'girish' ,output=out,passphrase="random") #Use the comment and passphrase given during key generation for encryption. f = open("encrypted.txt.gpg", 'rb') response = client.put_file("encrypted.txt.gpg", f) print 'uploaded: ', response
def main(argv): # Parse the command-line flags. parser = argparse.ArgumentParser(description="Dropbox uploader for Ufo-profiler") parser.add_argument("-i", "--input_file", required=True, type=str, help="path to the file") parser.add_argument("-o", "--output_path", required=True, type=str, help="path to the output path") try: args = parser.parse_args() except argparse.ArgumentTypeError as err: print err sys.exit(1) flow = dropbox.client.DropboxOAuth2FlowNoRedirect(app_key, app_secret) access_token = None if os.path.isfile(access_token_file): f = open(access_token_file, "r") access_token = f.read() f.close() if not access_token: # Have the user sign in and authorize this token authorize_url = flow.start() print "1. Go to: " + authorize_url webbrowser.open(authorize_url, new=2) print '2. Click "Allow" (you might have to log in first)' print "3. Copy the authorization code." code = raw_input("Enter the authorization code here: ").strip() # This will fail if the user enters an invalid authorization code access_token, user_id = flow.finish(code) if access_token: try: f = open(access_token_file, "w") except IOError as err: print "Can't write to file {0}!".format(access_token_file) sys.exit(1) f.write(access_token) f.close() client = dropbox.client.DropboxClient(access_token) input_file = args.input_file target_path = args.output_path base_filename = os.path.splitext(os.path.basename(input_file))[0] target_path_file = os.path.join(target_path, base_filename) f = open(input_file, "rb") response = client.put_file(target_path_file, f) print "File {0} has been inserted!".format(base_filename)
def upload(self,file, options): '''Plugin interface method to upload a file :param file: Path to the file to upload :type file: str :param options: context parameters :type options: list ''' f = open(file) from dropbox import client self.sess.set_token(options['drop_access_token'].key,options['drop_access_token'].secret) client = client.DropboxClient(self.sess) response = client.put_file('/'+options['name'], f)
def dropbox(APP_KEY, APP_SECRET, ACCESS_TYPE, upload_file): global client sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE) request_token = sess.obtain_request_token() url = sess.build_authorize_url(request_token) # Make the user sign in and authorize this token webbrowser.open(url, modal=False, stop_when_done=False) input() # This will fail if the user didn't visit the above URL and hit 'Allow' access_token = sess.obtain_access_token(request_token) client = client.DropboxClient(sess) response = client.put_file(upload_file, upload_file)
def dropbox(APP_KEY, APP_SECRET, ACCESS_TYPE, upload_file): global client sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE) request_token = sess.obtain_request_token() url = sess.build_authorize_url(request_token) # Make the user sign in and authorize this token open(url, modal=True) raw_input('Please press enter to continue') # This will fail if the user didn't visit the above URL and hit 'Allow' access_token = sess.obtain_access_token(request_token) client = client.DropboxClient(sess) response = client.put_file('Script Backups' + upload_file, upload_file)
def take_picture(): pygame.camera.init() cam = pygame.camera.Camera("/dev/video0", (640, 480)) cam.start() image = cam.get_image() file_name = 'webcam%s.png' % datetime.datetime.now().strftime( "%Y_%m_%d_%H_%M_%S") full_file_name = '%s%s' % (WEBCAM_PICTURE_FOLDER, file_name) pygame.image.save(image, full_file_name) cam.stop() if (brightness(full_file_name) < 50): # too dark os.remove(full_file_name) print "not bright enough, abort uploading image" return # detect whether to upload by image diff files = filter(os.path.isfile, glob.glob(WEBCAM_PICTURE_FOLDER + "*")) img1 = None if len(files) >= 2: files.sort(key=lambda x: os.path.getmtime(x)) # -1 is the one we just took most_recent_file_name = os.path.basename(files[len(files) - 2]) img1 = Image.open('%s%s' % (WEBCAM_PICTURE_FOLDER, most_recent_file_name)) img2 = Image.open(full_file_name) if img1: if img1.size != img2.size or img1.getbands() != img2.getbands(): return diff = 0 for band_index, band in enumerate(img1.getbands()): m1 = numpy.array([p[band_index] for p in img1.getdata()]).reshape(*img1.size) m2 = numpy.array([p[band_index] for p in img2.getdata()]).reshape(*img2.size) diff += numpy.sum(numpy.abs(m1 - m2)) if diff < 4500000: os.remove(full_file_name) print "not different enough, abort uploading image" return # upload to dropbox client = authenticate_to_dropbox() f = open(full_file_name) response = client.put_file(file_name, f) print "uploaded: ", response return json.dumps('./static/img/webcam/%s' % file_name)
def uploadfile(): root = Tkinter.Tk() #select the file of your choice file = tkFileDialog.askopenfile(parent=root, mode='rb', title='Choose a file') print "Before Encryption" print file out = "encrypted.txt.gpg" encrypted_ascii_data = gpg.encrypt_file(file, 'girish', output=out, passphrase="random") #Use the comment and passphrase given during key generation for encryption. f = open("encrypted.txt.gpg", 'rb') response = client.put_file("encrypted.txt.gpg", f) print 'uploaded: ', response
def take_picture(): pygame.camera.init() cam = pygame.camera.Camera("/dev/video0", (640, 480)) cam.start() image= cam.get_image() file_name = 'webcam%s.png' % datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S") full_file_name = '%s%s' % (WEBCAM_PICTURE_FOLDER, file_name) pygame.image.save(image, full_file_name) cam.stop() if (brightness(full_file_name) < 50): # too dark os.remove(full_file_name) print "not bright enough, abort uploading image" return # detect whether to upload by image diff files = filter(os.path.isfile, glob.glob(WEBCAM_PICTURE_FOLDER + "*")) img1 = None if len(files) >= 2: files.sort(key=lambda x: os.path.getmtime(x)) # -1 is the one we just took most_recent_file_name = os.path.basename(files[len(files)-2]) img1 = Image.open('%s%s' % (WEBCAM_PICTURE_FOLDER, most_recent_file_name)) img2 = Image.open(full_file_name) if img1: if img1.size != img2.size or img1.getbands() != img2.getbands(): return diff = 0 for band_index, band in enumerate(img1.getbands()): m1 = numpy.array([p[band_index] for p in img1.getdata()]).reshape(*img1.size) m2 = numpy.array([p[band_index] for p in img2.getdata()]).reshape(*img2.size) diff += numpy.sum(numpy.abs(m1-m2)) if diff < 4500000: os.remove(full_file_name) print "not different enough, abort uploading image" return # upload to dropbox client = authenticate_to_dropbox() f = open(full_file_name) response = client.put_file(file_name, f) print "uploaded: ", response return json.dumps('./static/img/webcam/%s' % file_name)
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 doing_anything(): """ Выполняет некоторые действия Precond.: Авторизация должна пройти Returns: """ # Проверка авторизованности? # This will fail if the user didn't visit the above URL and hit 'Allow' access_token = sess.obtain_access_token(request_token) # Все хорошо? ''' 'Now that the hard part is done, all you'll need to sign your other API calls is to to pass the session object to DropboxClient and attach the object to your requests.''' client = client.DropboxClient(sess) f = open('working-draft.txt') response = client.put_file('/magnum-opus.txt', f) return response
def main(): # Include the Dropbox SDK libraries from dropbox import client, rest, session # Get your app key and secret from the Dropbox developer website APP_KEY = 'INSERT_APP_KEY_HERE' APP_SECRET = 'INSERT_SECRET_HERE' # ACCESS_TYPE should be 'dropbox' or 'app_folder' as configured for your app ACCESS_TYPE = 'INSERT_ACCESS_TYPE_HERE' sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE) request_token = sess.obtain_request_token() # Make the user sign in and authorize this token url = sess.build_authorize_url(request_token) print "url:", url print "Please authorize in the browser. After you're done, press enter." 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) client = client.DropboxClient(sess) print "linked account:", client.account_info() f = open('working-draft.txt') response = client.put_file('/magnum-opus.txt', f) print "uploaded:", response folder_metadata = client.metadata('/') print "metadata:", folder_metadata f, metadata = client.get_file_and_metadata('/magnum-opus.txt') out = open('magnum-opus.txt', 'w') out.write(f.read()) out.close() print(metadata)
if __name__ == "__main__": uploadFile = "" if len(sys.argv) > 1: uploadFile = sys.argv[1] print "I see you'd like to schlepp", uploadFile else: print "What file to schlepp?: ", uploadFile = raw_input() if (os.path.exists(uploadFile)): print "Good, I found your file." else: print "Looks like I can't find a file called '{0}'.".format(uploadFile) sys.exit(1) SessionInfo = {} if (not(os.path.exists(".schlepp.key"))): print "Didn't find an access token. Getting one for you." getFirstAccessToken() SessionInfo = getPickledAccessToken() print "Schlepping." sess = session.DropboxSession(SessionInfo.key, SessionInfo.secret,dropbox_access_type) sess.set_token(SessionInfo.token,SessionInfo.token_secret) client = client.DropboxClient(sess) f = open(uploadFile) response = client.put_file(uploadFile, f) print "Successfully uploaded. Sharing." shareresponse = client.share(response['path']) print "Shared: ", shareresponse['url']
c = conn.cursor() def deposit(name, amount): c.execute("INSERT INTO deposits (NAME, AMOUNT, DATE) VALUES ('{}', {}, '{}')".format(name, float(amount.strip()[1:-1]), today)) conn.commit() print('deposit successful') def withdraw(name, amount): c.execute("INSERT INTO withdrawals (NAME, AMOUNT, DATE) VALUES ('{}', {}, '{}')".format(name, float(amount), today)) conn.commit() print('withdrawal successful') withdrawals_val = 0 deposits_val = 0 def get_vals(val,table): c.execute("SELECT amount FROM {}".format(table)) for row in c.fetchall(): val += (float(str(row)[1:-2])) return (val) if amount.startswith('('): deposit(name, amount) else: withdraw(name, amount) print('balance = {}'.format(get_vals(deposits_val,'deposits') -get_vals(withdrawals_val,'withdrawals'))) with open('checkbook.test.db', 'r+') as f: client.put_file('/checkbook.test.db', f,True)
#you do not need any of the above if you run the request_dropbox_token.py application token_file = open('dropbox_token.txt', 'r') token_key,token_secret = token_file.read().split('|') token_file.close() sess = session.DropboxSession(APP_KEY,APP_SECRET, ACCESS_TYPE) sess.set_token(token_key,token_secret) client = client.DropboxClient(sess) print "linked account:", client.account_info() print print "NOW READY TO UPLOAD!!!" print #below you declare what file you are uploading. f = open('working-draft.txt') #below you declare location AND name of file to upload as. Name whatever you desire. response = client.put_file('/fileUploader_linkCreator/magnum-opus.txt', f) print "uploaded:", response print print "FILE UPLOADED SUCCESSFULLY!!" print "...NOW ONTO CREATING LINK" print link = client.share('/fileUploader_linkCreator/magnum-opus.txt') print link
def upload_file(src, dest): with open(src) as f: response = client.put_file(dest, f) print "uploaded: ", response
def command(self, args, options): try: config_file = args[1] except IndexError: print 'Config file is not provided' return config = { 'server': 'api.dropbox.com', 'port': self.port, 'request_token_url': self.request_token_url, 'access_token_url': self.access_token_url, 'authorization_url': self.authorization_url, 'trusted_access_token_url': self.trusted_access_token_url, 'root': options['root'], 'verifier': self.verifier } config.update(dropbox.auth.Authenticator.load_config(config_file)) auth = dropbox.auth.Authenticator(config) if not config['access_token']: request_token = auth.obtain_request_token() url = auth.build_authorize_url(request_token) print 'Authorize dropper to access your Dropbox at \n%s' % url raw_input('Press enter key when you are done...') try: access_token = auth.obtain_access_token( request_token, self.verifier) except AssertionError: print "Failed to connect to Dropbox." return else: print 'Connected to Dropbox successfully!' print 'Got access token. Copy it to your config file: \n%s' % \ access_token.to_string() return # Determines remote directory and the file to upload try: remote_dir = args[2] except IndexError: print 'The remote dir is not provided' return try: upload_file = args[3] except IndexError: print 'The file to upload is not provided' return access_token = oauth.OAuthToken.from_string(config['access_token']) client = dropbox.client.DropboxClient(self.api_host, self.content_host, self.port, auth, access_token) f = open(upload_file, 'r') result = client.put_file(options['root'], remote_dir, f).data f.close() if result is None: print 'Unknown error' elif 'error' in result: print 'Error: %s' % result['error'] else: print 'Uploaded successfully.'
from dropbox import client, rest, session from get_keys import get_keys APP_KEY = 'ey24mzrpiyv5rzf' APP_SECRET = 'd0kh09zn6hv58hg' ACCESS_TYPE = 'app_folder' sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE) keys = get_keys() sess.set_token(keys[0], keys[1]) print keys[0], keys[1] client = client.DropboxClient(sess) file_name = "file.txt" response = client.put_file("/" + file_name, open(file_name)) print "uploaded:", response
def __call__(self, *args): # Include the Dropbox SDK libraries from dropbox import client, rest, session try: config_file = args[1] except IndexError: print "Config file is not provided" return else: if not os.path.exists(config_file): self.create_config_file(config_file) return try: remote_dir = args[2] except IndexError: print "The remote dir is not provided" return try: upload_file = args[3] except IndexError: print "The file to upload is not provided" return conf = ConfigParser.SafeConfigParser() conf.read(config_file) APP_KEY = conf.get(SECTION_AUTH, KEY_APP_KEY) APP_SECRET = conf.get(SECTION_AUTH, KEY_APP_SECRET) ACCESS_TYPE = conf.get(SECTION_AUTH, KEY_ACCESS_TYPE) ACCESS_TOKEN = conf.get(SECTION_AUTH, KEY_ACCESS_TOKEN) sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE) if not ACCESS_TOKEN: request_token = sess.obtain_request_token() url = sess.build_authorize_url(request_token) # Make the user sign in and authorize this token print "url:", url print "Please visit this website and press the 'Allow' button, then hit 'Enter' here." raw_input() try: access_token = sess.obtain_access_token(request_token) except AssertionError: print "Failed to connect to Dropbox." return else: print "Connected to Dropbox successfully!" print "Got access token. Copy it to your config file: \n%s" % access_token.to_string() return access_token = oauth.OAuthToken.from_string(ACCESS_TOKEN) sess.set_token(access_token.key, access_token.secret) client = client.DropboxClient(sess) f = open(upload_file) result = client.put_file(remote_dir + "/" + upload_file, f) f.close() if result is None: print "Unknown error" elif "error" in result: print "Error: %s" % result["error"] else: print "Uploaded successfully."
print "saving file " + outfilel cv2.imwrite("/dev/shm/bad_webcam.jpg", color) print("saving file /dev/shm/bad_webcam.jpg") else: outfilel = "flir_" + timestamp + ".jpg" outfiled = "flir_" + timestamp + ".jpg" cv2.imwrite(outfilel, color) print "saving file " + outfilel cv2.imwrite("/dev/shm/webcam.jpg", color) print("saving file /dev/shm/webcam.jpg") dropbox_token = 'BLwCADKixxgAAAAAAAE9brLPAQqsJ6mfbsm4XGAffOgMdvNv2IyaMbu04aUsUeHf' client = dropbox.client.DropboxClient(dropbox_token) if(db_decimate_count == db_decimate_rate): f = open(outfilel, 'rb') response = client.put_file(outfiled, f) print 'uploaded file: ', response['path'] print 'uploaded bytes: ', response['size'] db_decimate_count = 0 # reset counter db_decimate_count = db_decimate_count + 1 if (delay == "0"): first_shot = True print "stopping further pictures" f = open(outfilel, 'rb') response = client.put_file(outfiled, f) print 'uploaded file: ', response['path'] print 'uploaded bytes: ', response['size'] db_decimate_count = 0 # reset counter else: first_shot = False
# Include the Dropbox SDK libraries from dropbox import client, rest, session APP_KEY = "jgrn1vwmfcp0lpf" APP_SECRET = "reftv8sfas3bte5" ACCESS_TYPE = "app_folder" sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE) request_token = sess.obtain_request_token() # Make the user sign in and authorize this token url = sess.build_authorize_url(request_token) print "url:", url print "Please authorize in the browser. After you're done, press enter." 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) client = client.DropboxClient(sess) print "linked account:", client.account_info() f = open("/home/santee/workspace/Remote_Software/App/Code.py", "rb") response = client.put_file("/Remote_Software.py", f) print "uploaded:", response
APP_KEY = 'hhid9alxtnee5on' APP_SECRET = 'crxlj3sautuoo4d' ACCESS_TYPE = 'app_folder' # get the stored key from step one and use it token_file = open(TOKENS, 'r') token_key,token_secret = token_file.read().split('|') token_file.close() # init the session and the client sess = session.DropboxSession(APP_KEY,APP_SECRET, ACCESS_TYPE ) sess.set_token(token_key,token_secret) # APP_ACCESS_TOKEN = 'k4QvXviokXAAAAAAAAABAPBADOBTKgo2d5Wvib_QJWNC2lwakMXNL7kcZoorYUkN' client = client.DropboxClient(sess) if file_num == 1: f = open(file_source_path+sys.argv[1], 'r') res = client.put_file("/data/"+sys.argv[1], f) f.close() else: os.chdir(file_source_path) #subprocess.call(["rm", "data_batch.tar"]) subprocess.call(["tar", "czf", "data_batch.tar"]+sys.argv[1:]) f = open("data_batch.tar", 'r') res = client.put_file("/data/data_batch.tar", f) f.close() print res
# Make the user sign in and authorize this token url = sess.build_authorize_url(request_token) print "url:", url print "Please authorize in the browser. After you're done, press enter." 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) TOKENS = 'dropbox_token.txt' token_file = open(TOKENS,'w') token_file.write("%s|%s" % (access_token.key,access_token.secret) ) token_file.close() token_file = open(TOKENS) token_key,token_secret = token_file.read().split('|') token_file.close() sess.set_token(token_key,token_secret) client = client.DropboxClient(sess) #stored_creds = open(CONF_DIR + self.TOKEN_FILE).read() uploading of a file f = open('today.txt') response = client.put_file('/magnum_opus.txt', f) #listing of the files folder_metadata = client.metadata('/') #downloading the files f, metadata = client.get_file_and_metadata('/magnum_opus.txt') out = open('magnum_opus.txt', 'wb') out.write(f.read()) out.close()
# Include the Dropbox SDK libraries from dropbox import client, rest, session # Get your app key and secret from the Dropbox developer website APP_KEY = '6gccue9fycfx31b' APP_SECRET = 'wrtegtt4cu3z05e' # ACCESS_TYPE should be 'dropbox' or 'app_folder' as configured for your app ACCESS_TYPE = 'dropbox' sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE) # We will use the OAuth token we generated already. The set_token API # accepts the oauth_token and oauth_token_secret as inputs. sess.set_token("a117lsxqf4v0tpx7", "cui6kwmyp60xwkp") # Create an instance of the dropbox client for the session. This is # all we need to perform other actions client = client.DropboxClient(sess) # Let's upload a file! f = open('gl.html') response = client.put_file('/gl.html', f) print "uploaded:", response
Tk().withdraw( ) # we don't want a full GUI, so keep the root window from appearing filename = askopenfilename( ) # show an "Open" dialog box and return the path to the selected file print 'selected file: ', filename # upfile = open('E:/workspace/CSE6331/upload/working-draft.txt', 'rb') # upfile = open(filename, 'rb') # l = [] # l = filename.split('/') # # print l[-1] encfile = encrypt_file(key, filename) upfile = open(encfile, 'rb') response = client.put_file('/' + filename.split('/')[-1], upfile) print 'uploaded: ', response upfile.close() new_name = '../../upload/' + filename.split('/')[-1] os.rename(encfile, new_name) print 'encrypted file: ', new_name # folder_metadata = client.metadata('/') # print 'metadata: ', folder_metadata # downfile, metadata = client.get_file_and_metadata('/' + filename.split('/')[-1]) # print 'downfile: ', downfile out = open('../../download/' + filename.split('/')[-1] + '.enc', 'wb') out.write(downfile.read())
print "%6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f" % (voltage[0], voltage[1], voltage[2], voltage[3], voltage[4], voltage[5], voltage[6], voltage[7], voltage[8], voltage[9], voltage[10], voltage[11]) fo.write("%6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f" % (voltage[0], voltage[1], voltage[2], voltage[3], voltage[4], voltage[5], voltage[6], voltage[7], voltage[8], voltage[9], voltage[10], voltage[11])) fo.write("\n") time.sleep(speed/2) a.close() fo.close() #*********************Below code uploads to dropbox*************# APP_KEY = 'INSERT_APP_KEY_HERE' APP_SECRET = 'INSERT_SECRET_HERE' ACCESS_TYPE = 'app_folder' TOKENS = 'dropbox_token.txt' token_file = open(TOKENS) token_key,token_secret = token_file.read().split('|') token_file.close() sess = session.DropboxSession(APP_KEY,APP_SECRET, ACCESS_TYPE ) sess.set_token(token_key,token_secret) client = client.DropboxClient(sess) f = open(now1.strftime("%Y%m%d_%H%M%S")) response = client.put_file(now1.strftime("%Y%m%d_%H%M%S.txt"), f) f.close()
request_token = sess.obtain_request_token() # Make the user sign in and authorize this token url = sess.build_authorize_url(request_token) print "url:", url print "Please authorize in the browser. After you're done, press enter." 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) TOKENS = 'dropbox_token.txt' #create a new file to store api key information token_file = open(TOKENS, 'w') token_file.write("%s|%s" % (access_token.key, access_token.secret)) token_file.close() client = client.DropboxClient(sess) print "linked account:", client.account_info() f = open('working-draft.txt') response = client.put_file('/magnum-opus.txt', f) print "uploaded:", response folder_metadata = client.metadata('/') print "metadata:", folder_metadata #f, metadata = client.get_file_and_metadata('/magnum-opus.txt',rev='362e2029684fe') #out = open('magnum-opus.txt', 'w') #out.write(f.read()) #print(metadata)
# print 'linked account: ', client.account_info() Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file print 'selected file: ', filename # upfile = open('E:/workspace/CSE6331/upload/working-draft.txt', 'rb') # upfile = open(filename, 'rb') # l = [] # l = filename.split('/') # # print l[-1] encfile = encrypt_file(key, filename) upfile = open(encfile, 'rb') response = client.put_file('/' + filename.split('/')[-1], upfile) print 'uploaded: ', response upfile.close() new_name = '../../upload/' + filename.split('/')[-1] os.rename(encfile, new_name) print 'encrypted file: ', new_name # folder_metadata = client.metadata('/') # print 'metadata: ', folder_metadata # downfile, metadata = client.get_file_and_metadata('/' + filename.split('/')[-1]) # print 'downfile: ', downfile out = open('../../download/' + filename.split('/')[-1] + '.enc', 'wb') out.write(downfile.read()) out.close()
while 1: opt = raw_input("Enter choice : U- Encrypt and upload, D- Download and decrypt, E- Exit") if(opt=="U"): f_name = raw_input("Enter the full path of the file to be encrypted (including the file extension):") key_opt = raw_input("Do you want to use a new key or encrypt with default ? (N/D)") if(key_opt=="N"): opt1=raw_input("Enter key...minimum 16 bytes long") else: opt1="1234567891234567" encrypt_file(opt1,f_name) f_new_name=f_name+".enc" f = open(f_new_name) f_new_name_ext = "/"+f_new_name response = client.put_file(f_new_name_ext, f) print "File uploaded successfully:", response try: os.remove(f_new_name) except Exception, e: print e if(opt=="D"): f_name = raw_input("Enter filename (with file extension):") key_opt = raw_input("Use a specific key or the default ? (S/D)") if(key_opt=="S"): opt1=raw_input("Enter key used to encrypt the file ?") else: opt1 = "1234567891234567" f_new_name="/"+f_name
url = sess.build_authorize_url(request_token) # clipboard.Paste(url) print "url:", url print "Please visit this website and press the 'Allow' button, then hit 'Enter' here." raw_input() access_token = sess.obtain_access_token(request_token) print access_token print dir(access_token) print "Key:" print access_token.key print "Secret:" print access_token.secret ac_file = open("act.txt", "w") ac_file.write(str(access_token.key) + "*" + str(access_token.secret)) ac_file.close() client = client.DropboxClient(sess) if args.status: print "Account info:".format(args.filename) print "linked account:", client.account_info() filename = args.filename if filename: print "uploading file" print filename upload_file = open(filename, "rb") response = client.put_file(filename, upload_file) print "uploaded:", response
print('reading tokens...') with open(sys.argv[1]) as f: lines = f.readlines() lines = [item.strip() for item in lines[:4]] app_key, app_secret, token_key, token_secret = lines if not os.path.isdir(sys.argv[2]): exit('source path is not a directory: ' + sys.argv[2]) src_dir = sys.argv[2].strip(os.path.sep + os.path.altsep) ts = datetime.datetime.now().strftime("%Y%m%d%H%M") zip_file = "%s_%s.zip" % (ts, os.path.basename(src_dir)) print("archiving '%s' to '%s'..." % (src_dir, zip_file)) with zipfile.ZipFile(zip_file, 'w') as z: for root, dirs, files in os.walk(sys.argv[2]): for file_name in files: full_path = os.path.join(root, file_name) print(' ' + full_path) z.write(full_path) print('uploading to dropbox...') sess = session.DropboxSession(app_key, app_secret, ACCESS_TYPE) sess.set_token(token_key, token_secret) client = client.DropboxClient(sess) response = client.put_file('/' + zip_file, open(zip_file).read(), overwrite=True, parent_rev=None) os.unlink(zip_file) print('done')
folder = r'/home/username' zipname = r'vpsbu_' zipname += str(today) zipname += r".zip" makeArchive(dirEntries(folder, True), zipname) # Get your app key and secret from the Dropbox developer website APP_KEY = 'fill here' APP_SECRET = 'fill here' # ACCESS_TYPE should be 'dropbox' or 'app_folder' as configured for your app ACCESS_TYPE = 'app_folder' sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE) # We will use the OAuth token we generated already. The set_token API # accepts the oauth_token and oauth_token_secret as inputs. sess.set_token("fill here","fill here") # Create an instance of the dropbox client for the session. This is # all we need to perform other actions client = client.DropboxClient(sess) # Let's upload a file! f = open("zipname") response = client.put_file(zipname, f) # Let's delete the local file which we just created filelist2 = [ f for f in os.listdir(".") if f.endswith(".zip") ] for f in filelist2: os.remove(f)
url = sess.build_authorize_url(request_token) #clipboard.Paste(url) print "url:", url print "Please visit this website and press the 'Allow' button, then hit 'Enter' here." raw_input() access_token = sess.obtain_access_token(request_token) print access_token print dir(access_token) print 'Key:' print access_token.key print 'Secret:' print access_token.secret ac_file = open('act.txt', 'w') ac_file.write(str(access_token.key) + '*' + str(access_token.secret)) ac_file.close() client = client.DropboxClient(sess) if args.status: print "Account info:".format(args.filename) print "linked account:", client.account_info() filename = args.filename if filename: print 'uploading file' print filename upload_file = open(filename, 'rb') response = client.put_file(filename, upload_file) print "uploaded:", response
def db_client_update_file(client, filename, file): try: metadata = client.metadata(filename)['rev'] except Exception: metadata = None client.put_file(filename, file, parent_rev=metadata)