【问题标题】:How to use Google sheets API while inside a google cloud function如何在谷歌云功能中使用谷歌表格 API
【发布时间】:2017-11-10 21:29:16
【问题描述】:

我正在试用 Google 的 Cloud Functions 服务,我想阅读和编写 Google 电子表格,但似乎找不到任何示例或方法来做到这一点。

我的问题源于 Google 云函数的示例 javascript 是:

exports.helloWorld = function helloWorld (req, res) {
  res.send(`Hello ${req.body.name || 'World'}!`);
};

这可行,但我想做谷歌的例子,从谷歌电子表格中读取:

  gapi.load('client:auth2', initClient);

  function initClient() {
    gapi.client.init({
      discoveryDocs: DISCOVERY_DOCS,
      clientId: CLIENT_ID,
      scope: SCOPES
    }).then(function () {
      // Listen for sign-in state changes.
      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

      // Handle the initial sign-in state.
              gapi.client.sheets.spreadsheets.values.get({
      spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
      range: 'Class Data!A2:E',
    }).then(function(response) {
      var range = response.result;
      if (range.values.length > 0) {
        appendPre('Name, Major:');
        for (i = 0; i < range.values.length; i++) {
          var row = range.values[i];
          // Print columns A and E, which correspond to indices 0 and 4.
          appendPre(row[0] + ', ' + row[4]);
        }
      } else {
        appendPre('No data found.');
      }
    }, function(response) {
      appendPre('Error: ' + response.result.error.message);
    });
    });
  }

有谁知道这是否可行,或者有一个例子说明如何做类似的事情?

【问题讨论】:

    标签: javascript google-cloud-platform google-cloud-functions


    【解决方案1】:

    我找到了一种方法来做到这一点,其自动身份验证方式与 other services 可以做到的方式相同。

    在 NodeJS API README 中,他们有一个 auto-auth example,我们可以像这样将其应用于 Sheets API:

    index.js:

    const { google } = require('googleapis');
    const { promisify } = require('util');
    
    exports.main = (req, res) => {
      google.auth.getClient({
        scopes: ['https://www.googleapis.com/auth/spreadsheets'],
      }).then(auth => {
        const api = google.sheets({ version: 'v4', auth });
        const getSheets = promisify(api.spreadsheets.get.bind(api.spreadsheets));
        return getSheets({ spreadsheetId: 'SPREADSHEET_ID' });
      })
        // This just prints out all Worksheet names as an example
        .then(({ data: { sheets } }) => {
          res.status(200).send({ sheets });
        })
        .catch(err => {
          res.status(500).send({ err });
        })
    };
    

    package.json:

    {
      "dependencies": {
        "googleapis": "^42"
      }
    }
    

    最后,与运行云功能的服务帐户的电子邮件地址共享工作表。

    google.auth.getClient 在该示例中将检测附加到云功能的服务帐户的凭据。因此,您可以与 Sheets API 进行交互,而无需管理任何身份验证机密。

    地方发展

    如果将 .env 变量 GOOGLE_APPLICATION_CREDENTIALS 设置为 service account credentials JSON file 的路径,则可以对 local development 使用相同的代码。

    例如,当您的代码在本地开发者机器上运行时,将创建一个 JWT auth 客户端,而当相同代码在配置的 Google Compute Engine 实例上运行时,将创建一个 Compute 客户端

    https://github.com/googleapis/google-api-nodejs-client#service-to-service-authentication

    GOOGLE_APPLICATION_CREDENTIALS="/path/to/myapp-375951-sa01517d6251.json"
    

    https://cloud.google.com/docs/authentication/getting-started#setting_the_environment_variable

    【讨论】:

    • 有与此等价的python吗?
    • @JanKrynauw 我不懂 Python,但看起来你可以使用 this example 但使用 google-auth 而不是 oauth2client
    • 我已经尝试过了,但没有成功,并在此处发布了详细信息:stackoverflow.com/questions/51886522/…
    • @Matt,知道了,谢谢!我会更新我的答案并指向你的。我真的很喜欢你的方法。
    • 感谢这篇文章。阅读本文后,我的电子表格会在几分钟内更新。定义。一个可以接受的答案。
    【解决方案2】:

    以下是我使用 Google Cloud Functions 的方法。我认为 OAuth 不太适合,因为 Cloud Functions 经常在无人值守的情况下运行。幸运的是,有服务帐户,用于机器对机器的通信。


    1。在您的 Cloud 项目中创建服务帐号


    2。保存服务帐号密钥

    在第 1 步中,将 JSON 格式的密钥文件下载到您的计算机上。将其保存在您的项目目录中并重命名为credentials.json。


    3。创建 API 密钥


    4。保存 API 密钥

    复制步骤 3 中的 API 密钥并将其保存在项目目录中名为 api_key.json 的文件中。它应该是这样的:

    {
      "key": "<PASTE YOUR API KEY HERE>"
    }
    

    5。授予对服务帐号的电子表格访问权限

    与在步骤 1 中创建的服务帐户电子邮件共享电子表格。


    6。调用 Google 的 Sheets API

    这是我的代码,每次调用云函数时都会在电子表格中附加一行。

    const {google} = require('googleapis');
    
    exports.reply = (req, res) => {
      var jwt = getJwt();
      var apiKey = getApiKey();
      var spreadsheetId = '<PASTE YOUR SPREADSHEET ID HERE>';
      var range = 'A1';
      var row = [new Date(), 'A Cloud Function was here'];
      appendSheetRow(jwt, apiKey, spreadsheetId, range, row);
      res.status(200).type('text/plain').end('OK');
    };
    
    function getJwt() {
      var credentials = require("./credentials.json");
      return new google.auth.JWT(
        credentials.client_email, null, credentials.private_key,
        ['https://www.googleapis.com/auth/spreadsheets']
      );
    }
    
    function getApiKey() {
      var apiKeyFile = require("./api_key.json");
      return apiKeyFile.key;
    }
    
    function appendSheetRow(jwt, apiKey, spreadsheetId, range, row) {
      const sheets = google.sheets({version: 'v4'});
      sheets.spreadsheets.values.append({
        spreadsheetId: spreadsheetId,
        range: range,
        auth: jwt,
        key: apiKey,
        valueInputOption: 'RAW',
        resource: {values: [row]}
      }, function(err, result) {
        if (err) {
          throw err;
        }
        else {
          console.log('Updated sheet: ' + result.data.updates.updatedRange);
        }
      });
    }
    

    希望这会有所帮助!

    【讨论】:

    • 也许这可以通过 NPM 手动在 Node.JS 的本地副本上添加 Sheet API 来工作,但这个功能不能在 Google 中部署,我已经尝试过,但云环境无法识别 'googleapis '。
    • Axel,当我将上面的代码部署到 Google 时,它​​适用于我。您提到服务器无法识别“googleapis”。起初我也遇到了这个错误,当时我在上面第一行的“google”周围省略了花括号。另一件要检查的事情:您是否 npm install googleapis 使其进入您的 package-lock.json 文件,并与您的代码一起部署?
    • 是的,我也是这样解决问题的。代码确实需要一些更新才能使用新的 API。自从我使用它已经有一段时间了,我忘记了需要以不同方式完成的事情,尤其是在 Google 控制台中,但我让一切正常,现在它正在生产中。
    • 至今仍在工作。非常简单易懂。非常感谢你!
    • 获取 API key 的选项在 Google Cloud Console 中不再可用,或者我猜它已移至其他地方。
    【解决方案3】:

    我已经浏览了几个小时的网络,寻求有关如何将 Google Sheets API 与 Firebase Cloud Functions 集成的帮助。

    幸运的是,我在 Medium 上找到了这篇关于这个主题的帖子:

    https://medium.com/@elon.danziger/fast-flexible-and-free-visualizing-newborn-health-data-with-firebase-nodejs-and-google-sheets-1f73465a18bc

    【讨论】:

    • 您需要添加更多关于如何在没有链接的情况下解决问题的详细信息(链接将来可能会损坏)。
    • 这里是缓存的链接,以防万一它真的坏了,另一个选择是互联网存档webcache.googleusercontent.com/…
    猜你喜欢
    • 2017-11-14
    • 1970-01-01
    • 2020-10-14
    • 2019-09-19
    • 1970-01-01
    • 2022-12-17
    • 2018-12-11
    • 2019-06-14
    • 1970-01-01
    相关资源
    最近更新 更多