-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.py
82 lines (63 loc) · 2.28 KB
/
store.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# -*- coding: utf-8 -*-
from time import sleep
from pathlib import Path
import logging
import configparser
import redis
def init_config():
"""Init configuration"""
cp = configparser.ConfigParser()
config_file = str(Path(__file__).parent.joinpath('settings.ini'))
cp.read(config_file)
cp_section = cp['store']
host = cp_section.get('HOST')
port = int(cp_section.get('PORT'))
timeout = int(cp_section.get('TIMEOUT'))
return host, port, timeout
def retry(count=3, interval=1):
def my_decorator(func):
def wrapper(*args, **kwargs):
attempt = 1
while True:
try:
return func(*args, **kwargs)
except Exception as e:
logging.info('DB connection failed, attemp: %s', attempt)
attempt += 1
if attempt > count:
raise e
sleep(interval)
return wrapper
return my_decorator
HOST, PORT, SOCKET_TIMEOUT = init_config()
class Store:
def __init__(self, host=HOST, port=PORT, socket_timeout=SOCKET_TIMEOUT):
self._r = redis.Redis(host=host, port=port, socket_timeout=socket_timeout, decode_responses=True)
def ping(self):
return self._r.ping()
@retry()
def get(self, key):
return self._r.get(key)
@retry()
def set(self, name, value, ex=None):
return self._r.set(name, value, ex)
def cache_get(self, key):
try:
logging.info('Getting value from cache')
return self._r.get(key)
except Exception as e:
logging.info(e)
return None
def cache_set(self, name, value, ex=None):
try:
logging.info('Writing value to cache')
return self._r.set(name, value, ex)
except Exception as e:
logging.info(e)
def create_interests(self):
interests = ["cars", "pets", "travel", "hi-tech", "sport", "music",
"books", "tv", "cinema", "geek", "otus"]
for _id, interest in enumerate(interests, start=1):
self.set(f'i:{_id}', interest)
def disconnect(self):
self._r.connection_pool.disconnect()