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

如何通过gspread获取Google表格的两项所有者共享设置状态

获取Google表格的共享限制设置

gspread的list_permissions()仅能获取单个用户/角色的权限条目,你需要的两个全局共享限制属于文件元数据范畴,得通过调用Google Drive API的files.get接口来获取。

代码实现

首先确保你的gspread客户端拥有drive权限范围(授权时要包含https://www.googleapis.com/auth/drive,而非仅spreadsheets相关权限),然后用以下函数获取所需布尔值:

def get_sharing_restrictions(client, file_id):
    # 调用Drive API获取文件的restrictions字段
    response = client.request(
        "GET",
        f"https://www.googleapis.com/drive/v3/files/{file_id}",
        params={"fields": "restrictions"}
    )
    restrictions = response.get("restrictions", {})
    
    # 转换为目标布尔值:
    # 1. 编辑者是否可更改权限并共享:对应copyRequiresWriterPermission取反
    editors_can_manage_permissions = not restrictions.get("copyRequiresWriterPermission", False)
    # 2. 查看者/评论者是否可下载、打印、复制:对应viewersCanCopyContent取反
    viewers_can_download = not restrictions.get("viewersCanCopyContent", False)
    
    return {
        "editors_can_change_permissions_and_share": editors_can_manage_permissions,
        "viewers_commenters_can_download_print_copy": viewers_can_download
    }

# 使用示例
# 假设已初始化gspread客户端client
# file_id = "your-spreadsheet-id"
# settings = get_sharing_restrictions(client, file_id)
# print(settings["editors_can_change_permissions_and_share"])  # 输出True/False
# print(settings["viewers_commenters_can_download_print_copy"])  # 输出True/False

字段对应关系

  • copyRequiresWriterPermission:当该值为True时,仅文件所有者能更改权限和共享,编辑者无此权限;取反后就是你要的“编辑者是否可更改权限并共享”的结果。
  • viewersCanCopyContent:当该值为True时,查看者和评论者无法下载、打印或复制内容;取反后得到你需要的第二个布尔值。

注意点

  • 若OAuth授权范围仅包含spreadsheets相关权限,会触发权限错误,需在授权时添加drive权限。
  • 若文件未设置任何共享限制,restrictions字段可能为空,所以用dict.get()方法设置默认值,避免抛出KeyError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:30:44