通过 Google 驱动器 API 访问共享驱动器时出现 404 错误

404 error when accessing a shared drive via Google Drive API

我正在尝试列出共享驱动器的元数据。下面是代码:

from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

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

if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
        creds = flow.run_local_server(port=8080)
    with open('token.json', 'w') as token:
        token.write(creds.to_json())

上面的代码有效;它可以成功验证。

service = build('drive', 'v3', credentials=creds)
file_id = '0AFmX-a2BvgHBUk9PVA'
results = service.permissions().list(fileId=file_id).execute()

代码的输出如下:

Traceback (most recent call last): File "<pyshell#23>", line 1, in results = service.permissions().list(fileId=file_id).execute() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper return wrapped(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/googleapiclient/http.py", line 935, in execute raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: <HttpError 404 when requesting https://www.googleapis.com/drive/v3/files/0AFmX-a2BvgHBUk9PVA/permissions?alt=json returned "File not found: 0AFmX-a2BvgHBUk9PVA.". Details: "[{'domain': 'global', 'reason': 'notFound', 'message': 'File not found: 0AFmX-a2BvgHBUk9PVA.', 'locationType': 'parameter', 'location': 'fileId'}]">

文件确实存在。代码有错吗?我使用的权限范围正确吗?我需要使用服务帐户而不是 OAuth 客户端 ID 吗?

我认为您的目标和现状如下。

  • 您想从共享云端硬盘中检索权限列表。
  • 您可以访问共享云端硬盘。

在这种情况下,请将 supportsAllDrives 添加到请求的查询参数中,如下所示。

supportsAllDrives: Whether the requesting application supports both My Drives and shared drives. (Default: false)

发件人:

results = service.permissions().list(fileId=file_id).execute()

收件人:

results = service.permissions().list(fileId=file_id, supportsAllDrives=True).execute()

参考: