Skip to content

Commit

Permalink
fix: attemt to call dict() on non-dict objects
Browse files Browse the repository at this point in the history
  • Loading branch information
a-luna committed Jun 14, 2021
1 parent fa065fe commit e1fd364
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/fastapi_redis_cache/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,13 @@ def requested_resource_not_modified(self, request: Request, cached_data: str) ->
return self.get_etag(cached_data) in check_etags

def add_to_cache(self, key: str, value: Dict, expire: int) -> bool:
if not isinstance(value, dict): # pragma: no cover
if self.hasmethod(value, 'dict'):
value = value.dict()
else:
message = f"Object of type {type(value)} is not JSON-serializable"
self.log(RedisEvent.FAILED_TO_CACHE_KEY, msg=message, key=key)
return False
cached = self.redis.set(name=key, value=serialize_json(value), ex=expire)
if cached:
self.log(RedisEvent.KEY_ADDED_TO_CACHE, key=key)
Expand Down Expand Up @@ -151,3 +158,9 @@ def get_etag(cached_data: Union[str, bytes, Dict]) -> str:
def get_log_time():
"""Get a timestamp to include with a log message."""
return datetime.now().strftime(LOG_TIMESTAMP)

@staticmethod
def hasmethod(obj, method_name):
"""Return True if obj.method_name exists and is callable. Otherwise, return False."""
obj_method = getattr(obj, method_name, None)
return callable(obj_method) if obj_method else False

0 comments on commit e1fd364

Please sign in to comment.