コード例 #1
0
ファイル: syncAS.py プロジェクト: CatoMaior/Dotfiles
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
コード例 #2
0
ファイル: data_daemon.py プロジェクト: raghuvelagala/IOTPlant
def upload_file(filename):
    gauth = GoogleAuth()                #authenticates application from 'client_secrets.json'
    gauth.LoadCredentialsFile("/var/lib/cloud9/mycreds.txt")    #Load credentials of gdrive user to uplaod files

    if gauth.credentials is None:           #if file is empty or credentials not valid
        gauth.CommandLineAuth()             #For the first time, key has to be entered manually
                                            #But should never reach here on crontab job (signal will terminate application after 20s),
    elif gauth.access_token_expired:            #if credentials expired, then refresh them
        gauth.Refresh()
    else:                                   #if stored credentials are good, then authenticate application user
        gauth.Authorize()                       
        
    gauth.SaveCredentialsFile("/var/lib/cloud9/mycreds.txt")        #save new credentials
    
    drive = GoogleDrive(gauth)
    
    file2 = drive.CreateFile()              #create file to upload
    file2.SetContentFile("/var/lib/cloud9/photos/" + str(filename) + ".jpg")        #write to file
    file2['title'] = str(filename) + ".jpg"                                   #file name
    file2.Upload()                                                              #upload file to gdrive
    print 'Created file %s on Google Drive' % (file2['title'])

    f = open('/var/lib/cloud9/photos/successful_uploads.txt', 'a')              #log if file uploaded successfully. if stuck on credentials, signal termiantes app and nothing is written.
    f.write(filename+".jpg"+"\n")
    f.close()
コード例 #3
0
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)
コード例 #4
0
ファイル: jarvis_test.py プロジェクト: rb1811/jarvis-corp
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)
コード例 #5
0
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
コード例 #6
0
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
コード例 #7
0
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']}
    """)
コード例 #8
0
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
コード例 #9
0
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
コード例 #10
0
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)
コード例 #11
0
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
コード例 #12
0
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)
コード例 #13
0
class GDriveHandler:
    def __init__(self):
        self.gauth = GoogleAuth()

    def authenticate(self, credentials_file_location):
        self.gauth.LoadCredentialsFile(credentials_file_location)
        if self.gauth.credentials is None: print("Some error")
        elif self.gauth.access_token_expired: self.gauth.Refresh()
        else: self.gauth.Authorize()

        self.gauth.SaveCredentialsFile(credentials_file_location)
        self.drive = GoogleDrive(self.gauth)
        return True

    def setGDriveFolderId(self, folder_id):
        self.folder_id = folder_id

    def uploadfile(self, file_location, file_name):
        drive_file = self.drive.CreateFile(
            {"parents": [{
                "kind": "drive#fileLink",
                "id": self.folder_id
            }]})
        drive_file.SetContentFile(file_location)
        drive_file['title'] = file_name
        drive_file.Upload()
        print(drive_file['originalFilename'], drive_file['id'])
        return drive_file
コード例 #14
0
def auth_google_drive():
    '''
    Authorize script to use your google drive.
    Return:
    gauth - GoogleDrive object with your authorized g. drive
    '''

    from pydrive.auth import GoogleAuth
    from pydrive.drive import GoogleDrive

    gauth = GoogleAuth()
    gauth.DEFAULT_SETTINGS['client_config_file'] = "client_secret.json"
    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)

    return drive
コード例 #15
0
ファイル: googleStorage.py プロジェクト: bj00rn/schploff
class GoogleStorage:
    def __init__(self, target_path, settings_file):
        self.path = target_path
        self.gauth = None
        self.config = settings.LoadSettingsFile(settings_file)

    def connect(self):
        try:
            self.gauth = GoogleAuth()
            # Try to load saved client credentials
            self.gauth.LoadCredentialsFile(
                self.config['save_credentials_file'])
            if self.gauth.credentials is None:
                if sys.stdout.isatty():
                    # Authenticate if they're not there and shell is interactive
                    self.gauth.CommandLineAuth()
                else:
                    raise ValueError(
                        'No credentials found, need to log in first. try running script from interactive shell'
                    )
            elif self.gauth.access_token_expired:
                # Refresh them if expired
                self.gauth.Refresh()
            else:
                # Initialize the saved creds
                self.gauth.Authorize()
            # Save the current credentials to a file
            self.gauth.SaveCredentialsFile(
                self.config['save_credentials_file'])
        except Exception as e:
            logger.error('failed to connect to google storage', exc_info=True)
            raise e
コード例 #16
0
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
コード例 #17
0
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
コード例 #18
0
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")
コード例 #19
0
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()
コード例 #20
0
    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
コード例 #21
0
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
コード例 #22
0
ファイル: Authenticators.py プロジェクト: ohadozer/MiniDLP
    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
コード例 #23
0
    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)
コード例 #24
0
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
コード例 #25
0
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
コード例 #26
0
ファイル: fileToGdrive.py プロジェクト: 9123086/GDriveUpload
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
コード例 #27
0
ファイル: gDriver.py プロジェクト: hiddenxx/Toolkit
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)
コード例 #28
0
    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
コード例 #29
0
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")
コード例 #30
0
def get_credentials():  # Saves valid credentials and points the app to the
    # correct Google Drive account and folders
    # = the content (messages to save)
    """Gets valid user credentials from storage.
    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.
    Returns:
    Credentials, the obtained credential.
    """
    # from google API console - load credentials from file
    gauth = GoogleAuth()  # Object to hold authentication information
    # Try to load saved client credentials
    gauth.LoadCredentialsFile("credentials.txt")
    if gauth.credentials is None:
        print "No creds file"
        # Authenticate if they're not there
        gauth.CommandLineAuth()
    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")
    return GoogleDrive(gauth)  # To be passed as needed