Skip to content

Custom Templates

albert.collections.custom_templates

BaseCollection

BaseCollection(*, session: AlbertSession)

BaseCollection is the base class for all collection classes.

Parameters:

Name Type Description Default
session AlbertSession

The Albert API Session instance.

required
Source code in src/albert/collections/base.py
def __init__(self, *, session: AlbertSession):
    self.session = session

session

session = session

AlbertHTTPError

AlbertHTTPError(response: Response)

Bases: AlbertException

Base class for all erors due to HTTP responses.

Source code in src/albert/exceptions.py
def __init__(self, response: requests.Response):
    message = self._format_message(response)
    super().__init__(message)
    self.response = response

response

response = response

CustomTemplate

Bases: BaseTaggedResource

A custom template entity.

Attributes:

Name Type Description
name str

The name of the template.

id str

The Albert ID of the template. Set when the template is retrieved from Albert.

category TemplateCategory

The category of the template. Allowed values are Property Task, Property, Batch, Sheet, Notebook, and General.

metadata Dict[str, str | List[EntityLink] | EntityLink] | None

The metadata of the template. Allowed Metadata fields can be found using Custim Fields.

data CustomTemplateData | None

The data of the template.

team List[TeamACL] | None

The team of the template.

acl TemplateACL | None

name

name: str

id

id: str = Field(alias='albertId')

category

category: TemplateCategory = Field(default=GENERAL)

metadata

metadata: dict[str, MetadataItem] | None = Field(
    default=None, alias="Metadata"
)

data

data: CustomTemplateData | None = Field(
    default=None, alias="Data"
)

team

team: list[TeamACL] | None = Field(default_factory=list)

acl

acl: TemplateACL | None = Field(
    default_factory=list, alias="ACL"
)

add_missing_category

add_missing_category(
    data: dict[str, Any],
) -> dict[str, Any]

Initialize private attributes from the incoming data dictionary before the model is fully constructed.

Source code in src/albert/resources/custom_templates.py
@model_validator(mode="before")  # Must happen before construction so the data are captured
@classmethod
def add_missing_category(cls, data: dict[str, Any]) -> dict[str, Any]:
    """
    Initialize private attributes from the incoming data dictionary before the model is fully constructed.
    """

    if "Data" in data and "category" in data and "category" not in data["Data"]:
        data["Data"]["category"] = data["category"]
    return data

AlbertSession

AlbertSession(
    *,
    base_url: str,
    token: str | None = None,
    client_credentials: ClientCredentials | None = None,
    retries: int | None = None,
)

Bases: Session

A session that has a base URL, which is prefixed to all request URLs.

Parameters:

Name Type Description Default
base_url str

The base URL to prefix to all requests. (e.g., "https://sandbox.albertinvent.com")

required
retries int

The number of retries for failed requests. Defaults to 3.

None
client_credentials ClientCredentials | None

The client credentials for programmatic authentication. Optional if token is provided.

None
token str | None

The JWT token for authentication. Optional if client credentials are provided.

None
Source code in src/albert/session.py
def __init__(
    self,
    *,
    base_url: str,
    token: str | None = None,
    client_credentials: ClientCredentials | None = None,
    retries: int | None = None,
):
    super().__init__()
    self.base_url = base_url
    self.headers.update(
        {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": f"albert-SDK V.{albert.__version__}",
        }
    )

    if token is None and client_credentials is None:
        raise ValueError("Either client credentials or token must be specified.")

    self._provided_token = token
    self._token_manager = (
        TokenManager(base_url, client_credentials) if client_credentials is not None else None
    )

    # Set up retry logic
    retries = retries if retries is not None else 3
    retry = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=0.3,
        status_forcelist=(500, 502, 503, 504, 403),
        raise_on_status=False,
    )
    adapter = HTTPAdapter(max_retries=retry)
    self.mount("http://", adapter)
    self.mount("https://", adapter)

base_url

base_url = base_url

request

request(
    method: str, path: str, *args, **kwargs
) -> Response
Source code in src/albert/session.py
def request(self, method: str, path: str, *args, **kwargs) -> requests.Response:
    self.headers["Authorization"] = f"Bearer {self._access_token}"
    full_url = urljoin(self.base_url, path) if not path.startswith("http") else path
    with handle_http_errors():
        response = super().request(method, full_url, *args, **kwargs)
        response.raise_for_status()
        return response

CustomTemplatesCollection

CustomTemplatesCollection(*, session: AlbertSession)

Bases: BaseCollection

CustomTemplatesCollection is a collection class for managing CustomTemplate entities in the Albert platform.

Parameters:

Name Type Description Default
session AlbertSession

The Albert session instance.

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

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

base_path

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

get_by_id

get_by_id(*, id) -> CustomTemplate

Get a Custom Template by ID

Parameters:

Name Type Description Default
id str

id of the custom template

required

Returns:

Type Description
CustomTemplate

The CutomTemplate with the provided ID (or None if not found)

Source code in src/albert/collections/custom_templates.py
def get_by_id(self, *, id) -> CustomTemplate:
    """Get a Custom Template by ID

    Parameters
    ----------
    id : str
        id of the custom template

    Returns
    -------
    CustomTemplate
        The CutomTemplate with the provided ID (or None if not found)
    """
    url = f"{self.base_path}/{id}"
    response = self.session.get(url)
    return CustomTemplate(**response.json())

list

list(
    *,
    text: str | None = None,
    limit: int = 50,
    offset: int = 0,
) -> Iterator[CustomTemplate]

Searches for custom templates matching the provided criteria.

Parameters:

Name Type Description Default
text str | None

The text to search for, by default None

None

Yields:

Type Description
Iterator[CustomTemplate]

An iterator of CustomTemplate items matching the search criteria.

Source code in src/albert/collections/custom_templates.py
def list(
    self,
    *,
    text: str | None = None,
    limit: int = 50,
    offset: int = 0,
) -> Iterator[CustomTemplate]:
    """Searches for custom templates matching the provided criteria.

    Parameters
    ----------
    text : str | None, optional
        The text to search for, by default None


    Yields
    ------
    Iterator[CustomTemplate]
        An iterator of CustomTemplate items matching the search criteria.
    """

    def deserialize(items: list[dict]) -> Iterator[CustomTemplate]:
        for item in items:
            id = item["albertId"]
            try:
                yield self.get_by_id(id=id)
            except AlbertHTTPError as e:
                logger.warning(f"Error fetching custom template {id}: {e}")

    params = {"limit": limit, "offset": offset, "text": text}

    return AlbertPaginator(
        mode=PaginationMode.OFFSET,
        path=f"{self.base_path}/search",
        session=self.session,
        params=params,
        deserialize=deserialize,
    )