Skip to content

Units

albert.collections.units

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

OrderBy

Bases: str, Enum

DESCENDING

DESCENDING = 'desc'

ASCENDING

ASCENDING = 'asc'

Unit

Bases: BaseResource

Unit is a Pydantic model representing a unit entity.

Attributes:

Name Type Description
id str | None

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

name str

The name of the unit.

symbol str | None

The symbol of the unit.

synonyms List[str] | None

The list of synonyms for the unit.

category UnitCategory

The category of the unit.

verified bool | None

Whether the unit is verified.

status Status | None

The status of the unit. Allowed values are active, and inactive

id

id: str | None = Field(None, alias='albertId')

name

name: str

symbol

symbol: str | None = Field(None)

synonyms

synonyms: list[str] | None = Field(
    default_factory=list, alias="Synonyms"
)

category

category: UnitCategory | None = Field(None)

verified

verified: bool | None = Field(
    default=False, exclude=True, frozen=True
)

UnitCategory

Bases: str, Enum

UnitCategory is an enumeration of possible unit categories.

Attributes:

Name Type Description
LENGTH str

Represents length units.

VOLUME str

Represents volume units.

LIQUID_VOLUME str

Represents liquid volume units.

ANGLES str

Represents angle units.

TIME str

Represents time units.

FREQUENCY str

Represents frequency units.

MASS str

Represents mass units.

CURRENT str

Represents electric current units.

TEMPERATURE str

Represents temperature units.

AMOUNT str

Represents amount of substance units.

LUMINOSITY str

Represents luminous intensity units.

FORCE str

Represents force units.

ENERGY str

Represents energy units.

POWER str

Represents power units.

PRESSURE str

Represents pressure units.

ELECTRICITY_AND_MAGNETISM str

Represents electricity and magnetism units.

OTHER str

Represents other units.

WEIGHT str

Represents weight units.

LENGTH

LENGTH = 'Length'

VOLUME

VOLUME = 'Volume'

LIQUID_VOLUME

LIQUID_VOLUME = 'Liquid volume'

ANGLES

ANGLES = 'Angles'

TIME

TIME = 'Time'

FREQUENCY

FREQUENCY = 'Frequency'

MASS

MASS = 'Mass'

CURRENT

CURRENT = 'Electric current'

TEMPERATURE

TEMPERATURE = 'Temperature'

AMOUNT

AMOUNT = 'Amount of substance'

LUMINOSITY

LUMINOSITY = 'Luminous intensity'

FORCE

FORCE = 'Force'

ENERGY

ENERGY = 'Energy'

POWER

POWER = 'Power'

PRESSURE

PRESSURE = 'Pressure'

ELECTRICITY_AND_MAGNETISM

ELECTRICITY_AND_MAGNETISM = 'Electricity and magnetism'

OTHER

OTHER = 'Other'

WEIGHT

WEIGHT = 'Weight'

AREA

AREA = 'Area'

SURFACE_AREA

SURFACE_AREA = 'Surface Area'

BINARY

BINARY = 'Binary'

CAPACITANCE

CAPACITANCE = 'Capacitance'

SPEED

SPEED = 'Speed'

ELECTRICAL_CONDUCTIVITY

ELECTRICAL_CONDUCTIVITY = 'Electrical conductivity'

ELECTRICAL_PERMITTIVITY

ELECTRICAL_PERMITTIVITY = 'Electrical permitivitty'

DENSITY

DENSITY = 'Density'

RESISTANCE

RESISTANCE = 'Resistance'

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

UnitCollection

UnitCollection(*, session: AlbertSession)

Bases: BaseCollection

UnitCollection is a collection class for managing Unit entities in the Albert platform.

Parameters:

Name Type Description Default
session AlbertSession

The Albert session instance.

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

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

base_path

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

create

create(*, unit: Unit) -> Unit

Creates a new unit entity.

Parameters:

Name Type Description Default
unit Unit

The unit object to create.

required

Returns:

Type Description
Unit

The created Unit object.

Source code in src/albert/collections/units.py
def create(self, *, unit: Unit) -> Unit:
    """
    Creates a new unit entity.

    Parameters
    ----------
    unit : Unit
        The unit object to create.

    Returns
    -------
    Unit
        The created Unit object.
    """
    hit = self.get_by_name(name=unit.name, exact_match=True)
    if hit is not None:
        logging.warning(
            f"Unit with the name {hit.name} already exists. Returning the existing unit."
        )
        return hit
    response = self.session.post(
        self.base_path, json=unit.model_dump(by_alias=True, exclude_unset=True, mode="json")
    )
    this_unit = Unit(**response.json())
    return this_unit

get_by_id

get_by_id(*, id: str) -> Unit

Retrieves a unit by its ID.

Parameters:

Name Type Description Default
id str

The ID of the unit to retrieve.

required

Returns:

Type Description
Unit

The Unit object if found.

Source code in src/albert/collections/units.py
def get_by_id(self, *, id: str) -> Unit:
    """
    Retrieves a unit by its ID.

    Parameters
    ----------
    id : str
        The ID of the unit to retrieve.

    Returns
    -------
    Unit
        The Unit object if found.
    """
    url = f"{self.base_path}/{id}"
    response = self.session.get(url)
    this_unit = Unit(**response.json())
    return this_unit

get_by_ids

get_by_ids(*, ids: list[str]) -> list[Unit]

Retrieves a set of units by their IDs

Parameters:

Name Type Description Default
ids list[str]

The IDs of the units to retrieve.

required

Returns:

Type Description
list[Unit]

The Unit objects

Source code in src/albert/collections/units.py
def get_by_ids(self, *, ids: list[str]) -> list[Unit]:
    """
    Retrieves a set of units by their IDs

    Parameters
    ----------
    ids : list[str]
        The IDs of the units to retrieve.

    Returns
    -------
    list[Unit]
        The Unit objects
    """
    url = f"{self.base_path}/ids"
    batches = [ids[i : i + 500] for i in range(0, len(ids), 500)]
    return [
        Unit(**item)
        for batch in batches
        for item in self.session.get(url, params={"id": batch}).json()["Items"]
    ]

update

update(*, unit: Unit) -> Unit

Updates a unit entity by its ID.

Parameters:

Name Type Description Default
unit Unit

The updated Unit object.

required

Returns:

Type Description
Unit

The updated Unit

Source code in src/albert/collections/units.py
def update(self, *, unit: Unit) -> Unit:
    """
    Updates a unit entity by its ID.

    Parameters
    ----------
    unit : Unit
        The updated Unit object.

    Returns
    -------
    Unit
        The updated Unit
    """
    unit_id = unit.id
    original_unit = self.get_by_id(id=unit_id)
    payload = self._generate_patch_payload(existing=original_unit, updated=unit)
    url = f"{self.base_path}/{unit_id}"
    self.session.patch(url, json=payload.model_dump(mode="json", by_alias=True))
    unit = self.get_by_id(id=unit_id)
    return unit

delete

delete(*, id: str) -> None

Deletes a unit by its ID.

Parameters:

Name Type Description Default
id str

The ID of the unit to delete.

required

Returns:

Type Description
None
Source code in src/albert/collections/units.py
def delete(self, *, id: str) -> None:
    """
    Deletes a unit by its ID.

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

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

list

list(
    *,
    limit: int = 100,
    name: str | list[str] | None = None,
    category: UnitCategory | None = None,
    order_by: OrderBy = DESCENDING,
    exact_match: bool = False,
    start_key: str | None = None,
    verified: bool | None = None,
) -> Iterator[Unit]

Lists unit entities with optional filters.

Parameters:

Name Type Description Default
limit int

The maximum number of units to return, by default 50.

100
name Optional[str]

The name of the unit to filter by, by default None.

None
category Optional[UnitCategory]

The category of the unit to filter by, by default None.

None
order_by OrderBy

The order by which to sort the results, by default OrderBy.DESCENDING.

DESCENDING
exact_match bool

Whether to match the name exactly, by default False.

False
start_key Optional[str]

The starting point for the next set of results, by default None.

None

Returns:

Type Description
Iterator[Unit]

An iterator of Unit objects.

Source code in src/albert/collections/units.py
def list(
    self,
    *,
    limit: int = 100,
    name: str | list[str] | None = None,
    category: UnitCategory | None = None,
    order_by: OrderBy = OrderBy.DESCENDING,
    exact_match: bool = False,
    start_key: str | None = None,
    verified: bool | None = None,
) -> Iterator[Unit]:
    """
    Lists unit entities with optional filters.

    Parameters
    ----------
    limit : int, optional
        The maximum number of units to return, by default 50.
    name : Optional[str], optional
        The name of the unit to filter by, by default None.
    category : Optional[UnitCategory], optional
        The category of the unit to filter by, by default None.
    order_by : OrderBy, optional
        The order by which to sort the results, by default OrderBy.DESCENDING.
    exact_match : bool, optional
        Whether to match the name exactly, by default False.
    start_key : Optional[str], optional
        The starting point for the next set of results, by default None.

    Returns
    -------
    Iterator[Unit]
        An iterator of Unit objects.
    """
    params = {
        "limit": limit,
        "startKey": start_key,
        "orderBy": order_by.value,
        "name": [name] if isinstance(name, str) else name,
        "exactMatch": json.dumps(exact_match),
        "verified": json.dumps(verified) if verified is not None else None,
        "category": category.value if isinstance(category, UnitCategory) else category,
    }
    return AlbertPaginator(
        mode=PaginationMode.KEY,
        path=self.base_path,
        session=self.session,
        params=params,
        deserialize=lambda items: [Unit(**item) for item in items],
    )

get_by_name

get_by_name(
    *, name: str, exact_match: bool = False
) -> Unit | None

Retrieves a unit by its name.

Parameters:

Name Type Description Default
name str

The name of the unit to retrieve.

required
exact_match bool

Whether to match the name exactly, by default False.

False

Returns:

Type Description
Optional[Unit]

The Unit object if found, None otherwise.

Source code in src/albert/collections/units.py
def get_by_name(self, *, name: str, exact_match: bool = False) -> Unit | None:
    """
    Retrieves a unit by its name.

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

    Returns
    -------
    Optional[Unit]
        The Unit object if found, None otherwise.
    """
    found = self.list(name=name, exact_match=exact_match)
    return next(found, None)

unit_exists

unit_exists(*, name: str, exact_match: bool = True) -> bool

Checks if a unit exists by its name.

Parameters:

Name Type Description Default
name str

The name of the unit to check.

required
exact_match bool

Whether to match the name exactly, by default True.

True

Returns:

Type Description
bool

True if the unit exists, False otherwise.

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

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

    Returns
    -------
    bool
        True if the unit exists, False otherwise.
    """
    return self.get_by_name(name=name, exact_match=exact_match) is not None