谷歌计算实例和谷歌驱动器之间的谷歌驱动器API

时间:2020-10-06 16:16:11

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

我试图使用Google Drive API从python脚本访问Google Drive。

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

有人做过吗?有人知道怎么做吗? 非常感谢您提供任何信息 马修(N.Mathieu)

1 个答案:

答案 0 :(得分:0)

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

服务帐户属于应用程序,而不属于单个最终用户。可以单独使用它,也可以模拟域中的另一个用户(请参见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()

进一步阅读: