You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python API为指定邮箱授予Google Sheet编辑/查看权限且不影响现有权限?

用Python通过Drive API给Google Sheet批量添加权限

核心思路

Google Sheet本质是Google Drive中的文件,直接调用Drive API的Permissions.create方法就能新增权限,这个操作不会修改或删除现有权限,完全符合你的需求。

完整代码实现

from googleapiclient import discovery
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
import os.path

# 权限范围(你的配置已经足够,无需修改)
SCOPES = [
    'https://www.googleapis.com/auth/spreadsheets',
    'https://www.googleapis.com/auth/drive.metadata',
    'https://www.googleapis.com/auth/drive.file',      
    'https://www.googleapis.com/auth/drive',
]

def get_drive_client():
    """获取Drive API客户端"""
    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:
            from google_auth_oauthlib.flow import InstalledAppFlow
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # 保存凭据供下次使用
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    return discovery.build('drive', 'v3', credentials=creds)

def add_permission_to_sheet(drive_client, sheet_id, user_email, role='writer'):
    """
    给指定Google Sheet添加权限
    :param drive_client: Drive API客户端实例
    :param sheet_id: Google Sheet的文件ID
    :param user_email: 目标邮箱地址
    :param role: 权限类型,writer=编辑者,reader=查看者
    """
    try:
        permission = {
            'type': 'user',
            'role': role,
            'emailAddress': user_email
        }
        # 创建权限,supportsAllDrives=True适配共享驱动器中的文件
        response = drive_client.permissions().create(
            fileId=sheet_id,
            body=permission,
            sendNotificationEmail=True,  # 是否发送通知邮件,可选False
            transferOwnership=False,  # 禁止转移所有权,避免误操作
            supportsAllDrives=True
        ).execute()
        print(f"已成功为邮箱 {user_email} 授予 {role} 权限,权限ID: {response.get('id')}")
    except Exception as e:
        print(f"处理文件 {sheet_id} 时出错: {str(e)}")

if __name__ == '__main__':
    # 初始化Drive客户端
    drive_client = get_drive_client()
    
    # 批量处理的Sheet列表(格式:[(文件ID, 目标邮箱, 权限类型), ...])
    sheet_list = [
        ('your_sheet_id_1', 'user1@example.com', 'writer'),
        ('your_sheet_id_2', 'user2@example.com', 'reader'),
        # 可以继续添加更多表格
    ]
    
    # 循环处理每个Sheet
    for sheet_id, email, role in sheet_list:
        add_permission_to_sheet(drive_client, sheet_id, email, role)

关键说明

  • 获取文件ID: 打开你的Google Sheet,URL中d/和/edit之间的字符串就是文件ID,比如https://docs.google.com/spreadsheets/d/abc123xyz/edit中的abc123xyz。
  • 权限类型: role参数填writer对应Editor权限,填reader对应Viewer权限。
  • 通知邮件: 如果不想给目标用户发权限通知,把sendNotificationEmail设为False。
  • 共享驱动器适配: 如果你的Sheet在共享驱动器中,必须保留supportsAllDrives=True,否则会报错。

注意事项

  • 这个操作是新增权限,不会修改或删除任何已存在的权限,完全不会影响现有用户的访问权限。
  • 确保你的credentials.json文件已正确配置(从Google Cloud控制台下载)。

内容的提问来源于stack exchange,提问作者Tokyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:23:13