-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_json.py
48 lines (39 loc) · 1005 Bytes
/
db_json.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
"""
Rudimentary key,value db in a json file
"""
import os
import json
from django.conf import settings
DB_FILE = os.path.join(settings.BASE_DIR, 'db.json')
data = None
def db_set(key, val):
data = __get_data()
if val is None:
if key in data: del data[key]
else:
data[key] = val
__write_data()
def db_get(key, default_value=None):
global data
data = __get_data()
if key in data:
return data[key]
if default_value is not None:
data[key] = default_value
return data[key]
return None
def __write_data():
with open(DB_FILE, 'w') as f:
f.write(json.dumps(data, indent=2))
def __get_data():
global data
if data is None:
try:
with open(DB_FILE) as f:
data = json.loads(f.read())
except FileNotFoundError:
data = {}
except json.decoder.JSONDecodeError:
print('JSON decode error - resetting db')
data = {}
return data