簡體   English   中英

PyDrive Google Drive自動認證

[英]Pydrive google drive automate authentication

我有以下代碼:

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.

問題在於,驗證碼會在Google Chrome瀏覽器中生成,並且每次用戶需要在控制台中進行復制->粘貼以進行身份​​驗證時,都會生成驗證碼。 有沒有辦法使這個過程自動化?

實際上,您需要通過以下代碼將client_secret.json文件復制到my_cred.txt

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

然后使用以下代碼初始化驅動器:

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

查看此鏈接的更多信息: 自動化pydrive驗證過程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM