【问题标题】:Write alert policies list in Cloud Storage with cloud functions使用云功能在 Cloud Storage 中编写警报策略列表
【发布时间】:2021-11-15 04:41:37
【问题描述】:

我想在云存储中的 json 文件中编写警报策略列表。我有下面的脚本:

def my_function(request):
    alert_client = monitoring_v3.AlertPolicyServiceClient()
    storage_client = storage.Client()
    project_name = 'projects/my_project'
    bucket_name = 'test'

    policies = alert_client.list_alert_policies(name=project_name)
    for policy in policies:
        print(policy)
        destination_blob_name = 'test'
        bucket = storage_client.bucket(bucket_name)
        blob = bucket.blob(destination_blob_name)
        blob.upload_from_string("{}".format(json.dumps(policy)))

此脚本不起作用并返回以下错误:TypeError: Object of type AlertPolicy is not JSON serializable"

现在有几件事:

  • 使用 API 资源管理器或查看 documentation 来自列表方法的响应应该很容易处理。但是,我正在用 Python 编写我的云函数,但响应似乎有所不同。
  • 我知道分页的处理方式有些问题,但我不知道如何处理。
  • 我可以print(policies) 但日志输出有点奇怪,json 对象的每个元素都有一行。这是为什么?这是什么意思?
  • 如何处理此响应?这里有通用方法还是 API 特有的方法?
  • 我仍然能够独立访问每个变量policy.namepolicy.conditions 等...是否意味着我必须手动重建我想要的 json 对象?

【问题讨论】:

  • 如果您使用 fe 将策略转换为字符串会发生什么:blob.upload_from_string("{}".format(json.dumps(str(policy))))
  • 它在技术上可以正常工作,但输出非常混乱,很难使用。

标签: python json google-cloud-platform google-cloud-monitoring


【解决方案1】:

根据警报策略服务的 googleapis documentation,使用 list_alert_policies() 迭代警报策略列表会自动解析响应的后续页面。您不必担心根据文档实现分页逻辑:

返回:ListAlertPolicies 响应的协议。迭代此对象将产生结果并自动解析其他页面。 source

至于typeAlertPolicy,它本身似乎无法转换为JSON。您可能必须通过调用返回的 AlertPolicy 对象的相应属性来构建 JSON 对象,或者您也可以实现类似于此 ProtoEncoder class 的东西,这似乎从 AlertPolicy 类型返回 JSON。至于AlertPolicy 对象的可用属性,here is the source

class ProtoEncoder(json.JSONEncoder):
    """Encode protobufs as json."""

    def default(self, obj):
        if type(obj) in (monitoring_v3.AlertPolicy, monitoring_v3.NotificationChannel):
        text = proto.Message.to_json(obj)
        return json.loads(text)
    return super(ProtoEncoder, self).default(obj)

【讨论】:

    猜你喜欢
    • 2021-11-28
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多