Saltar al contenido

Referencia para hub_sdk/modules/users.py

Nota

Este archivo est谩 disponible en https://github.com/ultralytics/hub-sdk/blob/main/hub_sdk/modules/users .py. Si detectas alg煤n problema, por favor, ayuda a solucionarlo contribuyendo con una Pull Request 馃洜锔. 隆Gracias 馃檹!



hub_sdk.modules.users.Users

Bases: CRUDClient

Una clase que representa a un cliente para interactuar con Usuarios mediante operaciones CRUD. Esta clase extiende la clase CRUDClient y proporciona m茅todos espec铆ficos para trabajar con Usuarios.

Atributos:

Nombre Tipo Descripci贸n
id (str, None)

El identificador 煤nico del usuario, si est谩 disponible.

data dict

Un diccionario para almacenar los datos del usuario.

Nota

El atributo "id" se establece durante la inicializaci贸n y puede utilizarse para identificar de forma 煤nica a un usuario. El atributo "data" se utiliza para almacenar los datos del usuario obtenidos de la API.

C贸digo fuente en 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)

Inicializa un objeto Usuarios para interactuar con los datos de los usuarios mediante operaciones CRUD.

Par谩metros:

Nombre Tipo Descripci贸n Por defecto
user_id str

El identificador 煤nico del usuario.

None
headers dict

Un diccionario de cabeceras HTTP que deben incluirse en las peticiones de la API.

None
C贸digo fuente en 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)

Crea un nuevo usuario con los datos proporcionados y establece el ID de usuario para la instancia actual.

Par谩metros:

Nombre Tipo Descripci贸n Por defecto
user_data dict

Un diccionario que contiene los datos para crear el usuario.

necesario

Devuelve:

Tipo Descripci贸n
None

El m茅todo no devuelve ning煤n valor.

C贸digo fuente en 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)

Elimina el recurso de usuario representado por esta instancia.

Par谩metros:

Nombre Tipo Descripci贸n Por defecto
hard bool

Si es Verdadero, realiza un borrado fuerte.

False
Nota

El par谩metro "duro" determina si se realiza un borrado suave (por defecto) o un borrado duro. En un borrado suave, el modelo puede marcarse como borrado pero conservarse en el sistema. En un borrado duro, el modelo se elimina permanentemente del sistema.

Devuelve:

Tipo Descripci贸n
Optional[Response]

Objeto de respuesta de la petici贸n de borrado, o Ninguno si el borrado falla

C贸digo fuente en 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()

Recupera los datos de la instancia de usuario actual.

Si se ha establecido un ID de usuario v谩lido, env铆a una petici贸n para obtener los datos del usuario y los almacena en la instancia. Si no se ha establecido ning煤n ID de usuario, registra un mensaje de error.

Devuelve:

Tipo Descripci贸n
None

El m茅todo no devuelve ning煤n valor.

C贸digo fuente en 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)

Actualiza el recurso de usuario representado por esta instancia.

Par谩metros:

Nombre Tipo Descripci贸n Por defecto
data dict

Los datos actualizados del recurso de usuario.

necesario

Devuelve:

Tipo Descripci贸n
Optional[Response]

Objeto de respuesta de la solicitud de actualizaci贸n, o Ninguno si la actualizaci贸n falla

C贸digo fuente en 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)