使用files.copy接口的Sheets转Docs访问权限问题及代码排查
问题分析与解决方案
问题根源
你使用服务账号创建Google文档,该文档的所有权属于服务账号而非你的个人Gmail账号,因此你访问时会被要求申请权限;同时代码中缺少将新文档移动到指定Drive文件夹的逻辑。
修复步骤
1. 给个人账号赋予文档访问权限
创建文档后,添加权限授予逻辑,将你的个人Gmail账号设为文档编辑者:
# 创建文档后插入这段代码 permission = { 'type': 'user', 'role': 'writer', 'emailAddress': '你的个人Gmail账号@gmail.com' # 替换为你的实际邮箱 } DRIVE.permissions().create( fileId=new_doc_id, body=permission, sendNotificationEmail=False # 可选:是否发送权限通知邮件 ).execute()
2. 将文档移动到指定文件夹
默认创建的文档存放在服务账号的Drive根目录,需添加移动逻辑到目标文件夹:
# 设置权限后插入这段代码 # 先移除原根目录父级 DRIVE.files().update( fileId=new_doc_id, body={'parents': []} ).execute() # 添加目标文件夹为父级 DRIVE.files().update( fileId=new_doc_id, body={'parents': [folder_id]} ).execute()
3. 代码细节优化
- 你代码中重复加载了credentials,保留一次即可
get_ipython().system('googleapiclient.errors import HttpError')是错误写法,import语句不能用system执行,应改为:from googleapiclient.errors import HttpError
修改后的关键代码片段
# 创建新文档 new_doc_body = { 'title': 'JD Salinger Finished' } new_doc = DOCS.documents().create(body=new_doc_body).execute() new_doc_id = new_doc['documentId'] # 给个人账号添加编辑权限 permission = { 'type': 'user', 'role': 'writer', 'emailAddress': '你的个人邮箱@gmail.com' } DRIVE.permissions().create( fileId=new_doc_id, body=permission, sendNotificationEmail=False ).execute() # 将文档移动到指定文件夹 DRIVE.files().update( fileId=new_doc_id, body={'parents': []} ).execute() DRIVE.files().update( fileId=new_doc_id, body={'parents': [folder_id]} ).execute() # 插入内容逻辑不变 requests = [] for row in all_values[1:]: request = { 'insertText': { 'location': { 'index': 1 }, 'text': f'{row[0]} - {row[1]} - {row[2]} - {row[3]}\n\n' } } requests.append(request) DOCS.documents().batchUpdate(documentId=new_doc_id, body={'requests': requests}).execute() print("Content has been inserted into the new Google Docs document.") print(f"New Google Docs document created: https://docs.google.com/document/d/{new_doc_id}")
补充说明
服务账号是独立的Google账号实体,它创建的资源默认仅自身可访问,因此必须显式为个人账号授权;移动文件夹时需先移除原父目录,再添加新父目录,这是Drive API的强制要求。
内容的提问来源于stack exchange,提问作者Baker Ssebandeke
相关产品推荐
相关产品推荐

