python - 从谷歌表格触发云功能(通过谷歌应用脚本)
问题描述
我一直在尝试(几乎没有成功)通过来自谷歌表(谷歌应用程序脚本)的 http 请求触发谷歌云功能,但它似乎不起作用。一些重要的事情:
- 仅当用户来自我的组织时,该功能才应运行
- 不必邀请用户加入 GCP 项目
我知道这可以在 google colabs 和 Python 中很容易地完成。以下脚本将让我组织中不在GCP 项目中的用户触发云功能:
import requests
import google.auth
from google.auth.transport.requests import Request
from google.colab import auth
credentials, project_id = google.auth.default()
request = Request()
credentials.refresh(request=request)
GCF_URL = ''https://project_location-project_id.cloudfunctions.net/name-of-your-funciton''
resp = requests.get(GCF_URL, headers={'Authorization': f'Bearer {credentials.id_token}'})
这将对我组织内的任何用户起作用并触发云功能,但不适用于我的个人电子邮件。
现在,我想在谷歌应用程序脚本中复制这种行为,以便有权访问该工作表的最终用户只要是我组织的成员就可以触发云功能。
我尝试了一些我在网上看到的东西,例如这个例子:
function callExternalUrl() {
var url = 'https://project_location-project_id.cloudfunctions.net/name-of-your-funciton';
var oauthToken = ScriptApp.getOAuthToken(); // get the user who's logged into Google Sheet's OAuth token
const data = {
oauthToken, // 1. add the oauth token to the payload
activeUser: param.user // 2. this here is important as it adds the userinfo.email scope to the token
// any other data you need to send to the Cloud Function can be added here
};
var options = {
'method' : 'get', // or post, depending on how you set up your Cloud Function
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)
};
const response = UrlFetchApp.fetch(url, options);
Logger.log('Response Code: ' + response.getResponseCode());
}
这会产生 403 错误,但如果我将其更改为以正确格式提供 OAuth,如下所示:
function callExternalUrl() {
var url = 'https://project_location-project_id.cloudfunctions.net/name-of-your-funciton';
var oauthToken = ScriptApp.getOAuthToken(); // get the user who's logged into Google Sheet's OAuth token
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + oauthToken
}
});
// const response = UrlFetchApp.fetch(url, options);
Logger.log('Response Code: ' + response.getResponseCode());
}
我得到一个 401(即授权失败)。现在,似乎我只需要从用户那里获得正确的身份验证才能发送此请求以使其正常工作。我已经看到了这个 github repo,它专注于从谷歌应用程序脚本(https://github.com/gsuitedevs/apps-script-oauth2)获取 OAuth2,但我似乎也无法让它工作,它必须以某种我不知道的方式适应云。
我读过了
通过 Google Apps 脚本安全地调用 Google Cloud 函数
这非常相似,但似乎没有找到问题的根源,关于如何使这个过程成为可能的任何输入?
解决方案
推荐阅读
- vimeo - 如果视频上传成功,是否有任何回调选项用于通知?
- node.js - 在 Docker 上安装 npm 得到错误不支持 Node.js v13
- binary - 创建一个 dvar 布尔约束
- typescript - 如何过滤父类型以便在 TypeScript 中选择给定类型的子类型?
- python - 如何使用 groupby + stack 获得相当于 pandas 的融化?
- c++ - 如何从 TBB concurrent_hash_map C++ 中迭代和擦除
- c++ - 为什么在这段代码中使用 auto 和 int 会给出不同的答案?
- python - 创建 dask_jobqueue 调度程序以在自定义 HPC 上启动
- python - 需要使用 argparse 传递带单引号的字符串参数
- distributed-computing - 是否有没有主集群/服务器的服务注册表?