diff options
author | Jordan Cook <jordan.cook@pioneer.com> | 2021-11-24 08:38:52 -0600 |
---|---|---|
committer | Jordan Cook <jordan.cook@pioneer.com> | 2021-11-24 08:40:22 -0600 |
commit | d07b77d887a20d05a2d9689292ec3f36d8745e0f (patch) | |
tree | 09c2bb97342da7e5eb07ff9ed4f9268eecb3b162 | |
parent | 664b5f61ec42546ec9a509a88e0200ef24ffbfb8 (diff) | |
download | requests-cache-d07b77d887a20d05a2d9689292ec3f36d8745e0f.tar.gz |
Add back overrides for requests.Response.__getstate__ and __setstate__ so plain pickle will work as a serializer
-rw-r--r-- | HISTORY.md | 1 | ||||
-rwxr-xr-x | requests_cache/models/response.py | 9 | ||||
-rw-r--r-- | tests/unit/test_serializers.py | 13 |
3 files changed, 23 insertions, 0 deletions
@@ -25,6 +25,7 @@ * Add support for `BaseCache` keyword arguments passed along with a backend instance * Fix issue with cache headers not being used correctly if `cache_control=True` is used with an `expire_after` value * Fix license metadata as shown on PyPI +* Fix `CachedResponse` serialization behavior when using stdlib `pickle` in a custom serializer ## 0.8.1 (2021-09-15) * Redact `ingored_parameters` from `CachedResponse.url` (if used for credentials or other sensitive info) diff --git a/requests_cache/models/response.py b/requests_cache/models/response.py index 70a3ec0..974d878 100755 --- a/requests_cache/models/response.py +++ b/requests_cache/models/response.py @@ -105,6 +105,15 @@ class CachedResponse(Response): """Get the size of the response body in bytes""" return len(self.content) if self.content else 0 + def __getstate__(self): + """Override pickling behavior from ``requests.Response.__getstate__``""" + return self.__dict__ + + def __setstate__(self, state): + """Override pickling behavior from ``requests.Response.__setstate__``""" + for name, value in state.items(): + setattr(self, name, value) + def __str__(self): return ( f'request: {self.request}, response: {self.status_code} ' diff --git a/tests/unit/test_serializers.py b/tests/unit/test_serializers.py index a9b71be..bf776fd 100644 --- a/tests/unit/test_serializers.py +++ b/tests/unit/test_serializers.py @@ -2,6 +2,7 @@ # Any additional serializer-specific tests can go here. import gzip import json +import pickle import sys from importlib import reload from unittest.mock import patch @@ -93,3 +94,15 @@ def test_custom_serializer(tempfile_path): response = CachedResponse() session.cache.responses['key'] = response assert session.cache.responses['key'] == response + + +def test_plain_pickle(tempfile_path): + """`requests.Response` modifies pickling behavior. If plain `pickle` is used as a serializer, + serializing `CachedResponse` should still work as expected. + """ + session = CachedSession(tempfile_path, serializer=pickle) + + response = CachedResponse() + session.cache.responses['key'] = response + assert session.cache.responses['key'] == response + assert session.cache.responses['key'].expires is None |