【问题标题】:Create a Google Cloud Platform budget via a Cloud Function通过 Cloud Function 创建 Google Cloud Platform 预算
【发布时间】:2019-12-14 20:34:36
【问题描述】:

我想通过一个用 Python 编写的云函数来利用 beta BillingBudgets API。使用Billing API,使用 API 更新项目的账单非常简单......

from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()    
from apiclient import discovery
service = discovery.build('cloudbilling', 'v1', credentials=credentials, cache_discovery=False)
billing_info = service.projects().updateBillingInfo(name='projects/{}'.format(projectID), body={'billingAccountName': 'billingAccounts/000000-AAAAAA-BBBBBB'}).execute()

但是,尝试使用 BillingBudgets API 创建预算,例如...

from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
from apiclient import discovery
service = discovery.build('billingbudgets', 'v1beta1', credentials=credentials, cache_discovery=False)
budget_info = service.budgets().create('billingAccounts/000000-AAAAAA-BBBBBB/budgets', body={longJSONStringHere}).execute()

...因“'Resource' 对象没有属性 'billing'”而失败。浏览 API 并使用对象语法和结构并没有产生任何结果。从文档中可以看出,这个 API 还没有客户端库,所以我目前假设这将在未来工作,我现在正在寻找一种利用 API 的替代方法。

我可以使用 REST 和 OAuth 成功地直接使用 API,但我正在努力制定如何在云函数中实现这一点。目前,我的 requirements.txt 中有以下内容,并且正在尝试研究如何将 Rest API 与 OAuth 结合使用。

google-api-python-client==1.7.4
oauth2client==4.1.3
google-auth-httplib2==0.0.3

欢迎任何代码 sn-ps、想法或建议。

【问题讨论】:

    标签: google-cloud-platform google-cloud-functions google-oauth google-cloud-billing


    【解决方案1】:

    我自己试过了,好像错误就在这一行:

    预算信息 = service.budgets().create('billingAccounts/000000-AAAAAA-BBBBBB/budgets', body={longJSONStringHere}).execute()

    您在此服务路径上缺少billingAccounts 资源,您可以通过像这样添加它来修复它,它应该可以工作:

    预算信息 = service.billingAccounts().budgets().create('billingAccounts/000000-AAAAAA-BBBBBB/budgets', body={longJSONStringHere}).execute()

    我注意到的另一件事是,您正在使用oauth2client 库来检索应用程序的默认凭据,但是该库已被弃用。

    相反,您应该为此使用 google-auth 库,您只需更改代码以检索凭据,如下所示:

    import google.auth
    
    credentials, project_id = google.auth.default()
    

    【讨论】:

      【解决方案2】:

      我终于明白了。

      # for Cloud Functions use
      def get_service():
          import googleapiclient.discovery
          return googleapiclient.discovery.build('compute', 'v1',  cache_discovery=False)
      

      requirements.txt

      google-api-python-client
      oauth2client
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-05
        • 1970-01-01
        • 2021-03-25
        • 1970-01-01
        • 2021-04-08
        • 1970-01-01
        • 2018-02-18
        相关资源
        最近更新 更多