GoogleDrive REST API身份验证,无需干预

时间:2016-01-25 14:19:32

标签: google-drive-api

我需要做的是在GoolgeDrive API中验证自己(我在python中使用它)来访问我的驱动器以执行一些自动化任务。

我希望我的脚本每小时独自运行而不需要任何干预。所以我需要的是一种使用我的登录名和密码创建凭证对象的方法。

是否可以不进行任何重定向等等?

1 个答案:

答案 0 :(得分:1)

我认为使用用户ID和密码无法实现此目的。 Google云端硬盘实现此功能的方式是使用刷新令牌。这意味着您可以以交互方式对应用进行一次身份验证。这使您可以应用一小时。如果正确配置了刷新令牌机制,则应用程序将在每次需要时更新令牌。

基本上需要采取以下步骤

  • 访问c​​onsole.developers.google.com
  • 注册项目并获取Oauth客户端ID
  • 选择类型为网络服务器并输入" http://localhost:8080/"作为授权重定向网址
  • 下载client_secrets.json并将其存储在python应用程序的根目录中
  • 创建一个名为" settings.yaml"的文件。在同一个地方有以下内容

    client_config_backend: settings
    client_config:
    client_id: YOUR_CLIENT_ID_GOES_HERE
    client_secret: YOUR_CLIENT_SECRET_GOES_HERE

    save_credentials: True
    save_credentials_backend: file
    save_credentials_file: credentials.son

    get_refresh_token: True

    oauth_scope:
    - https://www.googleapis.com/auth/drive.file
    - https://www.googleapis.com/auth/drive.install

  • 在您的python代码中,您需要进行适当的身份验证和凭据保存:

    gauth = GoogleAuth()
    gauth.settings["get_refresh_token"]=True
    gauth.settings["approval_prompt"]="force"
    if exists(self.credsFile):
        gauth.LoadCredentialsFile(self.credsFile)
    if gauth.credentials is None:
        # Authenticate if they're not there
        gauth.LocalWebserverAuth()
        gauth.SaveCredentialsFile(self.credsFile)
    elif gauth.access_token_expired:
        # Refresh them if expired
        gauth.Refresh()
        gauth.Authorize()
    else:
        # Initialize the saved creds
        gauth.Authorize()
        # Save the current credentials to a file
        gauth.SaveCredentialsFile(self.credsFile)
    self.driveInstance= GoogleDrive(gauth)
    
  • 确保将self.credsFile作为有效文件名传递

  • 执行此代码应该会在控制台上显示一个URL。将其复制到浏览器,进行身份验证并征得您的同意。 Google应该要求您提供两份同意书,第二份是对Google云端硬盘进行身份验证 - 实际上是通过刷新令牌进行身份验证。

  • 一旦获得同意,将调用开发人员控制台中初始凭据配置的重定向URL。它调用应用程序启动的临时Web服务器。这就是回叫的完成方式。 (这意味着您必须在同一台计算机上运行浏览器和您的应用程序 - 您可以将所有三个文件复制到您的服务器上)

从现在开始,您的应用应该永远运行,无需用户互动。

相关问题