跳至内容

参考资料 hub_sdk/modules/users.py

备注

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



hub_sdk.modules.users.Users

垒球 CRUDClient

一个表示通过 CRUD 操作与用户交互的客户端的类。该类扩展了 CRUDClient 类,并提供了与用户交互的特定方法。

属性

名称 类型 说明
id (str, None)

用户的唯一标识符(如果有)。

data dict

用于存储用户数据的字典。

备注

id "属性在初始化时设置,可用于唯一标识用户。 data "属性用于存储从应用程序接口获取的用户数据。

源代码 hub_sdk/modules/users.py
class Users(CRUDClient):
    """
    A class representing a client for interacting with Users through CRUD operations. This class extends the CRUDClient
    class and provides specific methods for working with Users.

    Attributes:
        id (str, None): The unique identifier of the user, if available.
        data (dict): A dictionary to store user data.

    Note:
        The 'id' attribute is set during initialization and can be used to uniquely identify a user.
        The 'data' attribute is used to store user data fetched from the API.
    """

    def __init__(self, user_id: Optional[str] = None, headers: Optional[Dict[str, Any]] = None) -> None:
        """
        Initialize a Users object for interacting with user data via CRUD operations.

        Args:
            user_id (str, optional): The unique identifier of the user.
            headers (dict, optional): A dictionary of HTTP headers to be included in API requests.
        """
        super().__init__("users", "user", headers)
        self.id = user_id
        self.data = {}
        if user_id:
            self.get_data()

    def get_data(self) -> None:
        """
        Retrieves data for the current user instance.

        If a valid user ID has been set, it sends a request to fetch the user data and stores it in the instance.
        If no user ID has been set, it logs an error message.

        Returns:
            (None): The method does not return a value.
        """
        if not self.id:
            self.logger.error("No user id has been set. Update the user id or create a user.")
            return

        try:
            response = super().read(self.id)

            if response is None:
                self.logger.error(f"Received no response from the server for user ID: {self.id}")
                return

            # Check if the response has a .json() method (it should if it's a response object)
            if not hasattr(response, "json"):
                self.logger.error(f"Invalid response object received for user ID: {self.id}")
                return

            resp_data = response.json()
            if resp_data is None:
                self.logger.error(f"No data received in the response for user ID: {self.id}")
                return

            data = resp_data.get("data", {})
            self.data = self._reconstruct_data(data)
            self.logger.debug(f"User data retrieved for ID: {self.id}")

        except Exception as e:
            self.logger.error(f"An error occurred while retrieving data for user ID: {self.id}, {str(e)}")

    def create_user(self, user_data: dict) -> None:
        """
        Creates a new user with the provided data and sets the user ID for the current instance.

        Args:
            user_data (dict): A dictionary containing the data for creating the user.

        Returns:
            (None): The method does not return a value.
        """
        resp = super().create(user_data).json()
        self.id = resp.get("data", {}).get("id")
        self.get_data()

    def delete(self, hard: bool = False) -> Optional[Response]:
        """
        Delete the user resource represented by this instance.

        Args:
            hard (bool, optional): If True, perform a hard delete.

        Note:
            The 'hard' parameter determines whether to perform a soft delete (default) or a hard delete.
            In a soft delete, the model might be marked as deleted but retained in the system.
            In a hard delete, the model is permanently removed from the system.

        Returns:
            (Optional[Response]): Response object from the delete request, or None if delete fails
        """
        return super().delete(self.id, hard)

    def update(self, data: dict) -> Optional[Response]:
        """
        Update the user resource represented by this instance.

        Args:
            data (dict): The updated data for the user resource.

        Returns:
            (Optional[Response]): Response object from the update request, or None if update fails
        """
        return super().update(self.id, data)

__init__(user_id=None, headers=None)

初始化用户对象,以便通过 CRUD 操作与用户数据交互。

参数

名称 类型 说明 默认值
user_id str

用户的唯一标识符。

None
headers dict

将包含在 API 请求中的 HTTP 标头字典。

None
源代码 hub_sdk/modules/users.py
def __init__(self, user_id: Optional[str] = None, headers: Optional[Dict[str, Any]] = None) -> None:
    """
    Initialize a Users object for interacting with user data via CRUD operations.

    Args:
        user_id (str, optional): The unique identifier of the user.
        headers (dict, optional): A dictionary of HTTP headers to be included in API requests.
    """
    super().__init__("users", "user", headers)
    self.id = user_id
    self.data = {}
    if user_id:
        self.get_data()

create_user(user_data)

使用提供的数据创建新用户,并为当前实例设置用户 ID。

参数

名称 类型 说明 默认值
user_data dict

包含创建用户数据的字典。

所需

返回:

类型 说明
None

该方法不返回值。

源代码 hub_sdk/modules/users.py
def create_user(self, user_data: dict) -> None:
    """
    Creates a new user with the provided data and sets the user ID for the current instance.

    Args:
        user_data (dict): A dictionary containing the data for creating the user.

    Returns:
        (None): The method does not return a value.
    """
    resp = super().create(user_data).json()
    self.id = resp.get("data", {}).get("id")
    self.get_data()

delete(hard=False)

删除该实例所代表的用户资源。

参数

名称 类型 说明 默认值
hard bool

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

False
备注

硬 "参数决定执行软删除(默认)还是硬删除。 在软删除中,模型可能被标记为已删除,但仍保留在系统中。 在硬删除中,模型将从系统中永久删除。

返回:

类型 说明
Optional[Response]

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

源代码 hub_sdk/modules/users.py
def delete(self, hard: bool = False) -> Optional[Response]:
    """
    Delete the user resource represented by this instance.

    Args:
        hard (bool, optional): If True, perform a hard delete.

    Note:
        The 'hard' parameter determines whether to perform a soft delete (default) or a hard delete.
        In a soft delete, the model might be marked as deleted but retained in the system.
        In a hard delete, the model is permanently removed from the system.

    Returns:
        (Optional[Response]): Response object from the delete request, or None if delete fails
    """
    return super().delete(self.id, hard)

get_data()

读取当前用户实例的数据。

如果设置了有效的用户 ID,它就会发送请求获取用户数据并将其存储到实例中。 如果没有设置用户 ID,则会记录一条错误信息。

返回:

类型 说明
None

该方法不返回值。

源代码 hub_sdk/modules/users.py
def get_data(self) -> None:
    """
    Retrieves data for the current user instance.

    If a valid user ID has been set, it sends a request to fetch the user data and stores it in the instance.
    If no user ID has been set, it logs an error message.

    Returns:
        (None): The method does not return a value.
    """
    if not self.id:
        self.logger.error("No user id has been set. Update the user id or create a user.")
        return

    try:
        response = super().read(self.id)

        if response is None:
            self.logger.error(f"Received no response from the server for user ID: {self.id}")
            return

        # Check if the response has a .json() method (it should if it's a response object)
        if not hasattr(response, "json"):
            self.logger.error(f"Invalid response object received for user ID: {self.id}")
            return

        resp_data = response.json()
        if resp_data is None:
            self.logger.error(f"No data received in the response for user ID: {self.id}")
            return

        data = resp_data.get("data", {})
        self.data = self._reconstruct_data(data)
        self.logger.debug(f"User data retrieved for ID: {self.id}")

    except Exception as e:
        self.logger.error(f"An error occurred while retrieving data for user ID: {self.id}, {str(e)}")

update(data)

更新该实例所代表的用户资源。

参数

名称 类型 说明 默认值
data dict

用户资源的更新数据。

所需

返回:

类型 说明
Optional[Response]

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

源代码 hub_sdk/modules/users.py
def update(self, data: dict) -> Optional[Response]:
    """
    Update the user resource represented by this instance.

    Args:
        data (dict): The updated data for the user resource.

    Returns:
        (Optional[Response]): Response object from the update request, or None if update fails
    """
    return super().update(self.id, data)