【问题标题】:Trigger Google Cloud APIs from Cloud Functions从 Cloud Functions 触发 Google Cloud API
【发布时间】:2021-02-04 00:01:02
【问题描述】:

我想从 Google Cloud Functions 触发一些 Google Cloud API。你能帮我怎么做吗?如何获得 Auth TOken 以及所有这些?

如果有人有一些很好的示例用例。

【问题讨论】:

    标签: google-cloud-functions


    【解决方案1】:

    我认为您可以使用类似于此代码的内容。

    它没有经过测试。

    例如拨打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())  
    
    
    

    【讨论】:

    • 嗨,玛丽安,感谢您的回答,我尝试使用上述方法。它正在生成 access_token,但是当我运行发布请求时,它给出了“错误 401(未经授权)”。这里缺少什么?
    • 我认为您应该使用具有“roles/datafusion.admin”角色的服务帐户部署您的云功能。 Access control。据我了解,如果您使用具有正确角色的服务帐户部署云功能,则不需要令牌即可访问 api。
    • 嗨,玛丽安,我已经检查过,与我的函数关联的角色已附加了云数据融合管理员。我正在点击“enterprise-datafusion-downlight-datafusion-xxxx-dot-use1.datafu…”api 来触发数据融合管道
    【解决方案2】:

    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)。

    【讨论】:

    • 嗨 Ranaud,实际上我想从此处引用的 Cloud Functions 触发数据融合管道:cloud.google.com/data-fusion/docs/reference/cdap-reference 这是一个休息 api,我在 google.cloud 中没有看到任何数据融合的东西。我如何通过 Cloud Fucntions 实现这一目标?
    • 嗯,这是一个不同的问题。您当前问题的标题是“从 Cloud Functions 触发 Google Cloud API”。我不知道如何从 Cloud Functions 触发数据融合管道。您可以提出一个包含所有这些详细信息的新问题。
    • @SUDHIRGARG 你可以直接使用the REST API (add an access token to your request header) or the discovery API。如果您需要更多指导,请告诉我您的语言,我可以与您分享代码示例。
    • 嗨 Guallaume,我正在使用 Python on Cloud fucntions 进行编码
    猜你喜欢
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    相关资源
    最近更新 更多