From 914b62502cf510a6c67b61453a67f90c86222f6e Mon Sep 17 00:00:00 2001 From: Jordan Cook Date: Mon, 8 May 2023 12:27:21 -0500 Subject: Fix loading cached JSON content when decode_content=True and the root element is a list --- requests_cache/models/response.py | 2 +- requests_cache/serializers/cattrs.py | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) (limited to 'requests_cache') diff --git a/requests_cache/models/response.py b/requests_cache/models/response.py index 2cd6047..134d04b 100755 --- a/requests_cache/models/response.py +++ b/requests_cache/models/response.py @@ -18,7 +18,7 @@ if TYPE_CHECKING: from ..policy.actions import CacheActions DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S %Z' # Format used for __str__ only -DecodedContent = Union[Dict, str, None] +DecodedContent = Union[Dict, List, str, None] logger = getLogger(__name__) diff --git a/requests_cache/serializers/cattrs.py b/requests_cache/serializers/cattrs.py index bf45c2d..439463e 100644 --- a/requests_cache/serializers/cattrs.py +++ b/requests_cache/serializers/cattrs.py @@ -109,9 +109,12 @@ def init_converter( converter.register_structure_hook( CaseInsensitiveDict, lambda obj, cls: CaseInsensitiveDict(obj) ) - # Convert decoded JSON body back to string + + # Convert decoded JSON body back to a string. If the object is a valid JSON root (dict or list), + # that means it was previously saved in human-readable format due to `decode_content=True`. + # After this hook runs, the body will also be re-encoded with `_encode_content()`. converter.register_structure_hook( - DecodedContent, lambda obj, cls: json.dumps(obj) if isinstance(obj, dict) else obj + DecodedContent, lambda obj, cls: json.dumps(obj) if isinstance(obj, (dict, list)) else obj ) # Resolve forward references (required for CachedResponse.history) @@ -157,7 +160,9 @@ def _decode_content(response: CachedResponse, response_dict: Dict) -> Dict: def _encode_content(response: CachedResponse) -> CachedResponse: - """Re-encode response body if saved as JSON or text; has no effect for a binary response body""" + """Re-encode response body if saved as JSON or text (via ``decode_content=True``). + This has no effect for a binary response body. + """ if isinstance(response._decoded_content, str): response._content = response._decoded_content.encode('utf-8') response._decoded_content = None -- cgit v1.2.1