Search code examples
pythongoogle-apigoogle-drive-apigoogle-oauthpydrive

Implement access token from OAUTH playground google with pydrive


I was trying to authenticate without asking for permissions on google drive using pydrive and they suggest me to follow this answer answer on stack but when I got the access token I didn`t really know where to place it, I tried on client_secret.json but didn't work.


Solution

  • The question you are following is from 2013, following any question that old is always a crap shoot.

    First of all Using Oauth2 playground is intended for testing and development only. Tokens created on Oauth playground will expire quickly if you are not using your own client id and client secret. If you are using your own client id and client secret then your refresh token will expire with in seven days. As it will not be possible to verify an application using a redirect uri for Oauth playground as you do not own the domain. All of these security protection measures were applied prior to 2013.

    Assuming that you have a single user application and you will only be accessing your own drive account then you should be using a service account.

    from pydrive2.auth import GoogleAuth
    from pydrive2.drive import GoogleDrive
    from oauth2client.service_account import ServiceAccountCredentials
    
    scope = ["https://www.googleapis.com/auth/drive"]
    gauth = GoogleAuth()
    gauth.auth_method = 'service'
    gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secrets.json', scope)
    drive = GoogleDrive(gauth)
    
    about = drive.GetAbout()
    
    print('Current user name:{}'.format(about['name']))
    print('Root folder ID:{}'.format(about['rootFolderId']))
    print('Total quota (bytes):{}'.format(about['quotaBytesTotal']))
    print('Used quota (bytes):{}'.format(about['quotaBytesUsed']))
    
    
    file_list = drive.ListFile().GetList()
    for file1 in file_list:
      print('title: %s, id: %s' % (file1['title'], file1['id']))
    

    You should consult pydrive github page service account or us the official google api python sample instead.