Skip to content

Tags

albert.collections.tags.TagCollection

TagCollection(*, session: AlbertSession)

Bases: BaseCollection

TagCollection is a collection class for managing Tag entities in the Albert platform.

Parameters:

Name Type Description Default
session AlbertSession

The Albert session instance.

required

Attributes:

Name Type Description
base_path str

The base URL for tag API requests.

Methods:

Name Description
get_all

Lists tag entities with optional filters.

exists

Checks if a tag exists by its name.

create

Creates a new tag entity.

get_by_id

Retrieves a tag by its ID.

get_by_ids

Retrieve a list of tags by their IDs.

get_by_name

Retrieves a tag by its name.

delete

Deletes a tag by its ID.

rename

Renames an existing tag entity.

Parameters:

Name Type Description Default
session AlbertSession

The Albert session instance.

required
Source code in src/albert/collections/tags.py
def __init__(self, *, session: AlbertSession):
    """
    Initializes the TagCollection with the provided session.

    Parameters
    ----------
    session : AlbertSession
        The Albert session instance.
    """
    super().__init__(session=session)
    self.base_path = f"/api/{TagCollection._api_version}/tags"

base_path

base_path = f'/api/{_api_version}/tags'

exists

exists(*, tag: str, exact_match: bool = True) -> bool

Checks if a tag exists by its name.

Parameters:

Name Type Description Default
tag str

The name of the tag to check.

required
exact_match bool

Whether to match the name exactly, by default True.

True

Returns:

Type Description
bool

True if the tag exists, False otherwise.

Source code in src/albert/collections/tags.py
def exists(self, *, tag: str, exact_match: bool = True) -> bool:
    """
    Checks if a tag exists by its name.

    Parameters
    ----------
    tag : str
        The name of the tag to check.
    exact_match : bool, optional
        Whether to match the name exactly, by default True.

    Returns
    -------
    bool
        True if the tag exists, False otherwise.
    """

    return self.get_by_name(name=tag, exact_match=exact_match) is not None

create

create(*, tag: str | Tag) -> Tag

Creates a new tag entity.

Parameters:

Name Type Description Default
tag Union[str, Tag]

The tag name or Tag entity to create.

required

Returns:

Type Description
Tag

The created Tag entity.

Source code in src/albert/collections/tags.py
def create(self, *, tag: str | Tag) -> Tag:
    """
    Creates a new tag entity.

    Parameters
    ----------
    tag : Union[str, Tag]
        The tag name or Tag entity to create.

    Returns
    -------
    Tag
        The created Tag entity.
    """
    if isinstance(tag, str):
        tag = Tag(tag=tag)

    payload = {"name": tag.tag}
    response = self.session.post(self.base_path, json=payload)
    tag = Tag(**response.json())
    return tag

get_or_create

get_or_create(*, tag: str | Tag) -> Tag

Retrieves a Tag by its name or creates it if it does not exist.

Parameters:

Name Type Description Default
tag Union[str, Tag]

The tag name or Tag entity to retrieve or create.

required

Returns:

Type Description
Tag

The existing or newly created Tag entity.

Source code in src/albert/collections/tags.py
def get_or_create(self, *, tag: str | Tag) -> Tag:
    """
    Retrieves a Tag by its name or creates it if it does not exist.

    Parameters
    ----------
    tag : Union[str, Tag]
        The tag name or Tag entity to retrieve or create.

    Returns
    -------
    Tag
        The existing or newly created Tag entity.
    """
    if isinstance(tag, str):
        tag = Tag(tag=tag)
    found = self.get_by_name(name=tag.tag, exact_match=True)
    if found:
        logging.warning(f"Tag {found.tag} already exists with id {found.id}")
        return found
    return self.create(tag=tag)

get_by_id

get_by_id(*, id: TagId) -> Tag

Get a tag by its ID.

Parameters:

Name Type Description Default
id str

The ID of the tag to get.

required

Returns:

Type Description
Tag

The Tag entity.

Source code in src/albert/collections/tags.py
@validate_call
def get_by_id(self, *, id: TagId) -> Tag:
    """
    Get a tag by its ID.

    Parameters
    ----------
    id : str
        The ID of the tag to get.

    Returns
    -------
    Tag
        The Tag entity.
    """
    url = f"{self.base_path}/{id}"
    response = self.session.get(url)
    return Tag(**response.json())

get_by_ids

get_by_ids(*, ids: list[TagId]) -> list[Tag]
Source code in src/albert/collections/tags.py
@validate_call
def get_by_ids(self, *, ids: list[TagId]) -> list[Tag]:
    url = f"{self.base_path}/ids"
    batches = [ids[i : i + 100] for i in range(0, len(ids), 100)]
    return [
        Tag(**item)
        for batch in batches
        for item in self.session.get(url, params={"id": batch}).json()
    ]

get_by_name

get_by_name(
    *, name: str, exact_match: bool = True
) -> Tag | None

Retrieves a tag by its name or None if not found.

Parameters:

Name Type Description Default
name str

The name of the tag to retrieve.

required
exact_match bool

Whether to match the name exactly, by default True.

True

Returns:

Type Description
Tag

The Tag entity if found, None otherwise.

Source code in src/albert/collections/tags.py
def get_by_name(self, *, name: str, exact_match: bool = True) -> Tag | None:
    """
    Retrieves a tag by its name or None if not found.

    Parameters
    ----------
    name : str
        The name of the tag to retrieve.
    exact_match : bool, optional
        Whether to match the name exactly, by default True.

    Returns
    -------
    Tag
        The Tag entity if found, None otherwise.
    """
    found = self.get_all(name=name, exact_match=exact_match, max_items=1)
    return next(found, None)

delete

delete(*, id: TagId) -> None

Deletes a tag by its ID.

Parameters:

Name Type Description Default
id str

The ID of the tag to delete.

required

Returns:

Type Description
None
Source code in src/albert/collections/tags.py
@validate_call
def delete(self, *, id: TagId) -> None:
    """
    Deletes a tag by its ID.

    Parameters
    ----------
    id : str
        The ID of the tag to delete.

    Returns
    -------
    None
    """
    url = f"{self.base_path}/{id}"
    self.session.delete(url)

rename

rename(*, old_name: str, new_name: str) -> Tag

Renames an existing tag entity.

Parameters:

Name Type Description Default
old_name str

The current name of the tag.

required
new_name str

The new name of the tag.

required

Returns:

Type Description
Tag

The renamed Tag.

Source code in src/albert/collections/tags.py
def rename(self, *, old_name: str, new_name: str) -> Tag:
    """
    Renames an existing tag entity.

    Parameters
    ----------
    old_name : str
        The current name of the tag.
    new_name : str
        The new name of the tag.

    Returns
    -------
    Tag
        The renamed Tag.
    """
    found_tag = self.get_by_name(name=old_name, exact_match=True)
    if not found_tag:
        msg = f'Tag "{old_name}" not found.'
        logger.error(msg)
        raise AlbertException(msg)
    tag_id = found_tag.id
    payload = [
        {
            "data": [
                {
                    "operation": "update",
                    "attribute": "name",
                    "oldValue": old_name,
                    "newValue": new_name,
                }
            ],
            "id": tag_id,
        }
    ]
    self.session.patch(self.base_path, json=payload)
    return self.get_by_id(id=tag_id)

get_all

get_all(
    *,
    order_by: OrderBy = DESCENDING,
    name: str | list[str] | None = None,
    exact_match: bool = True,
    start_key: str | None = None,
    max_items: int | None = None,
) -> Iterator[Tag]

Get all Tag entities with optional filters.

Parameters:

Name Type Description Default
order_by OrderBy

The order by which to sort the results. Default is DESCENDING.

DESCENDING
name str or list[str]

Filter tags by one or more names.

None
exact_match bool

Whether to match the name(s) exactly. Default is True.

True
start_key str

The pagination key to start from.

None
max_items int

Maximum number of items to return in total. If None, fetches all available items.

None

Returns:

Type Description
Iterator[Tag]

An iterator of Tag entities matching the filters.

Source code in src/albert/collections/tags.py
def get_all(
    self,
    *,
    order_by: OrderBy = OrderBy.DESCENDING,
    name: str | list[str] | None = None,
    exact_match: bool = True,
    start_key: str | None = None,
    max_items: int | None = None,
) -> Iterator[Tag]:
    """
    Get all Tag entities with optional filters.

    Parameters
    ----------
    order_by : OrderBy, optional
        The order by which to sort the results. Default is DESCENDING.
    name : str or list[str], optional
        Filter tags by one or more names.
    exact_match : bool, optional
        Whether to match the name(s) exactly. Default is True.
    start_key : str, optional
        The pagination key to start from.
    max_items : int, optional
        Maximum number of items to return in total. If None, fetches all available items.

    Returns
    -------
    Iterator[Tag]
        An iterator of Tag entities matching the filters.
    """
    params = {
        "orderBy": order_by.value,
        "startKey": start_key,
    }

    if name:
        params["name"] = [name] if isinstance(name, str) else name
        params["exactMatch"] = exact_match

    return AlbertPaginator(
        mode=PaginationMode.KEY,
        path=self.base_path,
        session=self.session,
        params=params,
        max_items=max_items,
        deserialize=lambda items: [Tag(**item) for item in items],
    )