使用Drive/Sheets API(Python)创建表格后无法查看的问题
问题描述
我查阅了大量论坛和文档仍未找到问题所在,同时我是Python新手,可能犯了简单错误。我尝试通过服务账号在共享文件夹中创建电子表格,之后将该表格共享给我的主账号(因不确定其他方式才使用服务账号)。我能在共享云端硬盘的共享文件夹中创建表格,但即使添加了共享权限且未报错,仍无法看到新建的表格。
我的代码
from __future__ import print_function from oauth2client.service_account import ServiceAccountCredentials from googleapiclient.discovery import build SCOPES = [ 'https://www.googleapis.com/auth/drive.metadata', 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file', ] # Get credentials creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', SCOPES) service = build('drive', 'v3', credentials=creds) # Name sheet and provide parent ID of shared folder within shared drive sheet_metadata = { 'name': 'This will be cools', 'mimeType': 'application/vnd.google-apps.spreadsheet', 'parents': 'SHARED FOLDER ID INSIDE SHARED DRIVE', } # Sharing permissions shared_permissions = { 'role': 'writer', 'type': 'user', 'emailAddress': 'MY PERSONAL EMAIL' } results = service.files().create(body=sheet_metadata,fields='id').execute() permission = service.permissions().create( fileId=results.get('id'), body=shared_permissions )
我曾因不知道如何传递新建表格的ID而困扰,但这部分似乎已正常工作,不过我访问共享云端硬盘的共享文件夹时仍看不到新表格,恳请各位提供技术见解。
解决方案
你的代码存在3个关键错误,直接导致文件无法正常显示:
parents参数格式错误:Google Drive API要求parents是数组类型,你传入单个字符串,文件无法正确归属到目标共享文件夹- 权限创建未执行:仅定义
permission对象但未调用.execute(),权限根本没被应用到文件上 - 缺少共享驱动器支持参数:操作共享云端硬盘内的文件时,必须添加
supportsAllDrives=True参数,否则API会忽略共享驱动器相关操作
修正后的代码
from __future__ import print_function from oauth2client.service_account import ServiceAccountCredentials from googleapiclient.discovery import build SCOPES = [ 'https://www.googleapis.com/auth/drive.metadata', 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file', ] # 获取凭据 creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', SCOPES) service = build('drive', 'v3', credentials=creds) # 表格元数据:parents改为数组格式 sheet_metadata = { 'name': 'This will be cools', 'mimeType': 'application/vnd.google-apps.spreadsheet', 'parents': ['SHARED FOLDER ID INSIDE SHARED DRIVE'], } # 创建文件时添加共享驱动器支持参数 results = service.files().create( body=sheet_metadata, fields='id', supportsAllDrives=True ).execute() file_id = results.get('id') if not file_id: print("创建文件失败") exit() # 共享权限配置 shared_permissions = { 'role': 'writer', 'type': 'user', 'emailAddress': 'MY PERSONAL EMAIL' } # 应用权限:添加共享驱动器支持参数并执行execute() service.permissions().create( fileId=file_id, body=shared_permissions, supportsAllDrives=True ).execute() print(f"表格创建成功,ID: {file_id},权限已添加")
额外注意事项
- 确保服务账号已被添加到目标共享云端硬盘,且拥有至少编辑者权限,否则无法在其中创建文件
- 修正后刷新共享驱动器页面,就能在目标文件夹中看到新建的表格
内容的提问来源于stack exchange,提问作者yaziki
相关产品推荐
相关产品推荐

