我想从Google Cloud Functions中触发一些Google Cloud API。你能告诉我怎么做吗?如何获得认证TOken和所有这一切?
如果有人有一些示例用例,那就太好了。
发布于 2020-10-21 14:55:10
正如doc中所解释的
(您可以通过使用服务帐户代表您从Cloud Function访问Google Cloud Platform API。服务帐户为您的功能提供应用程序默认凭据。
..。
使用应用程序默认凭据的API客户端库在运行时自动从Cloud Functions主机获取内置服务帐户凭据。默认情况下,客户端使用YOUR_PROJECT_ID@appspot.gserviceaccount.com
服务帐户进行身份验证。
因此,您不需要获取身份验证令牌。
您可以在官方Firebase Cloud Functions示例页面中找到几个示例。例如,对于Translate API为this one,对于Vision API为this one。
在Cloud Functions doc (它涵盖了用Python或Java编写的云函数)中也有一组示例。
发布于 2020-10-21 17:23:54
我认为您可以使用类似于此代码的内容。
它没有经过测试。
例如,调用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())
https://stackoverflow.com/questions/64457344
复制相似问题