Google Drive API for Python:如何创建凭证?

Pau*_*ulJ 2 python google-drive-api google-oauth google-cloud-platform

我正在编写一个 Python 脚本来自动将一些文件上传到 Google Drive。由于我仍然是一名 Python 程序员新手,而且这与其他任何事情一样都是一种练习,因此我开始遵循Google 快速入门,并决定使用它们quickstart.py作为我自己的脚本的基础。在讨论如何为 Python 脚本创建凭据的部分中,它引用了“创建凭据”链接,网址为https://developers.google.com/workspace/guides/create-credentials

\n

我点击链接,进入我的 Google Cloud 项目之一,并尝试使用“内部”项目设置 OAuth 同意屏幕,正如他们告诉您的那样......但我不能。谷歌说:

\n
\n

\xe2\x80\x9c由于您\xe2\x80\x99 不是 Google Workspace 用户,\n您只能将您的应用提供给外部(普通受众)用户。\xe2\x80\x9d

\n
\n

因此,我尝试创建一个“外部”项目,然后使用桌面应用程序继续创建一个新的客户端 ID。然后,我下载 JSON 凭据并将它们放在与我的 Python 脚本相同的文件夹中,如"credentials.json". 然后我执行 Python 脚本以对其进行身份验证:浏览器打开,我登录到我的 Google 帐户,授予它我的权限...然后浏览器挂起,因为它正在重定向到本地主机 URL,显然是我的小Python 脚本根本没有在我的计算机上监听。

\n

我相信他们最近一定改变了这一点,因为一年前我开始遵循相同的 Python 教程并且可以毫无问题地创建凭据,但 Google Drive API 文档尚未更新。那么...现在如何为 Python 脚本创建凭据?

\n

编辑:在此处添加我的脚本的源代码。正如我所说,它与 Google 的“quickstart.py”非常相似:

\n
from __future__ import print_function\nimport pickle\nimport os.path\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom googleapiclient.errors import HttpError\n\n\n# If modifying these scopes, delete the file token.pickle.\nSCOPES = [\'https://www.googleapis.com/auth/drive.metadata\', \'https://www.googleapis.com/auth/drive\']\n\n\n\ndef main():\n    """Shows basic usage of the Drive v3 API.\n    Prints the names and ids of the first 10 files the user has access to.\n    """\n    creds = None\n    # The file token.pickle stores the user\'s access and refresh tokens, and is\n    # created automatically when the authorization flow completes for the first\n    # time.\n    if os.path.exists(\'token_myappname.pickle\'):\n        with open(\'token_myappname.pickle\', \'rb\') as token:\n            creds = pickle.load(token)\n    # If there are no (valid) credentials available, let the user log in.\n    if not creds or not creds.valid:\n        if creds and creds.expired and creds.refresh_token:\n            creds.refresh(Request())\n        else:\n            flow = InstalledAppFlow.from_client_secrets_file(\n                \'credentials.json\', SCOPES)\n            creds = flow.run_local_server(port=0)\n        # Save the credentials for the next run\n        with open(\'token_myappname.pickle\', \'wb\') as token:\n            pickle.dump(creds, token)\n\n\n\n    service = build(\'drive\', \'v3\', credentials=creds)\n\n    # Call the Drive v3 API\n    results = service.files().list(\n        pageSize=10, fields="nextPageToken, files(id, name)").execute()\n    items = results.get(\'files\', [])\n\n\n    if not items:\n        print(\'No files found.\')\n    else:\n        #print(items[0])\n \n        print(\'Files:\')\n        for item in items:\n            #print (item)\n            print(u\'{0}   {1}   {2}\'.format(item[\'name\'], item[\'owners\'], item[\'parents\']))\n \n
Run Code Online (Sandbox Code Playgroud)\n

gui*_*ere 5

我建议您使用服务帐户来访问云端硬盘。

为此,您需要与服务帐户电子邮件共享驱动器(或文件夹)。然后使用这段代码

from googleapiclient.discovery import build
import google.auth

SCOPES = ['https://www.googleapis.com/auth/drive.metadata', 'https://www.googleapis.com/auth/drive']



def main():
    credentials, project_id = google.auth.default(scopes=SCOPES)


    service = build('drive', 'v3', credentials=credentials)

    # Call the Drive v3 API
    results = service.files().list(
        q=f"'1YJ6gMgACOqVVbcgKviJKtVa5ITgsI1yP' in parents",
        pageSize=10, fields="nextPageToken, files(id, name, owners, parents)").execute()
    items = results.get('files', [])


    if not items:
        print('No files found.')
    else:
        #print(items[0])

        print('Files:')
        for item in items:
            #print (item)
            print(u'{0}   {1}   {2}'.format(item['name'], item['owners'], item['parents']))

Run Code Online (Sandbox Code Playgroud)

如果您在 Google Cloud 上(例如在计算引擎实例中)运行代码,则需要使用您在驱动器中授权的服务帐户自定义虚拟机。(不要使用计算引擎默认服务帐户,否则您将需要在虚拟机上进行额外配置)

如果您在 GCP 之外运行脚本,则需要生成服务帐户密钥文件并将其存储在本地服务器上。然后,创建一个GOOGLE_APPLICATION_CREDENTIALS引用存储的密钥文件的完整路径的环境变量。