Skip to content
This repository was archived by the owner on Jun 1, 2023. It is now read-only.

Commit e9298a4

Browse files
committed
Dump/load dictionary with instances of different classes as values.
1 parent 89838a0 commit e9298a4

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

src/oidcmsg/item.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
from typing import List
2+
from typing import Optional
3+
4+
from oidcmsg.impexp import ImpExp
5+
from oidcmsg.storage import importer
6+
from oidcmsg.storage.utils import qualified_name
7+
8+
9+
class DLDict(ImpExp):
10+
parameter = {
11+
"item_class": "",
12+
"db": {}
13+
}
14+
15+
def __init__(self):
16+
ImpExp.__init__(self)
17+
self.db = {}
18+
19+
def __setitem__(self, key: str, val):
20+
self.db[key] = val
21+
22+
def __getitem__(self, key: str):
23+
return self.db[key]
24+
25+
def dump(self, exclude_attributes: Optional[List[str]] = None) -> dict:
26+
res = {}
27+
28+
for k,v in self.db.items():
29+
_class = qualified_name(v.__class__)
30+
res[k] = [_class, v.dump(exclude_attributes=exclude_attributes)]
31+
32+
return res
33+
34+
def load(self, spec: dict, **kwargs) -> "DLDict":
35+
for attr, (_item_cls, _item) in spec.items():
36+
self.db[attr] = importer(_item_cls)(**kwargs).load(_item)
37+
return self
38+
39+
def keys(self):
40+
return self.db.keys()
41+
42+
def items(self):
43+
return self.db.items()

tests/test_13_dump_item.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from cryptojwt import KeyBundle
2+
from cryptojwt.key_bundle import build_key_bundle
3+
from cryptojwt.utils import qualified_name
4+
5+
from oidcmsg.item import DLDict
6+
7+
KEYSPEC = [
8+
{"type": "RSA", "use": ["sig"]},
9+
{"type": "EC", "crv": "P-256", "use": ["sig"]},
10+
]
11+
12+
KEYSPEC_2 = [
13+
{"type": "RSA", "use": ["sig"]},
14+
{"type": "EC", "crv": "P-256", "use": ["sig"]},
15+
{"type": "EC", "crv": "P-384", "use": ["sig"]},
16+
]
17+
18+
19+
20+
def test_dl_dict():
21+
_dict = DLDict()
22+
_kb1 = build_key_bundle(key_conf=KEYSPEC)
23+
_dict['a'] = _kb1
24+
_kb2 = build_key_bundle(key_conf=KEYSPEC_2)
25+
_dict['b'] = _kb2
26+
27+
dump = _dict.dump()
28+
29+
_dict_copy = DLDict().load(dump)
30+
31+
assert set(_dict_copy.keys()) == {"a", "b"}
32+
33+
kb1_copy = _dict_copy['a']
34+
assert len(kb1_copy.keys()) == 2

0 commit comments

Comments
 (0)