-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
40 lines (30 loc) · 1.08 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
from collections import defaultdict
import redis
from consts import LOCAL_DB_PATH, REDIS_URL
from state import get_default_user_data, serialize, deserialize
def load_from_local_db():
try:
with open(LOCAL_DB_PATH, encoding='utf-8') as f:
data = deserialize(f.read())
except FileNotFoundError:
data = {}
return defaultdict(lambda: get_default_user_data(), data)
def load_db_from_redis():
redis_db = redis.from_url(REDIS_URL)
raw_data = redis_db.get('data')
data = deserialize(raw_data.decode('utf-8')) if raw_data is not None else {}
return defaultdict(lambda: get_default_user_data(), data)
def load_from_db():
if REDIS_URL is None:
print('Using Local DB.')
return load_from_local_db()
else:
print('Using Redis.')
return load_db_from_redis()
def save_state(states):
if REDIS_URL is not None:
redis_db = redis.from_url(REDIS_URL)
redis_db.set('data', serialize(states))
else:
with open(LOCAL_DB_PATH, mode='w', encoding='utf-8') as f:
f.write(serialize(states))