2.3.3. Get
get
方法检索单个对象的表示。
以下示例找到并检索具有标识符 123
的虚拟机表示:
结果将是相应类型的实例。在本例中,结果是 Ruby 类 Vm 的实例。
某些服务的 get
方法支持额外的参数,它们控制如何检索对象的表示方式,或者如果有多个服务的表示方式。
例如,您可能需要在引导后检索虚拟机的未来状态。管理虚拟机的服务的 get
方法支持 next_run 布尔值参数:
检索虚拟机的 next_run
状态
Retrieve the representation of the virtual machine; not the current one, but the one that will be used after the next boot:
# Retrieve the representation of the virtual machine; not the
# current one, but the one that will be used after the next
# boot:
vm = vm_service.get(next_run: true)
详情请查看软件开发工具包的 参考文档。
如果无法检索对象,则软件开发工具包将引发 Error 异常,其中包含故障的详细信息。如果您尝试检索不存在的对象,会出现这种情况。
注意
对 服务 locator
方法的调用永远不会失败,即使对象不存在,因为 服务 locator
方法不会将请求发送到服务器。
在以下示例中,服务 locator 方法将
成功,而 get
方法会引发异常:
查找不存在的虚拟机服务: No Error
Find the service that manages a virtual machine that does not exist. This will succeed.
# Find the service that manages a virtual machine that does
# not exist. This will succeed.
vm_service = vms_service.vm_service('non_existent_VM')
检索不存在的虚拟机服务:错误
Retrieve the virtual machine. This will raise an exception.
# Retrieve the virtual machine. This will raise an exception.
vm = vm_service.get