首页 > 解决方案 > 为什么 azure-sdk-for-python 返回对象

问题描述

我最近开始研究适用于 Azure 的 SDK,但无法弄清楚为什么每个方法(由我测试)都返回一个对象,而不是更“人性化”的东西,即列表或字典。

IE:

list(compute_client.virtual_machines.list_all())
[<azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93c190>, <azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93c750>, <azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93cad0>, <azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93ced0>]

返回似乎很难与之交互的对象有什么好处,即我需要查找每个方法以查找返回值等以处理列表,然后构建字典,这似乎需要更多的工作。

我在Microsoft 博客/github之一中找到了这种方法:

def print_item(group):
    """Print a ResourceGroup instance."""
    print("\tName: {}".format(group.name))
    print("\tId: {}".format(group.id))
    print("\tLocation: {}".format(group.location))
    print("\tTags: {}".format(group.tags))
    print_properties(group.properties)

IMO似乎效率很低,无法打印另一种方法的返回值。

有人可以建议为什么“对象列表”比“列表”更好,为什么不返回像 json 之类的东西。

标签: pythonazure

解决方案


简短的回答:从任何实例只需调用as_dict()即可获取对象的 dict 视图。

长答案:您获得的对象不仅仅是初始 JSON 的简单包装器。它是由一个OpenAPI解析产生的,它负责:

  • 多态性
  • 类型化文字(日期时间、枚举等)
  • XML/JSON。无论使用何种初始媒体,该对象都是相同的,具体取决于端点的 Content-Type。

对象本身包含几种方法,使其比简单的 dict 更复杂,例如validate在构建模型时验证模型是否正确(即构建具有实时验证的 Web 表单)。

但是,作为消费者,Python 用户和您一样喜欢 dict,这就是该as_dict()方法的目的。此方法甚至需要一个回调(访问者模式)以允许动态更改您将从该方法获得的 dict 序列化。

(我在 Azure SDK Python 团队的 MS 工作)

编辑:在list操作的情况下,您将获得一个 Python 迭代器,它可以免费为您处理分页。您甚至不知道何时获取第二页。对于内存消耗,当您将其包装成 a 时,您会list()立即将所有内容加载到内存中。如果您使用 a for vm in compute_client.virtual_machines.list_all(),那么您在内存中一次只有一页,而不是更多。如果你只需要几个对象,如果你有很多虚拟机来利用迭代器(无论使用for循环还是next()异常StopIteration) ,if 会更快


推荐阅读