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

2024-10-06 14:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: 代码fromhttpsimportcomtokenauthjson
1条回答
网友
1楼 · 发布于 2024-10-06 14:23:53

我相信你的目标和现状如下

  • 您想从共享驱动器检索权限列表
  • 您可以访问共享驱动器

在这种情况下,请在请求的查询参数中包含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()

参考资料:

相关问题 更多 >