Skip to content

utils

T module-attribute

T = TypeVar('T')

run_sync

run_sync(
    coro: Coroutine[Any, Any, T] | Awaitable[T],
) -> T

Run an async function synchronously.

Source code in src/pixel_client/utils.py
15
16
17
18
19
20
21
22
def run_sync(coro: Coroutine[Any, Any, T] | Awaitable[T]) -> T:
    """
    Run an async function synchronously.
    """
    if asyncio.iscoroutinefunction(coro):
        raise ValueError("method is already synchronous")
    loop = asyncio.get_event_loop()
    return loop.run_until_complete(coro)

iter_over_async

iter_over_async(
    async_gen: AsyncGenerator[T, None],
) -> Iterator[T]

Iterate over an async generator synchronously.

Source code in src/pixel_client/utils.py
25
26
27
28
29
30
31
32
33
34
def iter_over_async(async_gen: AsyncGenerator[T, None]) -> Iterator[T]:
    """
    Iterate over an async generator synchronously.
    """
    async_iter = async_gen.__aiter__()
    try:
        while True:
            yield run_sync(async_iter.__anext__())
    except StopAsyncIteration:
        pass

chunks

chunks(lst: list[T], n: int) -> Iterator[list[T]]

Yield successive n-sized chunks from lst.

Source code in src/pixel_client/utils.py
37
38
39
40
def chunks(lst: list[T], n: int) -> Iterator[list[T]]:
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i : i + n]

silence_logger

silence_logger(logger: logging.Logger | None = None)

Temporarily disable a logger.

Source code in src/pixel_client/utils.py
43
44
45
46
47
48
49
50
51
52
53
@contextmanager
def silence_logger(logger: logging.Logger | None = None):
    """
    Temporarily disable a logger.
    """
    logger = logger or logging.getLogger()
    try:
        logger.disabled = True
        yield
    finally:
        logger.disabled = False

calculate_md5_base64_from_file

calculate_md5_base64_from_file(file_path: Path) -> str

Calculate the MD5 hash of a file and return it as a base64 encoded string.

Source code in src/pixel_client/utils.py
56
57
58
59
60
61
def calculate_md5_base64_from_file(file_path: Path) -> str:
    """
    Calculate the MD5 hash of a file and return it as a base64 encoded string.
    """
    with open(file_path, "rb") as f:
        return calculate_md5_base64(f.read())

calculate_md5_base64

calculate_md5_base64(content: bytes) -> str

Calculate the MD5 hash of a byte string and return it as a base64 encoded string.

Source code in src/pixel_client/utils.py
64
65
66
67
68
def calculate_md5_base64(content: bytes) -> str:
    """
    Calculate the MD5 hash of a byte string and return it as a base64 encoded string.
    """
    return base64.b64encode(hashlib.md5(content).digest()).decode()

iter_file_parts

iter_file_parts(
    file_path: Path, part_size: int
) -> Iterator[tuple[int, str, bytes]]

Iterate over a file in parts. Each part is a tuple of the part size, the MD5 hash of the part, and the part itself.

Source code in src/pixel_client/utils.py
71
72
73
74
75
76
77
78
79
80
81
82
def iter_file_parts(
    file_path: Path, part_size: int
) -> Iterator[tuple[int, str, bytes]]:
    """
    Iterate over a file in parts. Each part is a tuple of the part size, the MD5 hash of the part, and the part itself.
    """
    with open(file_path, "rb") as f:
        while True:
            part = f.read(part_size)
            if not part:
                break
            yield len(part), calculate_md5_base64(part), part

download_from_url

download_from_url(url: str, out: IO[bytes]) -> None

Download a file from a URL and write it to a file-like object.

Source code in src/pixel_client/utils.py
85
86
87
88
89
90
91
def download_from_url(url: str, out: IO[bytes]) -> None:
    """
    Download a file from a URL and write it to a file-like object.
    """
    with httpx.stream("GET", url) as response:
        for chunk in response.iter_bytes():
            out.write(chunk)