【问题标题】:Handling race condition in Google Sheets在 Google 表格中处理竞争条件
【发布时间】:2018-08-22 07:11:30
【问题描述】:

我正在使用 gspread 库通过 python 访问和编辑谷歌表格。当可能有多个工作人员写入同一张表时,是否有一种处理竞争条件的好方法(不一定只使用 gspread)。

我使用一个 Django 服务器,它将接受编辑或更新工作表的请求,如果有多个请求来,我可以使用一些锁定机制,以便我一次只有一个工作人员访问工作表,而其他工作人员将继续等待在以前的工作人员完成编辑工作表时获取锁并获得访问权限。

【问题讨论】:

    标签: django concurrency google-sheets-api gspread


    【解决方案1】:

    您可以使用Class Protection 访问和修改受保护的范围和工作表。它也被报告为feature request(已修复)。

    受保护的范围可以保护静态单元格范围或命名范围。受保护的工作表可能包含未受保护的区域。

    保护范围 A1:B10,然后从编辑器列表中删除所有其他用户。

    var ss = SpreadsheetApp.getActive();
    var range = ss.getRange('A1:B10');
    var protection = range.protect().setDescription('Sample protected range');
    

    在删除其他用户之前,请确保当前用户是编辑者。否则,如果用户的编辑权限来自某个组,则脚本会在删除该组时抛出异常。

    var me = Session.getEffectiveUser();
    protection.addEditor(me);
    protection.removeEditors(protection.getEditors());
    if (protection.canDomainEdit()) {
      protection.setDomainEdit(false);
    }
    

    删除用户有权编辑的电子表格中的所有范围保护。

       var ss = SpreadsheetApp.getActive();
        var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
        for (var i = 0; i < protections.length; i++) {
          var protection = protections[i];
          if (protection.canEdit()) {
            protection.remove();
          }
        }
    

    保护活动工作表,然后从编辑器列表中删除所有其他用户。

    var sheet = SpreadsheetApp.getActiveSheet();
    var protection = sheet.protect().setDescription('Sample protected sheet');
    

    在删除其他用户之前,请确保当前用户是编辑者。否则,如果用户的编辑权限来自某个组,则脚本会在删除该组时抛出异常。

    var me = Session.getEffectiveUser();
    protection.addEditor(me);
    protection.removeEditors(protection.getEditors());
    if (protection.canDomainEdit()) {
      protection.setDomainEdit(false);
    }
    

    【讨论】:

    • 感谢您的帮助。上面的代码将只支持一个用户访问工作表的区域,但在我的应用程序中,只有一个用户(我使用 google 帐户的 google auth 私钥)来编辑工作表。但是,不同的客户可能会提出多个请求来编辑工作表。想知道我们是否在顶部有一个锁定机制,只有当一个客户完成编辑工作表时,才会接受其他客户的请求。非常感谢您的回答,会尝试看看我是否能解决我目前的问题。
    猜你喜欢
    • 2011-04-01
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 2012-01-26
    相关资源
    最近更新 更多