File: utils.py

package info (click to toggle)
python-aioskybell 23.12.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 304 kB
  • sloc: python: 1,422; makefile: 22
file content (60 lines) | stat: -rw-r--r-- 1,442 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""AIOSkybell utility methods."""
from __future__ import annotations

import pickle
import random
import string
import uuid
from typing import Any

import aiofiles

from .helpers.models import EventTypeDict


async def async_save_cache(
    data: dict[str, str | dict[str, EventTypeDict]],
    filename: str,
) -> None:
    """Save cache from file."""
    async with aiofiles.open(filename, "wb") as file:
        pickled_foo = pickle.dumps(data)
        await file.write(pickled_foo)


async def async_load_cache(
    filename: str,
) -> dict[str, str | dict[str, dict[str, dict[str, dict[str, str]]]]]:
    """Load cache from file."""
    async with aiofiles.open(filename, "rb") as file:
        pickled_foo = await file.read()

    return pickle.loads(pickled_foo)


def gen_id() -> str:
    """Generate new Skybell IDs."""
    return str(uuid.uuid4())


def gen_token() -> str:
    """Generate a new Skybell token."""
    return "".join(
        random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)
        for _ in range(32)
    )


def update(
    dct: dict[str, Any],
    dct_merge: dict[str, Any],
) -> dict[str, Any]:
    """Recursively merge dicts."""
    if not isinstance(dct, dict):
        return dct
    for key, value in dct_merge.items():
        if key in dct and isinstance(dct[key], dict):
            dct[key] = update(dct[key], value)
        else:
            dct[key] = value
    return dct