def login(): try: gauth = GoogleAuth() gauth.LoadCredentialsFile(CREDENTIALS) if gauth.credentials is None: gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() gauth.SaveCredentialsFile(CREDENTIALS) drive = GoogleDrive(gauth) gauth = GoogleAuth() gauth.LoadCredentialsFile(CREDENTIALS) if gauth.credentials is None: gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() gauth.SaveCredentialsFile(CREDENTIALS) return GoogleDrive(gauth) print("Connected to cloud") except ServerNotFoundError: print("Cannot connect to cloud") return True
def upload_to_drive(filename): # auth gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile(credentials_file="mycreds.txt") if gauth.credentials is None: # 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("client_secrets.json") drive = GoogleDrive(gauth) file1 = drive.CreateFile( {'title': filename}) # Create GoogleDriveFile instance with title 'Hello.txt'. file1.SetContentFile( filename) # Set content of the file from given string. file1.Upload() drive_link = '' return drive_link
def download_google_drive(client_secrets_file, google_drive_dir_name, download_dir): """mycreds.txt was got by the method in https://github.com/OuyangWenyu/aqualord/blob/master/CloudStor/googledrive.ipynb """ gauth = GoogleAuth() gauth.LoadCredentialsFile(client_secrets_file) if gauth.credentials is None: # 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(client_secrets_file) drive = GoogleDrive(gauth) dir_id = None file_list_root = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList() for file_temp in file_list_root: print('title: %s, id: %s' % (file_temp['title'], file_temp['id'])) if file_temp['title'] == google_drive_dir_name: dir_id = str(file_temp['id']) print('the id of the dir is:', dir_id) if dir_id is None: print("No data....") else: download_a_file_from_google_drive(drive, dir_id, download_dir)
def upload_drive(FolderName): global current_path gauth = GoogleAuth() gauth.LoadCredentialsFile("credentials.txt") if gauth.credentials is None: # 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("credentials.txt") drive = GoogleDrive(gauth) file = drive.CreateFile() # The followinf 3 cases can occur it has to be a file only. You can't uploa folders in google drive. So it can happen that starting letter is caps # or all letters are in caps or all are smallcase if isfile(join(current_path, str(FolderName.title()))): file.SetContentFile(join(current_path, str(FolderName).title())) elif isfile(join(current_path, str(FolderName.upper()))): file.SetContentFile(join(current_path, str(FolderName).upper())) elif isfile(join(current_path, str(FolderName.lower()))): file.SetContentFile(join(current_path, str(FolderName).lower())) file.Upload() msg = "Your file is uploaded on your drive" return question(msg)
def connect(credentials_file=None, secret_client_config=None): # Reference: http://stackoverflow.com/questions/24419188/automating-pydrive-verification-process credentials_file = credentials_file or DEFAULT_USER_CREDENTIALS_PATH secret_client_config = secret_client_config or DEFAULT_SECRET_CLIENT_PATH gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile(credentials_file or '') if gauth.credentials is None: # 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(credentials_file) global CONN if not CONN: CONN = GoogleDrive(gauth) return CONN
def authenticate_pydrive__(self): if self.mycreds_file is None: mycreds_file = 'mycreds.json' with open(mycreds_file, 'w') as f: f.write('') else: mycreds_file = self.mycreds_file gauth = GoogleAuth() # https://stackoverflow.com/a/24542604/5096199 # Try to load saved client credentials gauth.LoadCredentialsFile(mycreds_file) if gauth.credentials is None: # Authenticate if they're not there auth.authenticate_user() gauth.credentials = GoogleCredentials.get_application_default() 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_file) self.drive = GoogleDrive(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 main(): g_login = GoogleAuth() g_login.LoadCredentialsFile('mycreds.txt') g_login.Authorize() drive = GoogleDrive(g_login) folders = drive.ListFile({'q': "sharedWithMe"}).GetList() mefin = [a for a in folders if a['title'] == 'MEFIN'][0] #MEFIN folder print(mefin['id']) folders = drive.ListFile({ 'q': "'%s' in parents and trashed=false" % mefin['id'] }).GetList() #folders inside MEFIN hern = [a for a in folders if a['title'] == 'Hernandarias'][0] print(hern['id']) folders = drive.ListFile({ 'q': "'%s' in parents and trashed=false" % hern['id'] }).GetList() #folders inside hernandarias cont = [a for a in folders if a['title'] == 'Contratos'][0] print(cont['id']) folders = drive.ListFile({ 'q': "'%s' in parents and trashed=false" % cont['id'] }).GetList() #folders inside contratos #now i collect the id of the dictionaries ids = dict(zip([a['title'] for a in folders], [a['id'] for a in folders])) return ids
def authenticate(secrets, credentials): authenticator = GoogleAuth() authenticator.settings = { 'client_config_backend': 'file', 'client_config_file': secrets, 'save_credentials': False, 'oauth_scope': ['https://www.googleapis.com/auth/drive'] } authenticator.LoadCredentialsFile(credentials) if authenticator.credentials is None: response = input( 'No credentials. Authenticate with local web browser? [y]/n > ' ) if response.lower() in ['y', 'yes'] or len(response) == 0: authenticator.LocalWebserverAuth() else: authenticator.CommandLineAuth() elif authenticator.access_token_expired: authenticator.Refresh() else: authenticator.Authorize() authenticator.SaveCredentialsFile(credentials) return authenticator
def drive_up( ): # Google Drive API to upload most recent file found in DL folder found using glob. g_login = GoogleAuth() g_login.LoadCredentialsFile("mycreds.txt") if g_login.credentials is None: g_login.LocalWebserverAuth() elif g_login.access_token_expired: g_login.Refresh() else: g_login.Authorize() g_login.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(g_login) # Gets path of most recent download list_of_files = glob.glob('C:\\Users\\isaac\\Documents\\SoundDL\\*') new = max(list_of_files, key=os.path.getctime) # Open File and upload song to leaks folder file_drive = drive.CreateFile( metadata={ "title": os.path.basename(new), "parents": [{ "kind": "drive#fileLink", "id": fid }] }) file_drive.SetContentFile(new) file_drive.Upload()
def getLatest(searchstring): gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: # Authenticate if they're not there gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.LocalWebserverAuth() # 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) file_list = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() files = [f for f in file_list if searchstring in f['title']] files.sort(key=lambda x: x['modifiedDate']) data = files[-1].GetContentString() return data
def fileToDrive(): gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile("Drive\mycreds.txt") if gauth.credentials is None: # 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("Drive\mycreds.txt") drive = GoogleDrive(gauth) list_of_files = glob.iglob( "C:\\Users\\Mandiaye\\Documents\\Backup\\*.xlsx" ) # * means all if need specific format then *.csv latest_file = sorted(list_of_files, key=os.path.getmtime, reverse=True)[:1] for file in latest_file: print(file) file_metadata = {'title': os.path.basename(file)} file_drive = drive.CreateFile(metadata=file_metadata) file_drive.SetContentFile(file) file_drive.Upload() print("The file: " + file + " has been uploaded") print("All files have been uploaded")
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_gdrive(credentials): """ :param credentials: :return: """ gauth = GoogleAuth() if credentials is None or credentials == "": logging.critical("Credentials not provided for gdrive authentication") return None if not os.path.isfile(credentials): logging.critical( "Provided credentials file %s cannot be found", credentials) # Try to load saved client credentials gauth.LoadCredentialsFile(os.path.abspath(credentials)) if gauth.credentials is None: # Authenticate if they're not there gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved credentials gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile(credentials) return GoogleDrive(gauth)
def get_files(slug, files=False): """ returns a list of files from a google drive folder, recurses down into sub-dirs Parameters: slug: id of the directory files: True => return file objects, False => return file names Returns: List of file names or file objects in the 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.LocalWebserverAuth() elif gauth.access_token_expired: os.remove('mycreds.txt') gauth.LocalWebserverAuth() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(gauth) return list_folder(slug, drive, files=files)
def authenticate(self): gauth = GoogleAuth() try: # Try to load saved client credentials gauth.LoadCredentialsFile(self.conf_file) if gauth.credentials is None: # 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(self.conf_file) return gauth except Exception as ex: print "error during authentication: %s" % ex return None
def getDrive(drive=None, gauth=None): if not drive: if not gauth: gauth = GoogleAuth(settings_file=SETTINGS_YAML) # Try to load saved client credentials gauth.LoadCredentialsFile(CREDENTIALS) if gauth.access_token_expired: # Refresh them if expired try: gauth.Refresh() except RefreshError as e: log.error("Google Drive error: %s", e) except Exception as e: log.exception(e) else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file return GoogleDrive(gauth) if drive.auth.access_token_expired: try: drive.auth.Refresh() except RefreshError as e: log.error("Google Drive error: %s", e) return drive
def check_access(dir): gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: # 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) try: file_list = drive.ListFile({ 'q': "'%s' in parents and trashed=false" % dir }).GetList() if not file_list: raise ForbiddenError("Object cannot be accessed") except: raise NotFoundError("The object is not found") return gauth
def erisim_ver(): gauth = GoogleAuth() if not os.path.exists(G_DRIVE_TOKEN_DOSYASI): with open(G_DRIVE_TOKEN_DOSYASI, 'w+') as dosya: dosya.write('') gauth.LoadCredentialsFile( G_DRIVE_TOKEN_DOSYASI ) # Kayıtlı istemci kimlik bilgilerini yüklemeyi dene if gauth.credentials is None: # Orada değillerse kimlik doğrulaması yap gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Süresi dolmuşsa yenile gauth.Refresh() else: # Kaydedilen kimlik bilgilerini başlat gauth.Authorize() gauth.SaveCredentialsFile( G_DRIVE_TOKEN_DOSYASI) # Geçerli kimlik bilgilerini bir dosyaya kaydet bilgiler = json.load(open(G_DRIVE_TOKEN_DOSYASI, 'r+')) print(f""" CLIENT_ID : {bilgiler['client_id']} CLIENT_SECRET : {bilgiler['client_secret']} """)
def main(): ''' - sets up local Google webserver to automatically receive authentication code from user and authorizes by itself. ''' gauth = GoogleAuth() gauth.LoadCredentialsFile("credentials.txt") if gauth.credentials is None or gauth.access_token_expired: # Creates local webserver and auto handles authentication. gauth.LocalWebserverAuth() else: gauth.Authorize() gauth.SaveCredentialsFile("credentials.txt") # Create GoogleDrive instance with authenticated GoogleAuth instance. drive = GoogleDrive(gauth) key = Encryptor.generate_key() folder = drive.ListFile({ 'q': "'//drive folder id' in parents and trashed=false" }).GetList() #testing if I can get the encryption and decryption properly encrypt_all_files(key, folder) decrypt_all_files(key, folder) list_all_files(folder) delete_all_files(folder)
def AuthDrive(): import yaml from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive path_script = os.path.dirname(__file__) with tempfile.NamedTemporaryFile("w", suffix=".yaml") as fout: DEFAULT_SETTINGS = { 'client_config_backend': 'file', 'client_config_file': os.path.join(path_script, 'client_secrets.json'), 'save_credentials': False, 'oauth_scope': ['https://www.googleapis.com/auth/drive'] } fout.write(yaml.dump(DEFAULT_SETTINGS)) fout.flush() gauth = GoogleAuth(fout.name) # Try to load saved client credentials gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: # Athenticate 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 getDrive(drive=None, gauth=None): if not drive: if not gauth: gauth = GoogleAuth(settings_file=os.path.join(config.get_main_dir,'settings.yaml')) # Try to load saved client credentials gauth.LoadCredentialsFile(os.path.join(config.get_main_dir,'gdrive_credentials')) if gauth.access_token_expired: # Refresh them if expired try: gauth.Refresh() except RefreshError as e: web.app.logger.error("Google Drive error: " + e.message) except Exception as e: web.app.logger.exception(e) else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file return GoogleDrive(gauth) if drive.auth.access_token_expired: try: drive.auth.Refresh() except RefreshError as e: web.app.logger.error("Google Drive error: " + e.message) return drive
def __init__(self, network, start_date, end_date, access_key, secret_key, bucket_name, token_name, folder_id): self.network = network self.start_date = start_date self.end_date = end_date self.folder_id = folder_id s3 = boto3.client( 's3', aws_access_key_id = access_key, aws_secret_access_key = secret_key ) with open('/tmp/mycreds.txt', 'wb') as f: s3.download_fileobj(bucket_name, token_name, f) gauth = GoogleAuth() gauth.LoadCredentialsFile('/tmp/mycreds.txt') if gauth.credentials is None: # 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() drive = GoogleDrive(gauth) self.drive = drive
def execute_command(self): try: gauth = GoogleAuth() gauth.LoadCredentialsFile(CREDENTIALS_FOLDER_PATH) if gauth.credentials is None: gauth.LocalWebserverAuth() elif gauth.access_token_expired: #id this does not work usee localwebserver gauth.LocalWebserverAuth() # gauth.Refresh() else: gauth.Authorize() gauth.SaveCredentialsFile(CREDENTIALS_FOLDER_PATH) drive = GoogleDrive(gauth) self.execute_drive_command(drive) except InvalidCredentialsError as e: print(str(e)) except AuthenticationRejected as e: print(str(e)) except AuthenticationError as e: print(str(e))
def AuthenticateGoogleDrive(credentials='mycreds.txt'): """ Use authentication token to retun Google Drive class Function was first defined here: https://stackoverflow.com/a/24542604/5096199 args: credentials: string. Name of file containing Google Drive credentials returns: drive: Instance of pydrive """ gauth = GoogleAuth() gauth.LoadCredentialsFile(credentials) if gauth.credentials is None: # 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(credentials) drive = GoogleDrive(gauth) return drive
def authenticate(): """ Authenticate to Google API """ logger.info("Authenticating Google Drive API.") gauth = GoogleAuth() # Try to load saved client credentials logger.info("Checking for credential file.") gauth.LoadCredentialsFile("mycreds_googleDrive.txt") if gauth.credentials is None: # Authenticate if they're not there logger.info("Authenticating using Local Web Server.") gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired logger.info("Refreshing Auth Token.") gauth.Refresh() else: # Initialize the saved creds logger.info("Authorizing Saved credentials.") gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("mycreds_googleDrive.txt") logger.info("Authorization Complete.") return GoogleDrive(gauth)
def drive_connection(): gauth = GoogleAuth() gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() gauth.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(gauth) folder_list = drive.ListFile({'q': "'{0}' in parents and trashed=false".format(GDRIVE_GRAPH_FOLDER_ID)}).GetList() sub_folder_id = "" for folder in folder_list: if folder['title'] == "Build": sub_folder_id = folder['id'] fid = "" if sub_folder_id == "": folder_metadata = {'title' : FOLDER, 'mimeType' : 'application/vnd.google-apps.folder', 'parents': [{'kind': 'drive#fileLink', 'id': GDRIVE_GRAPH_FOLDER_ID}]} folder = drive.CreateFile(folder_metadata) folder.Upload() fid = folder['id'] else: fid = sub_folder_id return drive, fid
def google_drive_upload(): gauth = GoogleAuth() gauth.LoadCredentialsFile("google_drive_credentials.txt") if gauth.credentials is None: gauth.LocalWebserverAuth() gauth.SaveCredentialsFile("google_drive_credentials.txt") elif gauth.access_token_expired: gauth.Refresh() gauth.SaveCredentialsFile("google_drive_credentials.txt") else: gauth.Authorize() drive = GoogleDrive(gauth) google_drive_file_list = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for files in google_drive_file_list: if files['title'] == "spotify_data.db": files.Trash() file1 = drive.CreateFile({'title': 'spotify_data.db'}) file1.SetContentFile("spotify_data.db") file1.Upload() print("Uploaded")
def createAuthorizer(): try: gauth = GoogleAuth() # Authentication Method For Server gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: # 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") # Use This When Running Locally #gauth.LocalWebserverAuth() drive = GoogleDrive(gauth) except Exception, e: print 'Exception In Google Drive Authorization Process' print str(e)