Skip to content

Commit e1fd364

Browse files
committed
fix: attemt to call dict() on non-dict objects
1 parent fa065fe commit e1fd364

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

src/fastapi_redis_cache/client.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,13 @@ def requested_resource_not_modified(self, request: Request, cached_data: str) ->
110110
return self.get_etag(cached_data) in check_etags
111111

112112
def add_to_cache(self, key: str, value: Dict, expire: int) -> bool:
113+
if not isinstance(value, dict): # pragma: no cover
114+
if self.hasmethod(value, 'dict'):
115+
value = value.dict()
116+
else:
117+
message = f"Object of type {type(value)} is not JSON-serializable"
118+
self.log(RedisEvent.FAILED_TO_CACHE_KEY, msg=message, key=key)
119+
return False
113120
cached = self.redis.set(name=key, value=serialize_json(value), ex=expire)
114121
if cached:
115122
self.log(RedisEvent.KEY_ADDED_TO_CACHE, key=key)
@@ -151,3 +158,9 @@ def get_etag(cached_data: Union[str, bytes, Dict]) -> str:
151158
def get_log_time():
152159
"""Get a timestamp to include with a log message."""
153160
return datetime.now().strftime(LOG_TIMESTAMP)
161+
162+
@staticmethod
163+
def hasmethod(obj, method_name):
164+
"""Return True if obj.method_name exists and is callable. Otherwise, return False."""
165+
obj_method = getattr(obj, method_name, None)
166+
return callable(obj_method) if obj_method else False

0 commit comments

Comments
 (0)