在Google Classroom API查询中列出30多名学生

问题描述 投票:2回答:1

此时,我有一个脚本可以正常列出Google课堂中的班级学生,但它没有列出所有学生,只列出了前30个。我需要它列出所有学生,无论多少有。我现在拥有以下内容:

function listStudents() {
  var s = SpreadsheetApp.getActiveSpreadsheet();
  var sh = s.getSheetByName('CLASS');
  var r = sh.getDataRange();
  var n = r.getNumRows();
  var d = r.getValues();
  for (x = 0; x < n; x++) {
    var i = d[x][0];
    if(i == ''){ continue; } else if (i == 'D') {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sh = ss.getSheetByName('LISTSTUDENTS');
      var tea = Classroom.Courses.Students.list(d[x][8]);
      var t = tea.students;
      var arr = [];

      try {
        for (i = 0; i < t.length; i++) {
          var c = t[i]; 
          var ids = c.profile;
          var em = ids.emailAddress;
          arr.push([em]);   
        }
      }
      catch (e) { continue; } 

      sh.getRange(d[x][14], d[x][15], arr.length, arr[0].length).setValues(arr);  
    }
  }
}
google-apps-script google-api google-classroom
1个回答
3
投票

您在查询中只收到30名学生,因为您只访问结果的第一页。几乎每个“高级服务”都以类似的方式对集合起作用,因为它们在调用中返回可变数量的项目(通常达到可以在查询中指定的大小,但是有限制)。这是为了确保每个使用它的人都能及时获得服务。

例如,考虑Bob(来自Accounting)。这种请求分页方式意味着他不能请求包含20,000个项目的单个响应,在此期间,其他人的服务速度较慢。但是,他可以要求接下来的100件物品,200次。虽然Bob从他最近的查询中消耗了这100个项目,但其他人可以在不中断的情况下使用该服务。

要进行此设置,您需要使用保证至少执行一次的代码循环,并使用nextPageToken调用.list()来控制循环。在Javascript / Google Apps脚本中,这可以是do .. while循环:

// Runs once, then again until nextPageToken is missing in the response.
const roster = [],
    // The optional arguments pageToken and pageSize can be independently omitted or included.
    // In general, 'pageToken' is essentially required for large collections.
    options = {pageSize: /* reasonable number */};

do {
  // Get the next page of students for this course.
  var search = Classroom.Courses.Students.list(courseId, options);

  // Add this page's students to the local collection of students.
  // (Could do something else with them now, too.)
  if (search.students)
    Array.prototype.push.apply(roster, search.students);

  // Update the page for the request
  options.pageToken = search.nextPageToken;
} while (options.pageToken);
Logger.log("There are %s students in class # %s", roster.length, courseId);
© www.soinside.com 2019 - 2024. All rights reserved.