【发布时间】:2021-02-04 00:01:02
【问题描述】:
我想从 Google Cloud Functions 触发一些 Google Cloud API。你能帮我怎么做吗?如何获得 Auth TOken 以及所有这些?
如果有人有一些很好的示例用例。
【问题讨论】:
我想从 Google Cloud Functions 触发一些 Google Cloud API。你能帮我怎么做吗?如何获得 Auth TOken 以及所有这些?
如果有人有一些很好的示例用例。
【问题讨论】:
我认为您可以使用类似于此代码的内容。
它没有经过测试。
例如拨打Method: projects.locations.instances.get
def make_func(request):
# Get the access token from the metadata server
metadata_server_token_url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token?scopes=https://www.googleapis.com/auth/cloud-platform'
token_request_headers = {'Metadata-Flavor': 'Google'}
token_response = requests.get(metadata_server_token_url, headers=token_request_headers)
token_response_decoded = token_response.content.decode("utf-8")
jwt = json.loads(token_response_decoded)['access_token']
# Use the api you mentioned to create the function
response = requests.post('https://datafusion.googleapis.com/v1beta1/projects/your-project/locations/us-central1/instances/your-instance',
headers={'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer {}'.format(jwt)} )
if response:
return 'Success! Function Created'
else:
return str(response.json())
【讨论】:
如doc中所述:
(您可以)通过使用 服务帐户代表您行事。服务帐户提供 您的函数的应用程序默认凭据。
...
使用应用程序默认凭据的 API 客户端库 自动从 Cloud Functions 在运行时托管。默认情况下,客户端进行身份验证 使用
YOUR_PROJECT_ID@appspot.gserviceaccount.com服务帐号。
因此,您不需要获取 Auth Token。
您可以在官方 Firebase Cloud Functions 示例页面中找到几个示例。例如,this one 用于 Translate API,this one 用于 Vision API。
Cloud Functions doc 中还有一组示例(涵盖了用 Python、Go 或 Java 编写的 Cloud Functions)。
【讨论】: