google-app-engine - 如何从 Google App Engine 调用 Google Cloud Function?
问题描述
我有一个 App Engine 项目。
我也有一个谷歌云功能。
我想从 App Engine 项目中调用该 Google Cloud Function。我似乎无法让它发挥作用。
是的,如果我将函数完全公开(即,将云函数设置为“允许所有流量”并为“allUsers”创建规则以允许调用该函数),它就可以工作。但是如果我限制这两个设置中的任何一个,它会立即停止工作,我会得到 403。
应用程序和函数在同一个项目中,所以我至少假设将函数设置为“仅允许内部流量”应该可以正常工作,前提是我有一个“allUsers”规则允许调用该函数。
这是如何运作的?通常如何从 Google App Engine 调用(非公开)Google Cloud Function?
解决方案
您需要一个 auth 标头来 ping 函数 url。它应该看起来像:
headers = {
....
'Authorization': 'Bearer some-long-hash-token'
}
以下是获取令牌的方法:
import requests
token_response = requests.get(
'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=' +
'https://[your zone]-[your app name].cloudfunctions.net/[your function name]',
headers={'Metadata-Flavor': 'Google'})
return token_response.content.decode("utf-8")
“仅允许内部流量”无法按预期工作。我的 App Engine 应用与函数在同一个项目中,但它不起作用。我不得不打开“允许所有流量”,并使用标题方法。
例子:
def get_access_token():
import requests
token_response = requests.get(
'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=' +
'https://us-central1-my_app.cloudfunctions.net/my_function',
headers={'Metadata-Flavor': 'Google'})
return token_response.content.decode("utf-8")
def test():
url_string = f"https://us-central1-my_app.cloudfunctions.net/my_function?message=it%20worked"
access_token = get_access_token()
print(
requests.get(url_string, headers={'Authorization': f"Bearer {access_token}"}
)
推荐阅读
- python-3.x - WEBScraping TypeError:sendmail()缺少1个必需的位置参数:'msg'
- python - 在 PLY 中使用常规定义
- wordpress - WordPress 恶意软件 - 重定向到 (fast.destinyfernandi.com) - 即使在扫描和清理之后
- python - 无法通过 pip install 安装软件包(pywin32、win10toast 和许多其他)
- android - 使用 GSON 时出现 java.lang.IllegalArgumentException
- java - 重启服务器和solr undefined field subtitle
- postgresql - 原因:org.postgresql.util.PSQLException:long 类型的值错误:\x
- javascript - 如何根据角色动态显示菜单选项
- mongodb - 如何在多个集合上实现对 spring 数据 mongodb 的排序?
- c# - 在新创建的团队中进行测试时,Teams UpdateActivity 事件的差异