redis_lib.py 1.04 KB
Newer Older
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
import redis


class RedisManager:
    def __init__(self, host='localhost', port=6379, db=0):
        self._host = host
        self._port = port
        self._db = db

    def __enter__(self):
        """ Opening connection with Redis"""
        self._redis_cli = redis.Redis(host=self._host, port=self._port, db=self._db)
        return self

    def key_exists(self, key):
        """Returns TRUE if key exists"""
        if self._redis_cli.exists(key) == 1:
            return True
        else:
            return False

    def save(self, key, value):
        try:
            self._redis_cli.set(name=key, value=value)
        except Exception as e:
            print(f'Error: {e}')

    def get_by_key(self, key):
        """Return value by key"""
        try:
            return self._redis_cli.get(key).decode('UTF-8')
        except Exception as e:
            print(e)
            return None

    def __exit__(self, exc_type, exc_val, exc_tb):
        """ Closing the connection """
        self._redis_cli.close()
        if exc_val:
            raise