2018-06-26 21:48:25 +00:00
|
|
|
import json
|
|
|
|
|
|
|
|
import redis
|
|
|
|
from flask_session import RedisSessionInterface
|
|
|
|
|
|
|
|
import settings
|
2018-09-05 22:27:26 +00:00
|
|
|
from funding.bin.utils import json_encoder
|
2018-06-26 21:48:25 +00:00
|
|
|
|
|
|
|
|
|
|
|
def redis_args():
|
|
|
|
args = {
|
|
|
|
"host": settings.REDIS_HOST,
|
|
|
|
"port": settings.REDIS_PORT,
|
|
|
|
'socket_connect_timeout': 2,
|
|
|
|
'socket_timeout': 2,
|
2018-07-12 00:39:49 +00:00
|
|
|
'retry_on_timeout': True,
|
|
|
|
'decode_responses': True
|
2018-06-26 21:48:25 +00:00
|
|
|
}
|
|
|
|
if settings.REDIS_PASSWD:
|
|
|
|
args["password"] = settings.REDIS_PASSWD
|
|
|
|
return args
|
|
|
|
|
|
|
|
|
|
|
|
class JsonRedisSerializer:
|
|
|
|
@staticmethod
|
|
|
|
def loads(val):
|
|
|
|
try:
|
|
|
|
return json.loads(val).get("wow", {})
|
|
|
|
except ValueError:
|
|
|
|
return
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def dumps(val):
|
|
|
|
try:
|
|
|
|
return json.dumps({"wow": val})
|
|
|
|
except ValueError:
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
class JsonRedis(RedisSessionInterface):
|
|
|
|
serializer = JsonRedisSerializer
|
|
|
|
|
|
|
|
def __init__(self, key_prefix, use_signer=False, decode_responses=True):
|
|
|
|
super(JsonRedis, self).__init__(
|
2018-07-12 00:39:49 +00:00
|
|
|
redis=redis.Redis(**redis_args()),
|
2018-06-26 21:48:25 +00:00
|
|
|
key_prefix=key_prefix,
|
|
|
|
use_signer=use_signer)
|
|
|
|
|
|
|
|
|
|
|
|
class WowCache:
|
|
|
|
def __init__(self):
|
|
|
|
self._cache = redis.StrictRedis(**redis_args())
|
|
|
|
|
|
|
|
def get(self, key):
|
|
|
|
try:
|
|
|
|
return json.loads(self._cache.get(key))
|
|
|
|
except:
|
|
|
|
return {}
|
|
|
|
|
|
|
|
def set(self, key: str, data: dict, expiry = 300):
|
2018-09-05 22:27:26 +00:00
|
|
|
self._cache.set(key, json.dumps(data, default=json_encoder), ex=expiry)
|