搜索

2.3.2. 服务方法

download PDF

找到您想要的服务后,您可以调用其服务方法。这些方法向服务器发送请求并执行实际工作。

管理对象集合的服务通常具有 列表和 添加 方法。

管理单个对象的服务通常具有 获取更新和删除 方法。

服务可能具有额外的操作方法,方法可在检索、创建、更新或删除之外执行操作。这些方法最常用于管理单个对象的服务。

2.3.2.1. Get

get 方法检索单个对象的表示。

以下示例查找并检索带有标识符 123 的虚拟机的表示:

# Find the service that manages the virtual machine:
vms_service = system_service.vms_service
vm_service = vms_service.vm_service('123')

# Retrieve the representation of the virtual machine:
vm = vm_service.get

其结果将是对应类型的实例。在本例中,结果是 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:
vm = vm_service.get(next_run: true)

详情请参阅软件开发套件的 参考文档

如果无法检索对象,软件开发套件将引发错误 异常,其中包含失败的详细信息。如果您试图检索不存在的对象,会出现这种情况。

注意

调用 service locator 方法永远不会失败,即使对象不存在,因为服务 locator 方法不会向服务器发送请求。

在以下示例中,service locator 方法可以成功,而 get 方法会产生异常:

找到不存在的虚拟机的服务:no Error

# 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.
vm = vm_service.get

Red Hat logoGithubRedditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

© 2024 Red Hat, Inc.