如何重复使用现有验证码/令牌来访问Google云端硬盘?

时间:2013-11-19 14:30:12

标签: python google-api google-api-python-client

我正在为我的GDrive文件夹创建备份脚本。每次运行我需要向Google确认 该脚本可以访问GDrive。但是,在第一次运行后,应保存验证码。在这篇文章中,他们提到了一个带有Web服务器(Fulfilling Google Drive API OAuth2.0 Procedure w/o needing to find a verification code)的解决方案 - 但我正在寻找一个没有Web服务器的简单备份脚本的解决方案。

  • 是否有一个类我可以使用而不是OAuth2WebServerFlow来使用现有的验证码来检索正确的凭据?有没有办法跳过step1_get_authorize_url()?或者我应该直接使用oauth2来实现此目的吗?

我的代码

    flow = OAuth2WebServerFlow(self.CLIENT_ID, self.CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI, offline=True)
    authorize_url = flow.step1_get_authorize_url()
    print 'Go to the following link in your browser: ' + authorize_url
    print
    code =  raw_input('Enter verification code: ').strip()
    credentials = flow.step2_exchange(code)
    http = httplib2.Http()
    http = credentials.authorize(http)
    drive_service = build('drive', 'v2', http=http)

1 个答案:

答案 0 :(得分:2)

这是一个命令行工具吗?如果是这样,请尝试以下操作,这将在第一次提示您后保留凭据:

import httplib2
from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run
from apiclient.discovery import build

storage = Storage("saved_user_creds.dat")
credentials = storage.get()
if credentials is None or credentials.invalid:
  credentials = run(flow_from_clientsecrets("client_secrets2.json", scope=["https://www.googleapis.com/auth/drive"]), storage)
http = credentials.authorize(httplib2.Http())
service = build("drive", "v2", http)
print service.files().list().execute()