twilight_utils.more_str.generators

Module containing different implementation of string generators.

 1"""Module containing different implementation of string generators."""
 2
 3__all__ = [
 4    "random_string",
 5    "uuid_to_base64",
 6]
 7
 8import base64
 9import uuid
10from collections.abc import Callable
11from typing import Literal
12
13
14def uuid_to_base64(
15    uuid_type: Literal["uuid1", "uuid3", "uuid4", "uuid5"] = "uuid4", namespace: str | None = None
16) -> str:
17    """
18    Convert a string to a base64 encoded string.
19
20    Args:
21        uuid_type (str): The type of UUID to generate. Must be one of "uuid1", "uuid3", "uuid4", or "uuid5".
22        namespace (str): The namespace to use for the UUID. Only used for "uuid3" and "uuid5" UUID types.
23
24    Returns:
25        str: The base64 encoded string.
26
27    Raises:
28        ValueError: If the UUID type is invalid;
29        ValueError: If the namespace is not provided for "uuid3" and "uuid5" UUID types
30    """
31    match uuid_type:
32        case "uuid1" | "uuid4":
33            input_bytes = getattr(uuid, uuid_type)().hex.encode("utf-8")
34        case "uuid3" | "uuid5":
35            if namespace is None:
36                msg = "Namespace must be provided for 'uuid3' and 'uuid5' UUID types."
37                raise ValueError(msg)
38            input_bytes = getattr(uuid, uuid_type)(uuid.NAMESPACE_DNS, namespace).hex.encode("utf-8")
39        case _:
40            msg = f"Invalid UUID type: {uuid_type!r}"
41            raise ValueError(msg)
42    base64_bytes = base64.b64encode(input_bytes)
43    return base64_bytes.decode("utf-8")
44
45
46def random_string(
47    prefix: str = "",
48    suffix: str = "",
49    randomizer: Callable[[], str] = uuid_to_base64,
50    max_length: int = 200,
51) -> str:
52    """
53    Generate a random string.
54
55    Args:
56        prefix (str | None): Optional prefix to add to the string.
57        suffix (str | None): Optional suffix to add to the string.
58        randomizer (Callable[[], str]): Optional function that will be used to generate the random part of the
59            string. Defaults to the `uuid_to_base64`.
60        max_length (int): Maximum length of the generated string.
61
62    Returns:
63        str: Generated random string.
64
65    Raises:
66        ValueError: If the generated string is longer than the maximum length.
67    """
68    if len(result := f"{prefix}{randomizer()}{suffix}") <= max_length:
69        return result
70    msg = (
71        f"Generated string {result!r} is longer than the maximum length of {max_length} characters."
72        f"Ensure the randomizer function does not generate too long strings for you or increase the"
73        f"`max_length` parameter."
74    )
75    raise ValueError(msg)
def random_string( prefix: str = '', suffix: str = '', randomizer: Callable[[], str] = <function uuid_to_base64>, max_length: int = 200) -> str:
47def random_string(
48    prefix: str = "",
49    suffix: str = "",
50    randomizer: Callable[[], str] = uuid_to_base64,
51    max_length: int = 200,
52) -> str:
53    """
54    Generate a random string.
55
56    Args:
57        prefix (str | None): Optional prefix to add to the string.
58        suffix (str | None): Optional suffix to add to the string.
59        randomizer (Callable[[], str]): Optional function that will be used to generate the random part of the
60            string. Defaults to the `uuid_to_base64`.
61        max_length (int): Maximum length of the generated string.
62
63    Returns:
64        str: Generated random string.
65
66    Raises:
67        ValueError: If the generated string is longer than the maximum length.
68    """
69    if len(result := f"{prefix}{randomizer()}{suffix}") <= max_length:
70        return result
71    msg = (
72        f"Generated string {result!r} is longer than the maximum length of {max_length} characters."
73        f"Ensure the randomizer function does not generate too long strings for you or increase the"
74        f"`max_length` parameter."
75    )
76    raise ValueError(msg)

Generate a random string.

Arguments:
  • prefix (str | None): Optional prefix to add to the string.
  • suffix (str | None): Optional suffix to add to the string.
  • randomizer (Callable[[], str]): Optional function that will be used to generate the random part of the string. Defaults to the uuid_to_base64.
  • max_length (int): Maximum length of the generated string.
Returns:

str: Generated random string.

Raises:
  • ValueError: If the generated string is longer than the maximum length.
def uuid_to_base64( uuid_type: Literal['uuid1', 'uuid3', 'uuid4', 'uuid5'] = 'uuid4', namespace: str | None = None) -> str:
15def uuid_to_base64(
16    uuid_type: Literal["uuid1", "uuid3", "uuid4", "uuid5"] = "uuid4", namespace: str | None = None
17) -> str:
18    """
19    Convert a string to a base64 encoded string.
20
21    Args:
22        uuid_type (str): The type of UUID to generate. Must be one of "uuid1", "uuid3", "uuid4", or "uuid5".
23        namespace (str): The namespace to use for the UUID. Only used for "uuid3" and "uuid5" UUID types.
24
25    Returns:
26        str: The base64 encoded string.
27
28    Raises:
29        ValueError: If the UUID type is invalid;
30        ValueError: If the namespace is not provided for "uuid3" and "uuid5" UUID types
31    """
32    match uuid_type:
33        case "uuid1" | "uuid4":
34            input_bytes = getattr(uuid, uuid_type)().hex.encode("utf-8")
35        case "uuid3" | "uuid5":
36            if namespace is None:
37                msg = "Namespace must be provided for 'uuid3' and 'uuid5' UUID types."
38                raise ValueError(msg)
39            input_bytes = getattr(uuid, uuid_type)(uuid.NAMESPACE_DNS, namespace).hex.encode("utf-8")
40        case _:
41            msg = f"Invalid UUID type: {uuid_type!r}"
42            raise ValueError(msg)
43    base64_bytes = base64.b64encode(input_bytes)
44    return base64_bytes.decode("utf-8")

Convert a string to a base64 encoded string.

Arguments:
  • uuid_type (str): The type of UUID to generate. Must be one of "uuid1", "uuid3", "uuid4", or "uuid5".
  • namespace (str): The namespace to use for the UUID. Only used for "uuid3" and "uuid5" UUID types.
Returns:

str: The base64 encoded string.

Raises:
  • ValueError: If the UUID type is invalid;
  • ValueError: If the namespace is not provided for "uuid3" and "uuid5" UUID types