-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathredisconn.py
96 lines (77 loc) · 2.44 KB
/
redisconn.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# -*- coding: utf-8 -*-
"""
Redis connection wrapper which gives a soft error in case that
noodles is run on a machine without redis
"""
from gevent.coros import RLock
try:
from local_config import RDB
except ImportError:
print "You have not set RDB setting, please" \
"create local_config.py by analogy of local_config.py.template"
import logging
class RedisImportError(Exception):
pass
try:
import redis
except:
redis = None
try:
from config import REDIS_HOST
except ImportError:
REDIS_HOST = 'localhost'
if redis:
# Use here true Redis connection
RedisConn = redis.Redis(host=REDIS_HOST, db=RDB)
else:
# Get warning and use dictionary wrapper
logging.warning('\n >>>>>> Redis-py is not intalled. Simple python'
'dictionary is used instead <<<<< \n')
class RedisConnWrapper(object):
_db = {}
dumb = True
db_lock = RLock()
def lock__db(func):
def gen(self, *args, **kwargs):
self.db_lock.acquire()
func(self, *args, **kwargs)
self.db_lock.release()
return gen
def get(self, key):
return self._db.get(key)
@lock__db
def set(self, key, value):
self._db[key] = value
@lock__db
def incr(self, key):
if self._db.get(key):
self._db[key] += 1
else:
self._db[key] = 1
def smembers(self, set_key):
return self._db.get(set_key)
@lock__db
def spop(self, set_key):
if type(self._db.get(set_key)) != set:
return None
self._db[set_key].pop()
@lock__db
def srem(self, set_key, value):
if type(self._db.get(set_key)) != set:
return False
else:
try:
self._db[set_key].remove(value)
return True
except KeyError:
return False
@lock__db
def sadd(self, set_key, value):
if type(self._db.get(set_key)) != set:
self._db[set_key] = set()
self._db[set_key].add(value)
def __getattr__(self, name):
raise RedisImportError('You use dumb redis storage that doesn\'t'
'support this function,\n you should install redis-server'
'and redis-py')
RedisConn = RedisConnWrapper()