2

I am using gspread library to access and edit google sheets via python. Is there a good way to handle race conditions ( not necessarily using gspread only ) when there may be multiple workers writing to the same sheet.

I use a Django server which will accept requests to edit or update the sheet, in case multiple requests come, can I use some locking mechanism so that I have only one worker accessing the sheet at a time, while other will keep waiting to acquire the lock and get the access when the previous workers are done editing the sheet.

Raj Malhotra
  • 89
  • 1
  • 11

1 Answers1

1

You may use the Class Protection to access and modify protected ranges and sheets. It was also reported as feature request (fixed).

A protected range can protect either a static range of cells or a named range. A protected sheet may include unprotected regions.

Protect range A1:B10, then remove all other users from the list of editors.

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

Ensure the current user is an editor before removing others. Otherwise, if the user's edit permission comes from a group, the script throws an exception upon removing the group.

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

Remove all range protections in the spreadsheet that the user has permission to edit.

   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();
      }
    }

Protect the active sheet, then remove all other users from the list of editors.

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

Ensure the current user is an editor before removing others. Otherwise, if the user's edit permission comes from a group, the script throws an exception upon removing the group.

var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}
abielita
  • 13,147
  • 2
  • 17
  • 59
  • Thank you for the help. The above code will support only one user accessing region of the sheet, but in my application, there is only one user ( I use google auth private key of a google account ) to edit the sheet. however, multiple requests could come for editing the sheet by different clients. Wanted to know if we have a locking mechanism on top such that only when one client completes editing the sheet, other clients' request is taken. Thanks a lot for the answer, will try to see if I can fit in my present problem. – Raj Malhotra Oct 16 '18 at 06:15