Skip to content

Commit 678bb78

Browse files
committed
Refactoring
1 parent 0ebc649 commit 678bb78

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

_FOO_TEST_TEST/FOO_TEST_TEST.py

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,85 @@
44
__author__ = "ipetrash"
55

66

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

0 commit comments

Comments
 (0)