1
0
mirror of https://github.com/chubin/cheat.sh.git synced 2026-06-20 21:26:44 +02:00
Files
cheat.sh/lib/cache.py
T
2019-02-17 14:07:02 +01:00

46 lines
975 B
Python

import os
import json
import redis
from globals import REDISHOST
if os.environ.get('REDIS_HOST', '').lower() != 'none':
_REDIS = redis.StrictRedis(host=REDISHOST, port=6379, db=0)
else:
_REDIS = None
if os.environ.get('REDIS_PREFIX', '').lower() != 'none':
_REDIS_PREFIX = os.environ.get('REDIS_PREFIX', '') + ':'
else:
_REDIS_PREFIX = ''
def put(key, value):
"""
Save `value` with `key`, and serialize it if needed
"""
if _REDIS_PREFIX:
key = _REDIS_PREFIX + key
if _REDIS:
if isinstance(value, (dict, list)):
value = json.dumps(value)
_REDIS.set(key, value)
def get(key):
"""
Read `value` by `key`, and deserialize it if needed
"""
if _REDIS_PREFIX:
key = _REDIS_PREFIX + key
if _REDIS:
value = _REDIS.get(key)
try:
value = json.loads(value)
except (ValueError, TypeError):
pass
return value
return None