conn.close() # Create an instance of a Dropbox class, which can make requests to the API. dbx = dropbox.Dropbox(TOKEN) # Check that the access token is valid try: dbx.users_get_current_account() except AuthError: exit("ERROR: Invalid access token; try re-generating an " "access token from the app console on the web.") message = '' # Open file as binary for reading with open(LOCALFILE, 'rb') as f: try: # Tries to upload the file dbx.files_upload(f.read(), BACKUPPATH, mode=WriteMode('overwrite')) message = 'Backup done!' except ApiError: # This checks for the specific error where a user doesn't have # enough Dropbox space quota to upload this file if (err.error.is_path() and err.error.get_path().reason.is_insufficient_space()): message = "ERROR: Cannot back up; insufficient space." elif err.user_message_text: message = err.user_message_text else: message = err # Insert backup event on database conn = sqlite3.connect(DATABASE) conn.execute("PRAGMA foreign_keys = ON")
def uploadToDropbox(path): dbx = dropbox.Dropbox(os.environ.get('DROPBOX_ACCESS_TOKEN')) response = dbx.files_upload(getPicture(path), '/knowit-18/' + path, mode=WriteMode('overwrite', None))
def update_file(self, access_token, path, text): dbx = dropbox.Dropbox(access_token) metadata = dbx.files_upload(text, path, WriteMode('overwrite')) return convert_metadata(metadata)
def uploadLog(dbx): with open('pomo-log.txt', 'rb') as f: print("Uploading log to your Dropbox...") dbx.files_upload(f.read(), LOGPATH, mode=WriteMode('overwrite')) print("Done!")
def uploadFile(this, file): with open(file, 'rb') as f: this.dbx.files_upload(f.read(), '/' + file, mode=WriteMode('overwrite')) print("Uploaded " + file)
def upload_file(self, file_from, file_to): dbx = dropbox.Dropbox(self.access_token) with open(file_from, 'rb') as f: dbx.files_upload(f.read(), file_to, mode=WriteMode('overwrite')) print('File Moved.')
def final_update(self, final_score, song_name, user_name): #計算各分項分數 all_note_score = [] all_bit_score = [] all_tempo_score = [] for item in final_score: all_note_score.append(item[0]) all_bit_score.append(item[1]) all_tempo_score.append(item[2]) print(sum(all_note_score)) print(sum(all_bit_score)) print(sum(all_tempo_score)) score = (sum(all_note_score) + sum(all_bit_score) + sum(all_tempo_score)) * 25 / len(final_score) + 25 print(score) score = score // 1 #顯示分數 label_score_text = tk.Label(root, text='分數', font=('Arial', 28)) label_score_text.place(x=60, y=600) label_score = tk.Label(root, text=score, font=('Arial', 28)) label_score.place(x=60, y=690) #標出錯音 dbx.files_download_to_file('temp/output.txt', '/i_Piano/' + song_name + '.txt') with open('temp/output.txt', 'rb') as fp: rec = pickle.load(fp) sheet_img = cv2.imread("temp/dst_image.png", 3) for index, note_score in enumerate(final_score): if sum(note_score) > 2: continue elif sum(note_score) == 2: rec[index].draw(sheet_img, (240, 250, 255), 2) elif sum(note_score) >= 1: rec[index].draw(sheet_img, (180, 204, 255), 2) elif sum(note_score) < 1: rec[index].draw(sheet_img, (125, 168, 255), 2) # sheet_img = cv2.imread('temp/mistake_note.png') cv2.imshow('mistake note', sheet_img) # cv2.imwrite('temp/mistake_note.png', sheet_img) #更新user成績 temp_song_score['user_name'] = [user_name] temp_song_score['score'] = [score] try: dbx.files_download_to_file('temp/song_score.csv', '/i_Piano/' + song_name + '.csv') df = pd.read_csv('temp/song_score.csv', index_col=False) df_temp = pd.DataFrame.from_dict(temp_song_score) df = df.append(df_temp) df.to_csv('temp/song_score.csv', encoding="utf_8_sig", index=False) except: df = pd.DataFrame.from_dict(temp_song_score) df.to_csv('temp/song_score.csv', encoding="utf_8_sig", index=False) #上傳user分數檔案 with open('temp/song_score.csv', 'rb') as f: dbx.files_upload(f.read(), '/i_Piano/' + song_name + '.csv', mode=WriteMode('overwrite')) #劃出分析圖 analysis_bar = [ sum(all_note_score), sum(all_bit_score), sum(all_tempo_score) ] bar_column = ['Note', 'Bit', 'Value'] plt.bar(bar_column, analysis_bar) plt.ylabel('score') plt.show()
def backup(self): with open(self.localPath, "rb") as f: self.dbx.files_upload(f.read(), self.backupPath, mode=WriteMode("overwrite")) self.logger.info("Backed up {0} to dropbox {1}".format(self.localPath, self.backupPath))
def upload_file(path, file_name): try: with open(path, 'rb') as local_file: dropbox_path = './' + file_name dropbox_api = dropbox.Dropbox(DROPBOX_TOKEN) response = dropbox_api.files_upload(local_file.read(), dropbox_path, mode=WriteMode('overwrite')) return response except ApiError as err: if (err.error.is_path() and err.error.get_path().error.is_insufficient_space()): sys.exit("ERROR: Cannot back up; insufficient space.") elif err.user_message_text: print(err.user_message_text) sys.exit() else: print(err) sys.exit() except Exception as e: print(str(e)) return None
def upload_data(data, dropbox_path): dbx.files_upload(data, dropbox_path, mode=WriteMode('overwrite'))
def upfile(i): with open(files.format(i), 'rb') as f: dbx.files_upload(f.read(), '/home/Hinh{0}.jpeg'.format(i), mode=WriteMode('overwrite'))
def upload_file(local_path, dropbox_path): with open(local_path, 'rb') as f: dbx.files_upload(f.read(), dropbox_path, mode=WriteMode('overwrite'))
from dropbox.files import WriteMode TOKEN_DICT = [l for l in csv.DictReader(open('tokens.csv', 'r'))][0] DROPBOX_TOKEN = TOKEN_DICT['dropbox'] db = dropbox.Dropbox(DROPBOX_TOKEN) MODS = {'wyreyote', 'teamfortress', 'plusreed', 'pixxo', 'radookal', 'pawjob'} # not PEP8 compliant but idc is_mod = lambda name: name.lower() in MODS clean = lambda s: str.strip(re.sub('/[@\w]+\s+', '', s + ' ', 1) ) # strips command name and bot name from input db_pull = lambda name: db.files_download_to_file(name, '/' + name) db_push = lambda name: db.files_upload( open(name, 'rb').read(), '/' + name, mode=WriteMode('overwrite')) db_make = lambda name: db.files_upload( open(name, 'rb').read(), '/' + name, mode=WriteMode('add')) add_s = lambda n: 's' if n != 1 else '' re_url = lambda s: re.sub( r'(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|' r'(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘' r'’]))', '', s) re_name = lambda s: re.sub('@\w+', '', s) def build_menu(buttons, n_cols, header_buttons=None, footer_buttons=None): menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)] if header_buttons: menu.insert(0, header_buttons) if footer_buttons:
while(msg != nome+': /quit'): msg = raw_input() msg = nome+': '+ msg dbx.files_download_to_file(saida, '/sdi_aluno8/'+ saida) with open(saida, 'a') as arq: arq.write(msg) arq.write('\n') dbx.files_upload(open(saida).read(),'/sdi_aluno8/' + saida, mode=WriteMode('overwrite')) nome = raw_input('Nome: ') saida = 'f-saida_'+nome+'.txt' ent = 'f-ent_'+nome+'.txt' #dbx.files_download_to_file('TEST.txt', '/sdi_aluno8/'+ 'TEST.txt') dbx.files_upload('', '/sdi_aluno8/' + saida, mode=WriteMode('overwrite')) dbx.files_upload('', '/sdi_aluno8/' + ent, mode=WriteMode('overwrite')) dbx.files_download_to_file(saida, '/sdi_aluno8/'+ saida) dbx.files_download_to_file(ent, '/sdi_aluno8/'+ ent) # opt = 0 # while(opt != 3): # opt = input('[1]Enviar mensagem\n[2]Receber mensagems\n[3]Sair\n') # if(opt == 1): #escreve a mensagem na saida # dbx.files_download_to_file(saida, '/sdi_aluno8/'+ saida) # msg = raw_input('Mensagem: ') # msg = nome+': '+ msg # with open(saida, 'a') as arq: # arq.write(msg) # arq.write('\n')
def processLBCSubmission(sub): try: # if not in db, add to db if not sqlSelectRows("tblFormSubs", "xml_id = '" + sub['xml_id'] + "'"): # parse data from submission emptyDic = {} fileUrls = {} for f in sub['fields']: if f['fieldid'] in fieldIds and f['fieldvalue'] != "": fieldName = fieldIds[f['fieldid']] if fieldName == 'bank_statement' or fieldName == 'selfie' or fieldName == 'note': fileUrls[fieldName] = f['fieldvalue'] else: emptyDic[fieldName] = f['fieldvalue'].strip() if fieldName == 'firstName' or fieldName == 'lastName' or fieldName == 'streetAddress' or fieldName == 'city': emptyDic[fieldName] = string.capwords( emptyDic[fieldName]) emptyDic['xml_id'] = sub['xml_id'] emptyDic['cc'] = sub['cc'] emptyDic['date'] = sub['date'] emptyDic['ip'] = sub['ip'] emptyDic['date'] = sub['datestart'] emptyDic['ref_id'] = sub['refid'] if 'lbcRef' in emptyDic: trade = sqlSelectRows( "tblClosedTrades", "reference = '" + emptyDic['lbcRef'] + "'") if len(trade) == 0: trade = sqlSelectRows( "tblClosedTrades", "transaction_id = '" + emptyDic['lbcRef'] + "'") else: trade = [] # find customer lbc username from trade db if len(trade) > 0: emptyDic['lbcUsername'] = str(trade[0]['customer_is']) customer = sqlSelectRows( "tblLBCCustomers", "username = '******'lbcUsername'] + "'")[0] now = str(datetime.datetime.now()) sqlAddRow( "tblReminders", { 'type': 'Docs Uploaded', 'reference': trade[0]['transaction_id'], 'created_at': now, 'timestamp': now }) else: emptyDic['lbcUsername'] = "" for key in emptyDic: emptyDic[key] = asciifyString(emptyDic[key]).replace( "'", "").replace('"', '') if trade: sqlUpdateRows('tblLBCCustomers', 'username = "******"', {'form_id': emptyDic['ref_id']}) # add the new submission to db sqlAddRow("tblFormSubs", emptyDic) subId = sqlSelectRows("tblFormSubs", "ref_id = '" + emptyDic['ref_id'] + "'")[0]['id'] # send confirmation message to telegram message = "NEW DOCS ON DROPBOX:" message += "\nIMPORTANT. Make sure the following details match documents: " message += "\nName: " + emptyDic['firstName'] + " " + emptyDic[ 'lastName'] message += "\nDOB: " + emptyDic['dob'] if emptyDic['lbcUsername']: message += "\nUsername: "******"\nLBC name: " + str(customer['real_name']) message += "\nTrade Amount: " + str(trade[0]['fiat_amount']) else: message += "\nRef: " + emptyDic['lbcRef'] message += "\n/sendBankDetails" + str(subId) print(message) telegramSendMessage(message, "docUpload") #add email address to mailchimp try: d = addMailChimpSub(emptyDic['email'], emptyDic['firstName'], emptyDic['lastName']) except NameError: # email address has already been added to mailchimp print('Email has already been added to MailChimp: ' + str(emptyDic['email'])) # send confirmation email to email address try: d = sendMailChimpEmail('25214feb7a', '38605340f2', emptyDic['email']) except NameError: # email has already been sent to email address print('Email has already been sent to: ' + str(emptyDic['email'])) #### now move docs to dropbox #fileUrls = [emptyDic['bankStatement'], emptyDic['selfie'], emptyDic['note']] folder_name = emptyDic['firstName'] + " " + emptyDic['lastName'] file_name = emptyDic['firstName'] + "_" + emptyDic['lastName'] docNum = 1 print("Moving files for " + folder_name + " to dropbox") try: # find out if there is already a folder with that name files = dbx.files_list_folder('/' + destination_folder + '/' + folder_name) docNum = len(files.entries) + 1 except AttributeError: docNum = 1 # download all the files attached in the form sub for fileType in fileUrls: f = requests.get(fileUrls[fileType], allow_redirects=True) # find file name (with file ext in it) session = requests.Session() response = session.head(fileUrls[fileType]) contentType = response.headers['content-disposition'] # find ext type of file ext = '' for extType in lstExt: if extType in contentType.lower(): ext = extType if not ext: telegramSendMessage( 'No extension type found for form sub ' + emptyDic['lbcUsername'] + '. Find out wtf is going on', 'error') continue # saving file to comp file = "C:/customer_docs/" + file_name + "_" + fileType + "_" + str( docNum) + '.' + ext.lower() open(file, 'wb').write(f.content) # uploading file to dropbox with open(file, 'rb') as f: print("Uploading " + file + " to " + folder_name) upload_location = '/' + destination_folder + '/' + folder_name + '/' + file_name + "_" + fileType + "_" + str( docNum) + '.' + ext.lower() dbx.files_upload(f.read(), upload_location, mode=WriteMode('overwrite')) # then delete from comp (don't know if can upload straight from python or need to save to hard disk first as above?) os.remove(file) docNum += 1 except Exception as e: errorMessage = 'ERROR sorting LBC submissions' errorMessage += '\n' + str(e) print(errorMessage) telegramSendMessage(errorMessage, 'errors')
def upload_to_dropbox(dbx): with open(LOCAL_FEED_FILE, "rb") as f: print("Uploading feed file to Dropbox ...") dbx.files_upload(f.read(), REMOTE_FEED_FILE, mode=WriteMode("overwrite"))
def upload_file(title, use_base_path=True): print 'Uploading {} at {}'.format(title, DROPBOX_BASE_PATH) path = LOCAL_BASE_PATH + title if use_base_path else title with open(path, 'rb') as f: response = db.files_upload(f.read(), DROPBOX_BASE_PATH + title, mode=WriteMode('overwrite'))
def send_alert(self, alert, alert_time, name): self.dbx.files_upload(alert.encode('utf-8'), self.alerts_folder + alert_time + name, mode=WriteMode('add'))
return time.sleep(0.1) def escrita(): global msg while (msg != name + ': /quit'): msg = input() msg = name + ': ' + msg dbx.files_download_to_file(output, '/Client/' + output) with open(output, 'a') as arq: arq.write(msg) arq.write('\n') dbx.files_upload(open(output).read().encode(), '/Client/' + output, mode=WriteMode('overwrite')) name = input('Nome: ') output = 'f-saida_' + name + '.txt' inp = 'f-ent_' + name + '.txt' dbx.files_upload(''.encode(), '/Client/' + output, mode=WriteMode('overwrite')) dbx.files_upload(''.encode(), '/Client/' + inp, mode=WriteMode('overwrite')) dbx.files_download_to_file(output, '/Client/' + output) dbx.files_download_to_file(inp, '/Client/' + inp) leitura_ = Thread(target=leitura) leitura_.start() escrita()
def process_user(account): ''' Call /files/list_folder for the given user ID and process any changes. ''' print("PROCESS_USER...") # OAuth token for the user token = redis_client.hget('tokens', account) print("token: ", token) # cursor for the user (None the first time) cursor = redis_client.hget('cursors', account) print("cursor: ", cursor) output_file_extension = ".csv" input_file_extensions = [".bak", ".tsv"] processed_marker = "_cleaned" dbx = Dropbox(token.decode()) has_more = True while has_more: print("has more: ", has_more) if cursor is None: print("cursor is 'None'!") result = dbx.files_list_folder(path='') print("result: ", result) else: result = dbx.files_list_folder_continue(cursor.decode()) print("result: ", result) for entry in result.entries: print("entry: ", entry) # yapf: disable if ( isinstance(entry, DeletedMetadata) or isinstance(entry, FolderMetadata) or not any(entry.path_lower.endswith(e) for e in input_file_extensions) ): # yapf: enable print("skipping.") continue _, resp = dbx.files_download(entry.path_lower) print("processing data...") processed_data = clean_data(resp.content) dbx.files_upload( processed_data, entry.path_lower[:-4] + processed_marker + output_file_extension, mode=WriteMode('add')) #mode=WriteMode('overwrite')) # Update cursor cursor = result.cursor redis_client.hset('cursors', account, cursor) # Repeat only if there's more to do has_more = result.has_more
try: meta = dbx.files_get_metadata(file.replace(mainPath, '/')) print("arquivo existe!") except: print("arquivo não existe!") # with open("." + file, 'rb') as f: with open(os_path, 'rb') as f: # if meta == None or meta.size != file_size: if meta == None or meta.size != os.path.getsize(os_path): print("arquivo diferente, fazendo a sincronização!") print() if file_size <= CHUNK_SIZE: try: dbx.files_upload(f.read(), os_path.replace(mainPath, '/'), mode=WriteMode('overwrite')) # dbx.files_upload(f.read(), file.replace(mainPath, '/'), mode=WriteMode('overwrite')) except ApiError as err: # This checks for the specific error where a user doesn't have enough Dropbox space quota to upload this file if (err.error.is_path() and err.error.get_path().error.is_insufficient_space() ): sys.exit("ERROR: Cannot back up; insufficient space.") elif err.user_message_text: print(err.user_message_text) sys.exit() else: print(err) sys.exit() else: upload_session_start_result = dbx.files_upload_session_start(
def db_upload(file, destination): with open(file, 'rb') as f: db.files_upload(f.read(), destination, mode=WriteMode('overwrite'))
def upload(dropbox_helper_id, access_token, size, max_retries): from .models import DropboxUploadHelper helper = DropboxUploadHelper.objects.get(id=dropbox_helper_id) dbx = Dropbox(access_token) try: with open(helper.src, 'rb') as f: chunk = f.read(CHUNK_SIZE) offset = len(chunk) upload_session = dbx.files_upload_session_start(chunk) while True: chunk = f.read(CHUNK_SIZE) if not chunk: break helper.progress = offset / size helper.save() dbx.files_upload_session_append_v2( chunk, UploadSessionCursor( upload_session.session_id, offset, ), ) offset += len(chunk) file_metadata = dbx.files_upload_session_finish( b'', UploadSessionCursor( upload_session.session_id, offset=offset, ), CommitInfo( '/{}'.format(os.path.basename(helper.src)), # When writing the file it won't overwrite an existing file, just add # another file like "filename (2).txt" WriteMode('add'), ), ) 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: path_link_metadata = dbx.sharing_create_shared_link_with_settings( file_metadata.path_display, SharedLinkSettings( requested_visibility=RequestedVisibility.team_only, ), ) context = { 'share_url': path_link_metadata.url, 'path': os.path.join( u'Apps', settings.DROPBOX_APP_NAME, path_link_metadata.name, ) } with localize(couch_user.get_language_code()): subject = _(u'{} 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 = _(u'{} 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, )
def backup(self): bak_file_name = self._get_fileobj_mtime(self.discobase) full_bak_path = '{}/{}'.format(self.backuppath, bak_file_name) copy_file_path = '{}/{}'.format(self.backuppath, self.discobase.name) print("Uploading as {} to {}".format(bak_file_name, self.backuppath)) if self.exists('{}/{}'.format(self.backuppath, bak_file_name)): log.warning('Backup existing. Won\'t overwrite "{}" '.format( bak_file_name)) #log.info('Exixting backup metadata: {}'.format( # self.dbx.files_get_metadata(full_bak_path))) else: print('Backup not existing yet, uploading ...') with open(self.discobase, 'rb') as f: try: self.dbx.files_upload( f.read(), full_bak_path, mode=WriteMode('overwrite'), client_modified=self._get_local_mtime_dt( self.discobase)) m_success = 'Dropbox_sync.backup: File successfully backuped ' m_success += 'or already up to date.' log.debug(m_success) except ApiError as err: # This checks for the specific error where a user doesn't have # enough Dropbox space quota to upload this file if (err.error.is_path() and err.error.get_path().reason. is_insufficient_space()): log.error( 'Cannot back up; insufficient space. Quitting.') raise SystemExit(1) elif err.user_message_text: print(err.user_message_text) raise SystemExit(1) else: print(err) raise SystemExit(1) # make a copy of the just uploaded file, named without date! # this eases accessing the latest discobase for other apps if self.exists(copy_file_path): m_exists = 'Dropbox_sync.backup: Latest discobase file ' m_exists += 'already existing, checking client_modified times.' log.info(m_exists) mod_time_bak = self.get_client_modified(full_bak_path) mod_time_copy = self.get_client_modified(copy_file_path) if mod_time_bak <= mod_time_copy: m_newer = 'Dropbox_sync.backup: Timestamp of latest discobase ' m_newer += 'file is newer than or the same as just uploaded file. ' m_newer += 'Not overwriting.' log.info(m_newer) else: m_older = 'Dropbox_sync.backup: Timestamp of latest discobase ' m_older += 'file is older than just uploaded file. Overwriting!' log.info(m_older) self.delete(copy_file_path) self.copy(full_bak_path, copy_file_path) else: m_not_existing = 'Dropbox_sync.backup: Latest discobase ' m_not_existing += 'file is not existing yet, copying.' log.info(m_not_existing) self.copy(full_bak_path, copy_file_path) # in any case, show list of existing backups self.show_backups() return True
def store(self, fileobj, filename): self.client.files_upload(fileobj.read(), self._full_path(filename), mode=WriteMode(self.write_mode)) return filename
counter = 0 try: print('scraping cattle exchange now') listings = scrape() print('getting cattle listings') get_listings_text(listings) print('scrape is complete') except: print('exception occured') # upload to one drive folder with open(listings, 'rb') as f: dest_path = datetime.datetime.today().strftime('%d-%m-%Y') dest_path = '/Cowbell/{}_listings.txt'.format(dest_path) try: client.files_upload(f.read(), dest_path, mode=WriteMode('add')) except ApiError: print('API Error occured') times = 28800 print('Seconds to next post') while times != 0: if times % 900 == 0: print(times) time.sleep(1) times -= 1 try: post() counter += 1 except: print('Post failed')
def load(self, name, path_in_pc, path_in_drp): tmp = str(name) with open(path_in_pc, 'rb') as f: self.dbx.files_upload(f.read(), path_in_drp + tmp + '.png', mode=WriteMode('overwrite'))
def upload(cls, file, name, metadata=""): dbx = dropbox.Dropbox(os.environ["DROPBOX_TOKEN"]) dbx.files_upload(file.read(), "/%s" % name, mode=WriteMode('overwrite')) return DropboxUpload.objects.create(name=name, metadata=metadata)