首页 > 解决方案 > 如何从 Google App Engine 调用 Google Cloud Function?

问题描述

我有一个 App Engine 项目。

我也有一个谷歌云功能。

我想从 App Engine 项目中调用该 Google Cloud Function。我似乎无法让它发挥作用。

是的,如果我将函数完全公开(即,将云函数设置为“允许所有流量”为“allUsers”创建规则以允许调用该函数),它就可以工作。但是如果我限制这两个设置中的任何一个,它会立即停止工作,我会得到 403。

应用程序和函数在同一个项目中,所以我至少假设将函数设置为“仅允许内部流量”应该可以正常工作,前提是我有一个“allUsers”规则允许调用该函数。

这是如何运作的?通常如何从 Google App Engine 调用(非公开)Google Cloud Function?

标签: google-app-enginegoogle-cloud-functionsgoogle-authentication

解决方案


您需要一个 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}"}
    )

推荐阅读