def get_topic(id, user=None): """Gets a single topic (formatted by json_data) from redis or postgresql And performs some pre-filters for the current user Args: id (int): id user (User): the current user Returns: None if the topic is not existed or a dict of topic data """ id = int(id) key = Topic.cache_key(id) redis_client = get_client(key) topic = None if not redis_client.exists(key): topic = Topic.find_by_pk(id) if topic: data = topic.json_data() redis_client.set(key, json.dumps(data)) topic = data else: if redis_client.type(key) == 'hash': print redis_client topic = json.loads(redis_client.get(key)) topic['user_vote'] = Topic.check_vote(user, topic['id']) return topic
def update_topic(id, topic=None): """Updates the cache of article :id Args: id (int): topic id topic (Topic): if not provided, a topic will be queried from postgresql Returns: Topic """ id = int(id) if not topic: topic = Topic.find_by_pk(id) if topic: key = Topic.cache_key(id) redis_client = get_client(key) data = topic.json_data() redis_client.set(key, json.dumps(data)) return topic