File: store.py

package info (click to toggle)
python-gcal-sync 7.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 416 kB
  • sloc: python: 4,994; sh: 9; makefile: 5
file content (63 lines) | stat: -rw-r--r-- 1,844 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
61
62
63
"""Library for local storage of calendar data."""

from __future__ import annotations

from abc import ABC
from typing import Any

__all__ = [
    "CalendarStore",
]


class CalendarStore(ABC):
    """Interface for external calendar storage.

    This is an abstract class that may be implemented by callers to provide a
    custom implementation for storing the calendar database.
    """

    async def async_load(self) -> dict[str, Any] | None:
        """Load data."""

    async def async_save(self, data: dict[str, Any]) -> None:
        """Save data."""


class InMemoryCalendarStore(CalendarStore):
    """An in memory implementation of CalendarStore."""

    def __init__(self) -> None:
        self._data: dict[str, Any] | None = None

    async def async_load(self) -> dict[str, Any] | None:
        """Load data."""
        return self._data

    async def async_save(self, data: dict[str, Any]) -> None:
        """Save data."""
        self._data = data


class ScopedCalendarStore(CalendarStore):
    """A store that reads/writes to a key within the store."""

    def __init__(self, store: CalendarStore, key: str) -> None:
        """Initialize ScopedCalendarStore."""
        self._store = store
        self._key = key

    async def async_load(self) -> dict[str, Any]:
        """Load data from the store."""
        store_data = await self._store.async_load()
        if not store_data:
            store_data = {}
        return store_data.get(self._key, {})  # type: ignore[no-any-return]

    async def async_save(self, data: dict[str, Any]) -> None:
        """Save data to the store, performing a read/modify/write"""
        store_data = await self._store.async_load()
        if not store_data:
            store_data = {}
        store_data[self._key] = data
        return await self._store.async_save(store_data)