|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +__author__ = "ipetrash" |
| 5 | + |
| 6 | + |
| 7 | +import shelve |
| 8 | +import functools |
| 9 | + |
| 10 | +from pathlib import Path |
| 11 | +from typing import Any |
| 12 | + |
| 13 | + |
| 14 | +DIR: Path = Path(__file__).resolve().parent |
| 15 | +DIR_DB: Path = DIR / "databases" |
| 16 | +DB_FILE_NAME: Path = DIR_DB / "db.shelve" |
| 17 | + |
| 18 | + |
| 19 | +DIR_DB.mkdir(parents=True, exist_ok=True) |
| 20 | + |
| 21 | + |
| 22 | +class DB: |
| 23 | + db_name: str = str(DB_FILE_NAME) |
| 24 | + |
| 25 | + def __init__(self): |
| 26 | + self.db: shelve.Shelf | None = None |
| 27 | + |
| 28 | + def session(*decorator_args, **decorator_kwargs): |
| 29 | + def actual_decorator(func): |
| 30 | + @functools.wraps(func) |
| 31 | + def wrapped(self, *args, **kwargs): |
| 32 | + has_db: bool = self.db is not None |
| 33 | + try: |
| 34 | + if not has_db: |
| 35 | + self.db = shelve.open(self.db_name, writeback=True) |
| 36 | + return func(self, *args, **kwargs) |
| 37 | + finally: |
| 38 | + if not has_db and self.db is not None: |
| 39 | + self.db.close() |
| 40 | + self.db = None |
| 41 | + |
| 42 | + return wrapped |
| 43 | + |
| 44 | + return actual_decorator |
| 45 | + |
| 46 | + @session() |
| 47 | + def get_value(self, name: str, default: Any = None) -> Any: |
| 48 | + if not name: |
| 49 | + return dict(self.db) |
| 50 | + |
| 51 | + if name not in self.db: |
| 52 | + return default |
| 53 | + return self.db.get(name) |
| 54 | + |
| 55 | + @session() |
| 56 | + def set_value(self, name: str, value: Any): |
| 57 | + self.db[name] = value |
| 58 | + |
| 59 | + def inc_value(self, name: str) -> int: |
| 60 | + value = self.get_value(name, default=0) |
| 61 | + value += 1 |
| 62 | + self.set_value(name, value) |
| 63 | + return value |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + db = DB() |
| 68 | + print("name", db.get_value("name")) |
| 69 | + |
| 70 | + db.set_value("name", 123) |
| 71 | + |
| 72 | + users: dict[str, dict[str, Any]] = db.get_value("users", default=dict()) |
| 73 | + print("users", users) |
| 74 | + if not users: |
| 75 | + users["Foo"] = dict(name="Foo", age=12) |
| 76 | + users["Bar"] = dict(name="Bar", age=12) |
| 77 | + db.set_value("users", users) |
| 78 | + |
| 79 | + counter: dict[str, int] = db.get_value("counter", default=dict()) |
| 80 | + print("counter", counter) |
| 81 | + if "value" not in counter: |
| 82 | + counter["value"] = 0 |
| 83 | + counter["value"] += 1 |
| 84 | + db.set_value("counter", counter) |
| 85 | + |
| 86 | + print([db.inc_value("age") for _ in range(3)]) |
| 87 | + |
| 88 | + print(dict(db.get_value(""))) |
0 commit comments