跳至内容

参考资料 hub_sdk/base/crud_client.py

备注

该文件可在https://github.com/ultralytics/hub-sdk/blob/main/hub_sdk/base/crud_client.py 获取。如果您发现问题,请通过提交 Pull Request🛠️ 帮助修复。谢谢🙏!



hub_sdk.base.crud_client.CRUDClient

垒球 APIClient

代表与特定资源交互的 CRUD(创建、读取、更新、删除)客户端。

属性

名称 类型 说明
name str

与 CRUD 操作相关的名称(如 "用户")。

logger Logger

用于记录日志的日志记录器实例。

源代码 hub_sdk/base/crud_client.py
class CRUDClient(APIClient):
    """
    Represents a CRUD (Create, Read, Update, Delete) client for interacting with a specific resource.

    Attributes:
        name (str): The name associated with the CRUD operations (e.g., "User").
        logger (logging.Logger): An instance of the logger for logging purposes.
    """

    def __init__(self, base_endpoint, name, headers):
        """
        Initialize a CRUDClient instance.

        Args:
            base_endpoint (str): The base endpoint URL for the API.
            name (str): The name associated with the CRUD operations (e.g., "User").
            headers (dict): Headers to be included in API requests.
        """
        super().__init__(f"{HUB_FUNCTIONS_ROOT}/v1/{base_endpoint}", headers)
        self.name = name
        self.logger = logger

    def create(self, data: dict) -> Optional[Response]:
        """
        Create a new entity using the API.

        Args:
            data (dict): The data to be sent as part of the creation request.

        Returns:
            (Optional[Response]): Response object from the create request, or None if upload fails.
        """
        try:
            return self.post("", json=data)
        except Exception as e:
            self.logger.error(f"Failed to create {self.name}: {e}")

    def read(self, id: str) -> Optional[Response]:
        """
        Retrieve details of a specific entity.

        Args:
            id (str): The unique identifier of the entity to retrieve.

        Returns:
            (Optional[Response]): Response object from the read request, or None if read fails.
        """
        try:
            return self.get(f"/{id}")
        except Exception as e:
            self.logger.error(f"Failed to read {self.name} with ID: {id}, {e}")

    def update(self, id: str, data: dict) -> Optional[Response]:
        """
        Update an existing entity using the API.

        Args:
            id (str): The unique identifier of the entity to update.
            data (dict): The updated data to be sent in the update request.

        Returns:
            (Optional[Response]): Response object from the update request, or None if update fails.
        """
        try:
            return self.patch(f"/{id}", json=data)
        except Exception as e:
            self.logger.error(f"Failed to update {self.name} with ID: {id}, {e}")

    def delete(self, id: str, hard: bool = False) -> Optional[Response]:
        """
        Delete an entity using the API.

        Args:
            id (str): The unique identifier of the entity to delete.
            hard (bool, optional): If True, perform a hard delete. If False, perform a soft delete.

        Returns:
            (Optional[Response]): Response object from the delete request, or None if delete fails.
        """
        try:
            return super().delete(f"/{id}", {"hard": hard})
        except Exception as e:
            self.logger.error(f"Failed to delete {self.name} with ID: {id}, {e}")

    def list(self, page: int = 0, limit: int = 10) -> Optional[Response]:
        """
        List entities using the API.

        Args:
            page (int, optional): The page number to retrieve.
            limit (int, optional): The maximum number of entities per page.

        Returns:
            (Optional[Response]): Response object from the list request, or None if it fails.
        """
        try:
            params = {"page": page, "limit": limit}
            return self.get("", params=params)
        except Exception as e:
            self.logger.error(f"Failed to list {self.name}: {e}")

__init__(base_endpoint, name, headers)

初始化一个 CRUDClient 实例。

参数

名称 类型 说明 默认值
base_endpoint str

API 的基本端点 URL。

所需
name str

与 CRUD 操作相关的名称(如 "用户")。

所需
headers dict

应包含在 API 请求中的标头。

所需
源代码 hub_sdk/base/crud_client.py
def __init__(self, base_endpoint, name, headers):
    """
    Initialize a CRUDClient instance.

    Args:
        base_endpoint (str): The base endpoint URL for the API.
        name (str): The name associated with the CRUD operations (e.g., "User").
        headers (dict): Headers to be included in API requests.
    """
    super().__init__(f"{HUB_FUNCTIONS_ROOT}/v1/{base_endpoint}", headers)
    self.name = name
    self.logger = logger

create(data)

使用 API 创建一个新实体。

参数

名称 类型 说明 默认值
data dict

作为创建请求的一部分发送的数据。

所需

返回:

类型 说明
Optional[Response]

创建请求的响应对象;如果上传失败,则为 "无"。

源代码 hub_sdk/base/crud_client.py
def create(self, data: dict) -> Optional[Response]:
    """
    Create a new entity using the API.

    Args:
        data (dict): The data to be sent as part of the creation request.

    Returns:
        (Optional[Response]): Response object from the create request, or None if upload fails.
    """
    try:
        return self.post("", json=data)
    except Exception as e:
        self.logger.error(f"Failed to create {self.name}: {e}")

delete(id, hard=False)

使用 API 删除实体。

参数

名称 类型 说明 默认值
id str

要删除的实体的唯一标识符。

所需
hard bool

如果为 True,则执行硬删除。如果为 False,则执行软删除。

False

返回:

类型 说明
Optional[Response]

删除请求的响应对象;如果删除失败,则为 "无"。

源代码 hub_sdk/base/crud_client.py
def delete(self, id: str, hard: bool = False) -> Optional[Response]:
    """
    Delete an entity using the API.

    Args:
        id (str): The unique identifier of the entity to delete.
        hard (bool, optional): If True, perform a hard delete. If False, perform a soft delete.

    Returns:
        (Optional[Response]): Response object from the delete request, or None if delete fails.
    """
    try:
        return super().delete(f"/{id}", {"hard": hard})
    except Exception as e:
        self.logger.error(f"Failed to delete {self.name} with ID: {id}, {e}")

list(page=0, limit=10)

使用 API 列出实体。

参数

名称 类型 说明 默认值
page int

要检索的页码。

0
limit int

每页实体的最大数量。

10

返回:

类型 说明
Optional[Response]

列表请求的响应对象,如果失败则为 "无"。

源代码 hub_sdk/base/crud_client.py
def list(self, page: int = 0, limit: int = 10) -> Optional[Response]:
    """
    List entities using the API.

    Args:
        page (int, optional): The page number to retrieve.
        limit (int, optional): The maximum number of entities per page.

    Returns:
        (Optional[Response]): Response object from the list request, or None if it fails.
    """
    try:
        params = {"page": page, "limit": limit}
        return self.get("", params=params)
    except Exception as e:
        self.logger.error(f"Failed to list {self.name}: {e}")

read(id)

检索特定实体的详细信息。

参数

名称 类型 说明 默认值
id str

要检索的实体的唯一标识符。

所需

返回:

类型 说明
Optional[Response]

读取请求的响应对象,如果读取失败则为 "无"。

源代码 hub_sdk/base/crud_client.py
def read(self, id: str) -> Optional[Response]:
    """
    Retrieve details of a specific entity.

    Args:
        id (str): The unique identifier of the entity to retrieve.

    Returns:
        (Optional[Response]): Response object from the read request, or None if read fails.
    """
    try:
        return self.get(f"/{id}")
    except Exception as e:
        self.logger.error(f"Failed to read {self.name} with ID: {id}, {e}")

update(id, data)

使用 API 更新现有实体。

参数

名称 类型 说明 默认值
id str

要更新的实体的唯一标识符。

所需
data dict

更新请求中要发送的更新数据。

所需

返回:

类型 说明
Optional[Response]

更新请求的响应对象;如果更新失败,则为 "无"。

源代码 hub_sdk/base/crud_client.py
def update(self, id: str, data: dict) -> Optional[Response]:
    """
    Update an existing entity using the API.

    Args:
        id (str): The unique identifier of the entity to update.
        data (dict): The updated data to be sent in the update request.

    Returns:
        (Optional[Response]): Response object from the update request, or None if update fails.
    """
    try:
        return self.patch(f"/{id}", json=data)
    except Exception as e:
        self.logger.error(f"Failed to update {self.name} with ID: {id}, {e}")