def get_status_json(id: IntLike, only_from_cache=False, process_json=True) -> Union[dict, None]: """Get processed status_json * None is returned in case of status is not found * `only_from_cache` is for multiget_status_json() """ key = KEYS.status_json.format(id) data = rd.get(key) # data is a dict with bytes key and bytes value if data: # hit in redis cache result = json.loads(data.decode()) rd.expire(key, KEYS.status_json_expire) if process_json: return Status.process_json(result) return result if only_from_cache: return None print("Can't load status {} from redis".format(id)) print("Try to load from mysql") status = Status.query.get(id) if status is None: print("Can't load status {} from mysql".format(id)) return None result = status.to_json(cache=True) cache_status_json(result) if process_json: return Status.process_json(result) return result
def multiget_status_json(ids: List[IntLike]) -> List['Status']: """ Get multiple statuses by ids result may not have same length of `ids` and may not returned in their's original order """ statuses = [] missed_ids = [] # get from redis cache for index, id in enumerate(ids): status_json = get_status_json(id, only_from_cache=True) if status_json != None: statuses.append(status_json) else: missed_ids.append(id) if not missed_ids: return statuses # get from mysql missed_statuses = Status.query.filter(Status.id.in_(missed_ids)).all() for s in missed_statuses: status_json = s.to_json(cache=True) cache_status_json(status_json) statuses.append(Status.process_json(status_json)) return statuses