2014-02-05 00:35:32 +01:00
|
|
|
from django.conf import settings
|
2020-01-20 14:17:53 +01:00
|
|
|
from typing import Any, Dict, Optional
|
|
|
|
from zerver.lib.utils import generate_random_token
|
2014-02-05 00:35:32 +01:00
|
|
|
|
|
|
|
import redis
|
2020-01-20 14:17:53 +01:00
|
|
|
import ujson
|
2014-02-05 00:35:32 +01:00
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def get_redis_client() -> redis.StrictRedis:
|
2016-08-01 04:51:00 +02:00
|
|
|
return redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT,
|
|
|
|
password=settings.REDIS_PASSWORD, db=0)
|
2020-01-20 14:17:53 +01:00
|
|
|
|
|
|
|
def put_dict_in_redis(redis_client: redis.StrictRedis, key_format: str,
|
|
|
|
data_to_store: Dict[str, Any],
|
2020-01-23 12:21:55 +01:00
|
|
|
expiration_seconds: int,
|
|
|
|
token_length: int=64) -> str:
|
2020-01-20 14:17:53 +01:00
|
|
|
with redis_client.pipeline() as pipeline:
|
2020-01-23 12:21:55 +01:00
|
|
|
token = generate_random_token(token_length)
|
2020-01-20 14:17:53 +01:00
|
|
|
key = key_format.format(token=token)
|
|
|
|
pipeline.set(key, ujson.dumps(data_to_store))
|
|
|
|
pipeline.expire(key, expiration_seconds)
|
|
|
|
pipeline.execute()
|
|
|
|
|
|
|
|
return key
|
|
|
|
|
|
|
|
def get_dict_from_redis(redis_client: redis.StrictRedis, key: str) -> Optional[Dict[str, Any]]:
|
|
|
|
data = redis_client.get(key)
|
|
|
|
if data is None:
|
|
|
|
return None
|
|
|
|
return ujson.loads(data)
|