使用开源 Python API 封装器与你的集群对话
API
![](/data/attachment/album/202305/07/232516w8j766mkp7pz7frl.png)



> 
> 结合开放的 API 和 Python 编程语言的力量。
> 
> 
> 


围绕 API 创建封装器的开源项目正变得越来越流行。这些项目使开发人员更容易与 API 交互并在他们的应用中使用它们。`openshift-python-wrapper` 项目是 [openshift-restclient-python](https://github.com/openshift/openshift-restclient-python) 的封装器。最初是一个帮助我们的团队使用 OpenShift API 的内部包，后来变成了一个[开源项目](https://github.com/RedHatQE/openshift-python-wrapper)（Apache 许可证 2.0）。


本文讨论了什么是 API 封装器，为什么它很有用，以及封装器的一些例子。


### 为什么要使用 API 封装器？


API 封装器是位于应用和 API 之间的一层代码。它通过将一些涉及发出请求和解析响应的复杂性抽象出来，以简化 API 访问过程。封装器还可以提供 API 本身提供的功能之外的附加功能，例如缓存或错误处理。


使用 API 封装器使代码更加模块化并且更易于维护。无需为每个 API 编写自定义代码，你可以使用封装器来提供与 API 交互的一致接口。它可以节省时间，避免代码重复，并减少出错的机会。


使用 API 封装器的另一个好处是它可以保护你的代码免受 API 变化的影响。如果 API 更改了它的接口，你可以更新封装器代码而无需修改你的应用程序代码。随着时间的推移，这可以减少维护应用程序所需的工作。


### 安装


该应用位于 [PyPi](https://pypi.org/project/openshift-python-wrapper/) 上，因此使用 [pip 命令](https://opensource.com/downloads/pip-cheat-sheet) 安装 `openshift-python-wrapper`：



```
$ python3 -m pip install openshift-python-wrapper

```

### Python 封装器


[OpenShift REST API](https://access.redhat.com/documentation/en-us/openshift_container_platform/3.5/html-single/using_the_openshift_rest_api/index?intcmp=7013a000002qLH8AAM) 提供对 OpenShift 平台的许多功能的编程访问。封装器提供了一个简单直观的界面，用于使用 `openshift-restclient-python` 库与 API 进行交互。它标准化了如何使用集群资源，并提供了统一的资源 CRUD（创建、读取、更新和删除）流程。它还提供额外的功能，例如需要由用户实现的特定于资源的功能。随着时间的推移，封装器使代码更易于阅读和维护。


简化用法的一个示例是与容器交互。在容器内运行命令需要使用 Kubernetes 流、处理错误等。封装器处理这一切并提供 [简单直观的功能](https://github.com/RedHatQE/openshift-python-wrapper/blob/main/ocp_resources/pod.py#L72)。



```
>>> from ocp_resources.pod import Pod
>>> from ocp_utilities.infra import get_client
>>> client = get_client()

ocp_utilities.infra INFO Trying to get
client via new_client_from_config

>>> pod = Pod(client=client, name="nginx-deployment-7fb96c846b-b48mv", namespace="default")
>>> pod.execute("ls")

ocp_resources Pod INFO Execute ls on
nginx-deployment-7fb96c846b-b48mv (ip-10-0-155-108.ec2.internal)

'bin\nboot\ndev\netc\nhome\nlib\nlib64\nmedia\nmnt\nopt\nproc\nroot\nrun\nsbin\nsrv\nsys\ntmp\nusr\nvar\n'

```

开发人员或测试人员可以使用这个封装器，我们的团队在编写代码的同时牢记测试。使用 Python 的上下文管理器可以提供开箱即用的资源创建和删除，并且可以使用继承来扩展特定场景的功能。Pytest fixtures 可以使用代码进行设置和拆卸，不留任何遗留物。甚至可以保存资源用于调试。可以轻松收集资源清单和日志。


这是上下文管理器的示例：



```
@pytest.fixture(scope="module")
def namespace():
    admin_client = get_client()
    with Namespace(client=admin_client, name="test-ns",) as ns:
        ns.wait_for_status(status=Namespace.Status.ACTIVE, timeout=240)
        yield ns

def test_ns(namespace):
    print(namespace.name)

```

生成器遍历资源，如下所示：



```
>>> from ocp_resources.node import Node
>>> from ocp_utilities.infra import get_client
>>> admin_client = get_client()
# This returns a generator
>>> for node in Node.get(dyn_client=admin_client): 
        print(node.name)

ip-10-0-128-213.ec2.internal

```

### 开源社区的开源代码


套用一句流行的说法，“如果你热爱你的代码，就应该让它自由。” `openshift-python-wrapper` 项目最初是作为 [OpenShift 虚拟化](https://www.redhat.com/en/technologies/cloud-computing/openshift/virtualization?intcmp=7013a000002qLH8AAM) 的实用模块。随着越来越多的项目从代码中受益，我们决定将这些程序提取到一个单独的仓库中并将其开源。套用另一句俗语，“如果代码不回到你这里，那就意味着它从未属于你。” 一旦这种情况发生，它就真正成为了开源。


更多的贡献者和维护者意味着代码属于社区。欢迎大家贡献。


*（题图：MJ/5ca32a4a-2194-4b36-ade9-053433e79201）*




---


via: <https://opensource.com/article/23/4/cluster-open-source-python-api-wrapper>


作者：[Ruth Netser](https://opensource.com/users/rnetser1) 选题：[lkxed](https://github.com/lkxed/) 译者：[geekpi](https://github.com/geekpi) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
Open source projects that create a wrapper around an API are becoming increasingly popular. These projects make it easier for developers to interact with APIs and use them in their applications. The `openshift-python-wrapper`

project is a wrapper around [openshift-restclient-python](https://github.com/openshift/openshift-restclient-python). What began as an internal package to help our team work with the OpenShift API became an [open source project](https://github.com/RedHatQE/openshift-python-wrapper) (Apache License 2.0).

This article discusses what an API wrapper is, why it's useful, and some examples from the wrapper.

## Why use an API wrapper?

An API wrapper is a layer of code that sits between an application and an API. It simplifies the API access process by abstracting away some of the complexities involved in making requests and parsing responses. A wrapper can also provide additional functionality beyond what the API itself offers, such as caching or error handling.

Using an API wrapper makes the code more modular and easier to maintain. Instead of writing custom code for every API, you can use a wrapper that provides a consistent interface for interacting with APIs. It saves time, avoids code duplications, and reduces the chance of errors.

Another benefit of using an API wrapper is that it can shield your code from changes to the API. If an API changes its interface, you can update the wrapper code without modifying your application code. This can reduce the work required to maintain your application over time.

## Install

The application is on [PyPi](https://pypi.org/project/openshift-python-wrapper/), so install `openshift-python-wrapper`

using the [pip command](https://opensource.com/downloads/pip-cheat-sheet):

```
````$ python3 -m pip install openshift-python-wrapper`


## Python wrapper

The [OpenShift REST API](https://access.redhat.com/documentation/en-us/openshift_container_platform/3.5/html-single/using_the_openshift_rest_api/index?intcmp=7013a000002qLH8AAM) provides programmatic access to many of the features of the OpenShift platform. The wrapper offers a simple and intuitive interface for interacting with the API using the `openshift-restclient-python`

library. It standardizes how to work with cluster resources and offers unified resource CRUD (Create, Read, Update, and Delete) flows. It also provides additional capabilities, such as resource-specific functionality that otherwise needs to be implemented by users. The wrapper makes code easier to read and maintain over time.

One example of simplified usage is interacting with a container. Running a command inside a container requires using Kubernetes stream, handling errors, and more. The wrapper handles it all and provides [simple and intuitive functionality](https://github.com/RedHatQE/openshift-python-wrapper/blob/main/ocp_resources/pod.py#L72).

```
``````
>>> from ocp_resources.pod import Pod
>>> from ocp_utilities.infra import get_client
>>> client = get_client()
ocp_utilities.infra INFO Trying to get
client via new_client_from_config
>>> pod = Pod(client=client, name="nginx-deployment-7fb96c846b-b48mv", namespace="default")
>>> pod.execute("ls")
ocp_resources Pod INFO Execute ls on
nginx-deployment-7fb96c846b-b48mv (ip-10-0-155-108.ec2.internal)
'bin\nboot\ndev\netc\nhome\nlib\nlib64\nmedia\nmnt\nopt\nproc\nroot\nrun\nsbin\nsrv\nsys\ntmp\nusr\nvar\n'
```



Developers or testers can use this wrapper—our team wrote the code while keeping testing in mind. Using Python capabilities, context managers can provide out-of-the-box resource creation and deletion, and inheritance can be used to extend functionality for specific use cases. Pytest fixtures can utilize the code for setup and teardown, leaving no leftovers. Resources can even be saved for debugging. Resource manifests and logs can be easily collected.

Here's an example of a context manager:

```
``````
@pytest.fixture(scope="module")
def namespace():
admin_client = get_client()
with Namespace(client=admin_client, name="test-ns",) as ns:
ns.wait_for_status(status=Namespace.Status.ACTIVE, timeout=240)
yield ns
def test_ns(namespace):
print(namespace.name)
```


Generators iterate over resources, as seen below:

```
``````
>>> from ocp_resources.node import Node
>>> from ocp_utilities.infra import get_client
>>> admin_client = get_client()
# This returns a generator
>>> for node in Node.get(dyn_client=admin_client):
print(node.name)
ip-10-0-128-213.ec2.internal
```


## Open source code for open source communities

To paraphrase a popular saying, "If you love your code, set it free." The `openshift-python-wrapper`

project started as utility modules for [OpenShift Virtualization](https://www.redhat.com/en/technologies/cloud-computing/openshift/virtualization?intcmp=7013a000002qLH8AAM). As more and more projects benefitted from the code, we decided to extract those utilities into a separate repository and have it open sourced. To paraphrase another common saying, "If the code does not return to you, it means it was never yours." We like saying that once that happens, it's truly open source.

More contributors and maintainers mean that the code belongs to the community. Everyone is welcome to contribute.

## Comments are closed.