
本文档旨在帮助开发者解决在使用 Google Drive API 请求访问 Google 表格文件时遇到的 "File not found" 错误。我们将深入分析问题原因,并提供详细的解决方案,包括如何正确使用文件 ID 以及注意事项,确保您能成功通过 API 管理 Google 表格文件的访问权限。
在使用 Google Drive API 尝试请求访问 Google 表格文件时,可能会遇到 "File not found" 错误,即使通过浏览器可以正常访问该文件并看到权限请求提示。 这种问题通常是由于在 API 请求中使用了错误的 fileId 导致的。 常见的错误是将整个 Google 表格的 URL 当作 fileId 传递给 API。
问题分析:
API 报错信息:
{'message': 'File not found: https://docs.google.com/spreadsheets/d/1u...4bcSqdgc/edit#gid=0.', 'domain': 'global', 'reason': 'notFound', 'location': 'fileId', 'locationType': 'parameter'}错误信息表明 API 无法找到指定的 fileId。 这通常意味着您传递的 fileId 不是 Google Drive API 期望的格式。
解决方案:
正确的做法是使用 Google 表格的 ID 作为 fileId。 表格 ID 是 URL 中 d/ 和 /edit 之间的字符串。
例如,如果 Google 表格的 URL 是:
https://docs.google.com/spreadsheets/d/1u...4bcSqdgc/edit#gid=0
那么,正确的 fileId 应该是:
1u...4bcSqdgc
代码示例:
修改您的代码,将 file_url 变量的值更改为正确的 Google 表格 ID。
drive_service = build('drive', 'v3', credentials=g.gcreds_scoped)
permission_request = { 'role': 'writer', 'type': 'anyone', 'allowFileDiscovery': False }
sheets_service = build('sheets', 'v4', credentials=g.gcreds_scoped)
# 确保 file_url 变量包含正确的 Google 表格 ID
file_id = "1u...4bcSqdgc" # 替换为您的表格 ID
request = drive_service.permissions().create(body=permission_request, fileId=file_id, supportsAllDrives=True, fields='id')
response = request.execute()注意事项:
总结:
在使用 Google Drive API 请求访问 Google 表格文件时,确保使用正确的 Google 表格 ID 作为 fileId。 检查您的客户端是否具有访问权限,并确保已启用必要的 API 和权限范围。 遵循这些步骤,您应该能够成功通过 API 管理 Google 表格文件的访问权限。
参考资料:
以上就是通过 Google Drive API 请求访问 Google 表格文件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号