def package_and_upload(): g_login = GoogleAuth() g_login.LoadCredentialsFile("mycreds.txt") name = datetime.now().strftime("%d/%m/%Y-%H:%M:%S") + '.tar.gz' os.system('tar -czvf ' + name + ' history*') os.system('rm history*') if g_login.credentials is None: # Authenticate if they're not there log = open("cam.log", "a") log.write("Token failed, we need to manual auth") log.close() g_login.GetFlow() g_login.flow.params.update({'access_type': 'offline'}) g_login.flow.params.update({'approval_prompt': 'force'}) g_login.LocalWebserverAuth() elif g_login.access_token_expired: # Refresh them if expired g_login.Refresh() else: # Initialize the saved creds g_login.Authorize() # Save the current credentials to a file g_login.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(g_login) with open(name, "r") as file: file_drive = drive.CreateFile({'title': os.path.basename(file.name)}) file_drive.SetContentString(file.read()) file_drive.Upload() os.system('rm ' + name)
def authenticate_Grive(): from google.colab import auth gauth = GoogleAuth() credential_file_path = os.path.join(os.path.dirname(utils.BASE_PATH), 'mycredentials.txt') if not os.path.exists(credential_file_path): # print('cred file not found') auth.authenticate_user() gauth.credentials = GoogleCredentials.get_application_default() gauth.SaveCredentialsFile(credential_file_path) gauth.LoadCredentialsFile(credential_file_path) if gauth.credentials is None: # print('None') gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.LocalWebserverAuth() # gauth.credentials = GoogleCredentials.get_application_default() elif gauth.access_token_expired: # print('Expired') gauth.Refresh() else: # print('Authorize') gauth.Authorize() # auth.authenticate_user() gauth.SaveCredentialsFile(credential_file_path) return gauth
async def the_drive() -> Any: """ Gets the GoogleDrive connection. """ gauth = GoogleAuth() # gauth.LocalWebserverAuth() gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: # This is what solved the issues: gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) # Authenticate if they're not there gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(gauth) return drive
def getGDrive(clientSecretPath): tmpCredsPath = os.getenv("TMP_SECRET_PATH") if( tmpCredsPath is None ): tmpCredsPath = "gdrive_secrets.bin" gauth = GoogleAuth() gauth.LoadClientConfigFile(clientSecretPath) #try to load saved client credetials gauth.LoadCredentialsFile(tmpCredsPath) if gauth.credentials is None: gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() drive = GoogleDrive(gauth) gauth.SaveCredentialsFile(tmpCredsPath) return drive
def start_auth_telegram(self, client_config): if self.telegram_bot is None: t.log_message('telegram bot is None. Telegram auth canceled.') return auth = GoogleAuth() auth.LoadClientConfigFile(client_config_file=client_config) if auth.flow is None: auth.GetFlow() auth.flow.redirect_uri = OOB_CALLBACK_URN self.telegram_bot.send_message( 'Please go to the following link in your browser and send me a Google verification code. \nAuth url: ' + auth.GetAuthUrl()) dirty = False code = None save_credentials = auth.settings.get('save_credentials') if auth.credentials is None and save_credentials: auth.LoadCredentials() if auth.credentials is None: code = self.telegram_bot.get_code() dirty = True else: if auth.access_token_expired: if auth.credentials.refresh_token is not None: auth.Refresh() else: code = self.telegram_bot.get_code() dirty = True if code is not None: auth.Auth(code) if dirty and save_credentials: auth.SaveCredentials() return auth
def user_find(): from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: # Authenticate if they're not there # This is what solved the issues: gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(gauth) with open(r'./txtfiles/recipient.txt', 'r') as rec: username = rec.readline() folderList = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for fold in folderList: if (fold['title'] == 'User_list'): foldID = fold['id'] break filelist = drive.ListFile({ 'q': "'" + foldID + "' in parents and trashed=false" }).GetList() y = 0 for fil in filelist: if (fil['title'] == username + '.txt'): fileID = fil['id'] y = 1 break if y == 1: from Drive_Kryp_Interaction import crypt_implement return (crypt_implement.Krypt().encrypt_message()) elif (y == 0): import os os.remove(r'./txtfiles/message.txt') os.remove(r'./txtfiles/recipient.txt') return False
def authenticate(): gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: # Authenticate if they're not there # This is what solved the issues: gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() gauth.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(gauth) return drive
def launch(code: str): gauth = GoogleAuth() gauth.GetFlow() gauth.flow.redirect_uri = "http://localhost:8000/launch/" gauth.Auth(code) drive = GoogleDrive(gauth) trio.run(fns_process_files, drive) return "success"
def Uploader(file, folder): from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: # Authenticate if they're not there # This is what solved the issues: gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(gauth) fileList = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() x = 0 for fold in fileList: if (fold['title'] == folder): folderID = fold['id'] x = 1 break if (x == 0 and folder == 'root'): folderID = 'root' elif (x == 0): folder1 = drive.CreateFile({ 'title': folder, 'mimeType': 'application/vnd.google-apps.folder' }) folder1.Upload() folderID = folder1['id'] file1 = drive.CreateFile({'parents': [{'id': folderID}]}) file1.SetContentFile(r"./txtfiles/" + file) file1['title'] = file file1.Upload()
def upload(clients_secrets_path, files_folder, creds_file, notebook, notebook_training): # Login to Google Drive and create drive object try: GoogleAuth.DEFAULT_SETTINGS["client_config_file"] = str( clients_secrets_path) except FileNotFoundError as e: print("Please provide correct name of secrets file.") raise e gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile(creds_file) if gauth.credentials is None: # Authenticate if they're not there # This is what solved the issues: gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile(creds_file) drive = GoogleDrive(gauth) # Create folder on Google Drive to store files from given directory folder_metadata = { 'title': files_folder, 'mimeType': 'application/vnd.google-apps.folder' } folder = drive.CreateFile(folder_metadata) folder.Upload() folderid = folder['id'] for file in listdir_nohidden(files_folder): with open(file, "r") as f: fn = os.path.basename(f.name) file_drive = drive.CreateFile({ 'title': fn, "parents": [{ "kind": "drive#fileLink", "id": folderid }] }) file_drive.SetContentString(f.read()) file_drive.Upload() print(f"The file: {fn} has been uploaded") if notebook: file_train = drive.CreateFile({'title': notebook_training}) file_train.SetContentFile(notebook_training) file_train.Upload() print(f"The file: {notebook_training} has been uploaded")
def Downloader(file, folder): from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() # Try to load saved client credentials #username_Pu_key #Download_pukey gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: # Authenticate if they're not there # This is what solved the issues: gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(gauth) folderlist = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for fold in folderlist: if (fold['title'] == folder): foldID = fold['id'] break filelist = drive.ListFile({ 'q': "'" + foldID + "' in parents and trashed=false" }).GetList() for fil in filelist: if (fil['title'] == file): fileID = fil['id'] break file1 = drive.CreateFile({'id': fileID}) file1.GetContentFile(r"./txtfiles/" + file)
def process_new_meme(folder, channel_name): try: print(f"PROCESSING FOLDER {folder} CHANNEL {channel_name}") gauth = GoogleAuth() gauth.LoadCredentialsFile("creds.txt") if gauth.credentials is None: gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() gauth.SaveCredentialsFile("creds.txt") drive = GoogleDrive(gauth) file_list = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() memes_folder_id = None for file1 in file_list: if file1['title'] == folder: memes_folder_id = file1['id'] break if not memes_folder_id: print(f"{folder} FOLDER NOT FOUND") else: memes_list = drive.ListFile({ 'q': f"'{memes_folder_id}' in parents and trashed=false" }).GetList() for meme in memes_list: print(f"title: {meme['title']}, id: {meme['id']}") selected_meme = random.choice(memes_list) meme_file = drive.CreateFile({'id': selected_meme['id']}) meme_file.GetContentFile("./memes/" + selected_meme['title']) send_meme("./memes/" + selected_meme['title'], channel_name) os.remove("./memes/" + selected_meme['title']) except Exception as e: print(e)
def upload_to_drive(filename): gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile("oauthcreds.txt") if gauth.credentials is None: # Authenticate if they're not there # TODO Move to master # https://stackoverflow.com/a/55876179 # This is what solved the issues: gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("oauthcreds.txt") drive = GoogleDrive(gauth) # https://stackoverflow.com/a/22934892 # https://stackoverflow.com/a/40236586 drive_file = drive.CreateFile({ 'title': filename, "parents": [{ "kind": "drive#fileLink", "id": "1mqZ2DkpPghC6N04Qt8WcMKBa_hN3PKv9" }] }) # Read file and set it as a content of this instance. drive_file.SetContentFile("paly_from_8th.xlsx") drive_file.Upload() # Upload the file.
def getGDrive(self): gauth = GoogleAuth() gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() gauth.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(gauth) return drive
def sendFileToCloud(runmotiondetection_queue, deletefile_queue): #Login to Google Drive and create drive object gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: # Authenticate if they're not there # This is what solved the issues: gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(gauth) while True: file_path = runmotiondetection_queue.get() print(" sending file to cloud " + file_path, flush=True) with open(file_path, "r", encoding='ansi') as file: file_drive = drive.CreateFile( {'title': os.path.basename(file.name)}) file_drive.SetContentFile(file.name) file_drive.Upload() print(" file uploaded", flush=True) deletefile_queue.put(file_path)
def set_up_drive(settings_file, credentials_file): print( f'Settings File Location: {settings_file} Credentials File Location: {credentials_file}' ) gauth = GoogleAuth(settings_file=settings_file) # Try to load saved client credentials gauth.LoadCredentialsFile(credentials_file) if gauth.credentials is None: # Authenticate if they're not there gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile(credentials_file) return GoogleDrive(gauth)
def show(request): name = None link = None if request.method == 'POST': print("hello") title = request.POST.get('title') gauth = GoogleAuth() gauth.LoadCredentialsFile("credentials.txt") if gauth.credentials is None: gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() gauth.SaveCredentialsFile("credentials.txt") drive = GoogleDrive(gauth) file_list = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for item in file_list: if item['title'] == title: link = 'https://drive.google.com/file/d/' + item[ 'id'] + '/view?usp=drivesdk' name = item['title'] break return render(request, 'Voice/patient_record.html', {'result': { 'name': name, 'link': link }})
def to_google(): gauth = GoogleAuth() gauth.GetFlow() gauth.flow.redirect_uri = "http://localhost:8000/launch/" auth_url = gauth.GetAuthUrl() hug.redirect.to(auth_url)
def pdf(request): if request.method == 'POST': name = request.POST.get('name') address = request.POST.get('address') age = request.POST.get('age') contact = request.POST.get('contact') symptom = request.POST.get('symptom') daignosis = request.POST.get('daignosis') medication = request.POST.get('medication') p = canvas.Canvas(f'{dat[0]}.pdf') p.setFont("Times-Roman", 24) p.drawString(400, 800, "Dr. Octocat") p.drawString(400, 775, "MBBS") p.drawImage("datafiles/logo.png", 45, 740, width=100, height=100) p.setFont("Times-Roman", 18) p.drawString( 0, 730, "_____________________________________________________________________" ) now = datetime.now() today = date.today() d2 = today.strftime("%B %d, %Y") current_time = now.strftime("%H:%M:%S") p.drawString(50, 695, f"Date : {d2}") p.drawString(400, 695, f"Time : {current_time}") p.drawString( 0, 680, "_____________________________________________________________________" ) p.drawString(100, 650, f"Name : {dat[0]}") p.drawString(100, 620, f"Addres : {dat[1]}") p.drawString(100, 590, f"Age : {dat[2]}") p.drawString(100, 560, f"Contact No. : {dat[3]}") p.drawString(100, 530, f"Symptoms : {dat[4]}") p.drawString(100, 500, f"Daignosis : {dat[5]}") p.drawString(100, 470, f"Medication : {dat[6]}") p.drawImage("media/images/sign.png", 400, 200, width=100, height=100) p.drawString(400, 180, "Doctor's Signature") p.showPage() p.save() gauth = GoogleAuth() gauth.LoadCredentialsFile("credentials.txt") if gauth.credentials is None: gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() gauth.SaveCredentialsFile("credentials.txt") drive = GoogleDrive(gauth) file = drive.CreateFile({'title': f"{dat[0]}"}) file.SetContentFile(f'{dat[0]}.pdf') file.Upload() result = None file_list = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for item in file_list: if item['title'] == f'{dat[0]}': result = 'https://drive.google.com/file/d/' + item[ 'id'] + '/view?usp=drivesdk' break qr = qrcode.QRCode() qr.add_data(result) qr.make() img = qr.make_image() img.save('assets/qrcode.png') return render(request, 'Voice/Last.html')
class DriveAccessor(object): def __init__(self, mainID, backupID, queueID): self.ANIMEMES_FOLDER_ID = mainID self.BACKUP_FOLDER_ID = backupID self.QUEUE_FOLDER_ID = queueID self.gauth = GoogleAuth() self.gauth.LoadCredentialsFile(CREDENTIALS_PATH) self.authorize() self.drive = GoogleDrive(self.gauth) def authorize(self): if self.gauth.credentials is None: print(NO_CREDENTIALS_MSG) self.gauth.GetFlow() self.gauth.flow.params.update(ACCESS_TYPE_DICT) self.gauth.flow.params.update(APPROVAL_PROMPT_DICT) self.gauth.LocalWebserverAuth() elif self.gauth.access_token_expired: print(EXPIRED_CREDS_MSG) self.gauth.Refresh() print(REFRESHED_CREDS_MSG) else: print(VALID_CREDS_MSG) self.gauth.Authorize() self.gauth.SaveCredentialsFile(CREDENTIALS_PATH) def getMeme(self): print(INIT_DOWNLOAD_MSG) fileList = self.drive.ListFile({ 'q': self.getFileQuery(self.QUEUE_FOLDER_ID) }).GetList() # Queued Folder is empty, use regular meme folder and shuffle if not fileList: print(EMPTY_QUEUE_MSG) fileList = self.drive.ListFile({ 'q': self.getFileQuery(self.ANIMEMES_FOLDER_ID) }).GetList() shuffle(fileList) imgPattern = re.compile("image.*") for file in fileList: if imgPattern.match(file["mimeType"]): imgName = file["title"] print(GOT_IMAGE_MSG, imgName) self.imgFile = self.drive.CreateFile({'id': file['id']}) self.imgFile.GetContentFile(imgName) return imgName return None def backupMeme(self, imgName): print(BACKUP_IMAGE_MSG) backupFile = self.drive.CreateFile({ "parents": [{ "kind": "drive#fileLink", "id": self.BACKUP_FOLDER_ID }] }) backupFile.SetContentFile(imgName) backupFile.Upload() self.imgFile.Delete() def getFileQuery(self, folderID): return ("'" + folderID + "' in parents and trashed=false")
def user_add(): from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: # Authenticate if they're not there # This is what solved the issues: gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(gauth) with open(r'./txtfiles/sender.txt', 'r') as u: username = u.read() fileList = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() x = 0 for fold in fileList: if (fold['title'] == 'User_list'): foldID = fold['id'] x = 1 break if x == 0: folder1 = drive.CreateFile({ 'title': 'User_list', 'mimeType': 'application/vnd.google-apps.folder' }) folder1.Upload() foldID = folder1['id'] file1 = drive.CreateFile({ 'title': username + '.txt', 'parents': [{ 'id': foldID }] }) file1.Upload() from Drive_Kryp_Interaction import crypt_implement crypt_implement.Krypt().generate()
# Auxiliary functions for uploading recordings to google drive fl = open('api.txt', 'r') apis = fl.readlines() zoomRecordingsFolderId = apis[6].replace("\n", "") # to get folder id, run getFolderId function below and place it at line 7 of api.txt # place google drive api client_secrets.json under same directory gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: # Authenticate if they're not there gauth.GetFlow() gauth.flow.params.update({'access_type': 'offline'}) gauth.flow.params.update({'approval_prompt': 'force'}) gauth.CommandLineAuth() # gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(gauth)
class DriveManager: def __init__(self): """Create an instance of UploadDrive.""" self.gauth = GoogleAuth() self.connect() self.drive = GoogleDrive(self.gauth) def connect(self): """Connect to the drive with the flow """ # https: // github.com / gsuitedevs / PyDrive / issues / 104 self.gauth.LoadCredentialsFile("mycreds.txt") if self.gauth.credentials is None: # Authenticate if they're not there self.gauth.GetFlow() self.gauth.flow.params.update({'access_type': 'offline'}) self.gauth.flow.params.update({'approval_prompt': 'force'}) self.gauth.LocalWebserverAuth() elif self.gauth.access_token_expired: # Refresh them if expired self.gauth.Refresh() else: # Initialize the saved creds self.gauth.Refresh() # Save the current credentials to a file self.gauth.SaveCredentialsFile("mycreds.txt") def write_file_on_cloud(self, path, title="values.csv"): """Create GoogleDriveFile instance :param path: path of the file :type path: str :param title: title in google drive :type title: str """ self.connect() file1 = self.drive.CreateFile() file1.SetContentFile(path) file1['title'] = title file1.Upload() # Auto-iterate through all files that matches this query def find_file_title_on_cloud(self, title=''): """find a given file by its title on the cloud :param title:The title of the text file :type title: str :return file_id """ self.connect() file_list = self.drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for file in file_list: print('title: %s, id: %s' % (file['title'], file['id'])) if file['title'] == title: print('found : ' + title) return file['title'] print('file not found : ' + title) return 404 def find_file_id_on_cloud(self, title=''): """Find a file by its id on the cloud :param title:The title of the text file :type title: str :return file_id """ # results=service.files().list().execute() # file_list=results.get('items',[]) self.connect() file_list = self.drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for file in file_list: print('title: %s, id: %s' % (file['title'], file['id'])) if file['title'] == title: print('found : ' + title) return file['id'] return 404 def download_file_from_cloud(self, file_id, path): """Download a Drive file's content to the local filesystem. :param file_id: ID of the Drive file that will downloaded. :type file_id: str :param path: where the file is written :type path: str :return if the download succeeded """ self.connect() if self.internet_on(): local_fd = open(path + "commands.csv", "wb") request = self.drive.auth.service.files().get_media(fileId=file_id) media_request = http.MediaIoBaseDownload(local_fd, request) while True: try: download_progress, done = media_request.next_chunk() except errors.HttpError as error: print('An error occurred: %s' % error) return False if download_progress: print('Download Progress: %d%%' % int(download_progress.progress() * 100)) if done: print('Download Complete') return True else: return False def delete_file_on_cloud(self, file_title): # HTTP request DELETE """Permanently delete a file, skipping the trash. :param file_title: ID of the file to delete. :type file_title: str :return if file didn't delete """ self.connect() file_list = self.drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for file in file_list: print('title: %s, id: %s' % (file['title'], file['id'])) if file['title'] == file_title: print('found : ' + file_title) self.drive.auth.service.files().delete( fileId=file['id']).execute() print('file not found : ' + file_title) return 404 @staticmethod def internet_on(): """Check if the connection to the internet works :return if there is a internet connexion """ try: urlopen('http://216.58.192.142', timeout=1) return True except URLError: return False