【问题标题】:Google drive api between google compute instance and google drive谷歌计算实例和谷歌驱动器之间的谷歌驱动器api
【发布时间】:2020-10-07 15:57:35
【问题描述】:

我尝试使用 Google Drive API 从 Python 脚本访问 Google Drive。

  • 它可以在我的个人计算机上运行,​​因为我可以启动浏览器来验证身份验证
  • 无法使其在 Google Compute 实例上运行(没有浏览器,无法传输凭据)。

有人做过吗?有谁知道该怎么做? 非常感谢您提供的任何信息 N.Mathieu

【问题讨论】:

    标签: google-drive-api google-compute-engine


    【解决方案1】:

    使用服务帐号,不需要浏览器或用户交互。

    服务帐户属于应用程序,而不是单个最终用户。它可以单独使用,也可以模拟域中的其他用户(请参阅Delegating domain-wide authority to the service account)。

    但无论如何,它不需要用户同意或交互,并且在没有浏览器和不应该是用户交互的情况下很有用。

    代码示例:

    # Copyright 2020 Google LLC.
    # SPDX-License-Identifier: Apache-2.0
    
    from googleapiclient.discovery import build
    from google.oauth2 import service_account
    
    SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
    SERVICE_ACCOUNT_FILE = 'credentials.json'
    
    def getCreds():
        creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
        # Uncomment if you want to impersonate another user:
        # creds = creds.with_subject('impersonated_account@your_domain.com') 
        return creds
    
    def main():
        creds = getCreds()
        service = build('drive', 'v3', credentials=creds)
        # Use service to call Drive API (e.g. service.files().list().execute())
    
    if __name__ == '__main__':
        main()
    

    延伸阅读:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 2021-07-07
      • 1970-01-01
      • 2012-07-04
      • 1970-01-01
      相关资源
      最近更新 更多