Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pydrive google drive automate authentication

I have the following piece of code:

from pydrive.auth import GoogleAuth

gauth = GoogleAuth()
gauth.DEFAULT_SETTINGS = {'save_credentials': True,'client_config_backend': 'settings',
                          'oauth_scope': ['https://www.googleapis.com/auth/drive'],
                          'get_refresh_token': True,
                          'save_credentials_file':"credential_log.txt",
                          'save_credentials_backend': 'file'}

gauth.client_config = {'client_id': '499039293801-krogpnentl6qk035vt4hcd36nefiautt.apps.googleusercontent.com', 'client_secret': 'iqFCuOh36amMFi3U1dkyCWJK',
                       'redirect_uri':'urn:ietf:wg:oauth:2.0:oob','revoke_uri': 'None',
                       'token_uri':'https://accounts.google.com/o/oauth2/token',
                       'auth_uri':'https://accounts.google.com/o/oauth2/auth',
                       'save_credentials_file':"mycreds_p2iman.txt"}
gauth.CommandLineAuth()

from pydrive.drive import GoogleDrive

drive = GoogleDrive(gauth)

file4 = drive.CreateFile({'title':'somethingdifferent.txt', 'mimeType':'different/txt'})
file4.SetContentString('My name is John')
file4.Upload() # Upload file.
file4.SetContentString('My name is John')
file4.Upload() # Update content of the file.

The problem is that a verification code is generated in the Google Chrome and every time user needs to copy->paste it in the console in order to authenticate. Is there a way to automate this process?

like image 764
Black Pepper BG Avatar asked Oct 27 '17 15:10

Black Pepper BG


Video Answer


1 Answers

Actually you need to copy the client_secret.json file to my_cred.txt by the following code:

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")

Then use the following code to initialize the drive:

def authorize_drive():
    gauth = GoogleAuth()
    gauth.DEFAULT_SETTINGS['client_config_file'] = "client_secret.json"
    gauth.LoadCredentialsFile("mycreds.txt")
    return GoogleDrive(gauth)


class DriveReport(object):
    def __init__(self):
        self.drive = authorize_drive()    

See more of this link: Automating pydrive verification process

like image 151
Gavriel Cohen Avatar answered Oct 12 '22 01:10

Gavriel Cohen