【问题标题】:How do I use the drive.file scope for a standalone google apps script如何将 drive.file 范围用于独立的谷歌应用程序脚本
【发布时间】:2021-10-18 03:23:19
【问题描述】:

我有一个使用 Sheets API 的独立脚本。只有两个调用:

SpreadsheetApp.openById(spreadsheetID).getSheetByName("Answers")
SpreadsheetApp.openById(otherspreadsheetID).getSheetByName("Questions").getDataRange().getValues()

所以它从一个文件读取并写入另一个文件。该脚本设置为像我一样作为 web 应用程序运行,因此在初始运行时,默认情况下,这会触发查看/编辑/删除所有工作表的广泛范围。我想限制它。我看到这是我可以手动设置的范围:https://www.googleapis.com/auth/drive.file (docs)。

但我不知道如何将我的两个电子表格设置为已由应用“打开或创建”的文件,以便范围对这些文件有效。我尝试创建一个创建两个新工作表的函数(我认为这算作“您使用此应用创建的驱动器文件”),但即使是 Spreadsheetapp.create() 函数也会引发“没有权限”错误。

我可能误解了这个范围是如何工作的?

【问题讨论】:

    标签: google-apps-script google-oauth google-sheets-api


    【解决方案1】:

    问题和解决方法:

    当使用SpreadsheetApp.openById() 时,使用https://www.googleapis.com/auth/spreadsheets 的范围。看来这是目前的规范。

    那么,作为一种解决方法,使用 Sheets API 怎么样?使用Sheets API时,可以使用https://www.googleapis.com/auth/drive.file的范围。

    作为重点,https://www.googleapis.com/auth/drive.file范围的官方文档如下。

    按文件访问应用程序创建或打开的文件。文件授权是按用户授予的,并在用户取消对应用的授权时撤销。

    因此,当您要使用https://www.googleapis.com/auth/drive.file 的范围从电子表格中检索数据时,首先需要由范围创建电子表格。在这个答案中,我想介绍以下流程。

    1. https://www.googleapis.com/auth/drive.file 的范围设置为 Google Apps 脚本项目。
    2. 创建一个新的电子表格。
    3. 从电子表格中检索值。

    用法:

    1。设置范围。

    请创建一个新的 Google Apps 脚本。根据您的问题,我了解到您使用的是独立类型。为此,请将https://www.googleapis.com/auth/drive.file 的范围设置为清单文件。 Ref 请将"oauthScopes": ["https://www.googleapis.com/auth/drive.file"] 添加到appsscript.json 的文件中。这样就可以使用特定的范围了。

    2。创建一个新的电子表格。

    在使用此脚本之前,please enable Sheets API at Advanced Google services。当您运行以下脚本时,会创建一个新的电子表格,您可以在日志中看到电子表格 ID。请复制身份证。此 ID 将在下一个脚本中使用。这样,https://www.googleapis.com/auth/drive.file 的范围内就会创建一个新的电子表格。

    function createNewSpreadsheet() {
      const id = Sheets.Spreadsheets.create({properties: {title: "sample"}}).spreadsheetId;
      console.log(id)
    }
    
    • 当您尝试从不是由该 Google Apps 脚本项目创建的现有电子表格中检索值时,会出现 Requested entity was not found. 错误。因此,在本节中,此 Google Apps 脚本项目将创建一个新的电子表格。

    3。从电子表格中获取值。

    在使用此脚本之前,请打开创建的电子表格并检查表格名称。并且,作为样本,请将样本值放入单元格中。当您运行以下脚本时,将从电子表格中检索值,您可以在日志中看到它们。

    function getValues() {
      const spreadsheetId = "###"; // Please set the spreadsheet ID.
      const obj = Sheets.Spreadsheets.Values.get(spreadsheetId, "Sheet1");
      const values = obj.values;
      console.log(values)
    }
    

    参考资料:

    【讨论】:

    • 感谢您的彻底回复。我最初基本上遵循该流程,但我的错误是我需要切换到 Sheets API 才能正确应用范围。
    猜你喜欢
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    相关资源
    最近更新 更多