-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathzdict.py
64 lines (57 loc) · 2 KB
/
zdict.py
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
#!/usr/bin/env python3
import sys
import os
import time
import atexit
import msgpack
from io import BytesIO
from tempfile import gettempdir
"""
Usage:
mydict = Zdict("mydict_unique_name", restart_time=60).load()
restart_time : If the app is not restarted before this time, the store
of the dict variable will be deleted.
If not specified, restart_time default value is 3600s
"""
__all__ = ['Zdict']
def _save_var(self):
self._zdictfp = open(self._zdictfile, "wb")
self._zdictfp.write(msgpack.packb(self._obj, use_bin_type=True))
self._zdictfp.flush()
self._zdictfp.close()
# Zdb-backed dict class
class Zdict(dict):
def __init__(self, objname, default={}, restart_time=60, namespace=''):
if not isinstance(default, dict):
raise ValueError(f"Default value is must be {type({})}, "
f"{type(default)} given")
self._obj = default
self._objname = objname
self._zdictfile = gettempdir() + '/' + namespace + '_' + objname
try:
tm = os.stat(self._zdictfile).st_atime
now = time.time()
if now - tm > restart_time:
# zdict file is more than 1hr old...dump it
raise ValueError("Old zdict file")
self._zdictfp = open(self._zdictfile, "rb")
except Exception:
self._zdictfp = open(self._zdictfile, "wb+")
if not self._zdictfp:
raise ValueError("Unable to create backup file")
self._zdictfp.close()
atexit.register(_save_var, self)
def load(self):
val = None
self._zdictfp = open(self._zdictfile, "rb")
myio = BytesIO(self._zdictfp.read())
it = msgpack.Unpacker(myio, raw=False)
self._zdictfp.close()
if not it:
return self._obj
for obj in it:
val = obj
if val:
for k,v in val.items():
self._obj.__setitem__(k, v)
return self._obj