This repository has been archived by the owner on Aug 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtinymp.py
59 lines (46 loc) · 1.48 KB
/
tinymp.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
from tinydb import Storage
import os
def touch(fname, create_dirs):
if create_dirs:
base_dir = os.path.dirname(fname)
if not os.path.exists(base_dir):
os.makedirs(base_dir)
with open(fname, 'a'):
os.utime(fname, None)
class MsgPackStorage(Storage):
def __init__(self, path, create_dirs=False, **kwargs):
super(MsgPackStorage, self).__init__()
touch(path, create_dirs=create_dirs) # Create file if not exists
self.kwargs = kwargs
'''
Import the correct msgpack library
'''
if 'Lib' in kwargs:
self.library = self.kwargs['Lib']
if self.library == 'umsgpack':
import umsgpack as msgpack
self.msgpack = msgpack
else:
import msgpack
self.msgpack = msgpack
else:
import msgpack
self.msgpack = msgpack
self._handle = open(path, 'r+')
def write(self, data):
self._handle.seek(0)
serialized = self.msgpack.dump(data, self._handle)
self._handle.flush()
self._handle.truncate()
def read(self):
# Get the file size
self._handle.seek(0, os.SEEK_END)
size = self._handle.tell()
if not size:
# File is empty
return None
else:
self._handle.seek(0)
return self.msgpack.unpackb(self._handle.read())
def close(self):
self._handle.close()