-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
66 lines (47 loc) · 1.04 KB
/
db.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
64
65
66
import config
import json
import os
import threading
_contents = {}
_lock = threading.Lock()
def _write():
"""Writes the database to the filesystem.
Precondition: The lock is acquired by the calling function.
"""
with open(config.db, "w") as db_fd:
json.dump(_contents, db_fd)
def init():
global _contents
_lock.acquire()
if not os.path.isfile(config.db):
_write()
else:
with open(config.db, "r") as db_fd:
_contents = json.load(db_fd)
_lock.release()
def has(name):
_lock.acquire()
res = name in _contents
_lock.release()
return res
def get(name):
_lock.acquire()
res = _contents[name]
_lock.release()
return res
def set(name, value):
_lock.acquire()
_contents[name] = value
_write()
_lock.release()
def delete(name):
_lock.acquire()
if name in _contents:
del _contents[name]
_write()
_lock.release()
def get_all():
_lock.acquire()
res = _contents.copy()
_lock.release()
return res