Make Request and Response picklable (#1579)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Make Request and Response picklable * fixup! Make Request and Response picklable * Apply suggestions from code review * Apply suggestions from code review * Update tests/models/test_requests.py
authored by Hannes Ljungberg · committed by GitHub · parent 9b8f5af · Browse files · 4 files·+133 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Tom Christie <tom@tomchristie.com>
Diff stats
4 files+133 added−2 removed
- tests:+91 added−0 removed
- other:+42 added−2 removed
Provenance
- Commit
2d57104- Tree
81ead62- Author
Hannes Ljungberg <hannes@5monkeys.se>- Committer
GitHub <noreply@github.com>- Parent
9b8f5af
4 files changed+133 added−2 removed
modified:httpx/_content.py+16 added-1 removed
11 unmodified lines12 Union,13 )14 from urllib.parse import urlencode15 16-from ._exceptions import StreamConsumed16+from ._exceptions import StreamClosed, StreamConsumed17 from ._multipart import MultipartStream18 from ._transports.base import AsyncByteStream, SyncByteStream19 from ._types import RequestContent, RequestData, RequestFiles, ResponseContent20 from ._utils import primitive_value_to_str39 unmodified lines60 async for part in self._stream:61 yield part62 63 64+class UnattachedStream(AsyncByteStream, SyncByteStream):65+ """66+ If a request or response is serialized using pickle, then it is no longer67+ attached to a stream for I/O purposes. Any stream operations should result68+ in `httpx.StreamClosed`.69+ """70+71+ def __iter__(self) -> Iterator[bytes]:72+ raise StreamClosed()73+74+ async def __aiter__(self) -> AsyncIterator[bytes]:75+ raise StreamClosed()76+ yield b"" # pragma: nocover77+78+79 def encode_content(80 content: Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]81 ) -> Tuple[Dict[str, str], Union[SyncByteStream, AsyncByteStream]]:82 120 unmodified linesmodified:httpx/_models.py+26 added-1 removed
9 unmodified lines10 11 import rfc398612 import rfc3986.exceptions13 14-from ._content import ByteStream, encode_request, encode_response14+from ._content import ByteStream, UnattachedStream, encode_request, encode_response15 from ._decoders import (16 SUPPORTED_DECODERS,17 ByteChunker,18 ContentDecoder,878 unmodified lines897 class_name = self.__class__.__name__898 url = str(self.url)899 return f"<{class_name}({self.method!r}, {url!r})>"900 901+ def __getstate__(self) -> typing.Dict[str, typing.Any]:902+ return {903+ name: value904+ for name, value in self.__dict__.items()905+ if name not in ["stream"]906+ }907 908+ def __setstate__(self, state: typing.Dict[str, typing.Any]) -> None:909+ for name, value in state.items():910+ setattr(self, name, value)911+ self.stream = UnattachedStream()912+913+914 class Response:915 def __init__(916 self,917 status_code: int,249 unmodified lines1167 1168 def __repr__(self) -> str:1169 return f"<Response [{self.status_code} {self.reason_phrase}]>"1170 1171+ def __getstate__(self) -> typing.Dict[str, typing.Any]:1172+ return {1173+ name: value1174+ for name, value in self.__dict__.items()1175+ if name not in ["stream", "is_closed", "_decoder"]1176+ }1177+1178+ def __setstate__(self, state: typing.Dict[str, typing.Any]) -> None:1179+ for name, value in state.items():1180+ setattr(self, name, value)1181+ self.is_closed = True1182+ self.stream = UnattachedStream()1183+1184 def read(self) -> bytes:1185 """1186 Read and return the response content.1187 """382 unmodified linesmodified:tests/models/test_requests.py+52 added
1+import pickle2 import typing3 4 import pytest5 168 unmodified lines174 assert request.url.scheme == "https"175 assert request.url.port is None176 assert request.url.path == "/abc"177 assert request.url.raw_path == b"/abc?foo=bar"178+179+180+def test_request_picklable():181+ request = httpx.Request("POST", "http://example.org", json={"test": 123})182+ pickle_request = pickle.loads(pickle.dumps(request))183+ assert pickle_request.method == "POST"184+ assert pickle_request.url.path == "/"185+ assert pickle_request.headers["Content-Type"] == "application/json"186+ assert pickle_request.content == b'{"test": 123}'187+ assert pickle_request.stream is not None188+ assert request.headers == {189+ "Host": "example.org",190+ "Content-Type": "application/json",191+ "content-length": "13",192+ }193+194+195+@pytest.mark.asyncio196+async def test_request_async_streaming_content_picklable():197+ async def streaming_body(data):198+ yield data199+200+ data = streaming_body(b"test 123")201+ request = httpx.Request("POST", "http://example.org", content=data)202+ pickle_request = pickle.loads(pickle.dumps(request))203+ with pytest.raises(httpx.RequestNotRead):204+ pickle_request.content205+ with pytest.raises(httpx.StreamClosed):206+ await pickle_request.aread()207+208+ request = httpx.Request("POST", "http://example.org", content=data)209+ await request.aread()210+ pickle_request = pickle.loads(pickle.dumps(request))211+ assert pickle_request.content == b"test 123"212+213+214+def test_request_generator_content_picklable():215+ def content():216+ yield b"test 123" # pragma: nocover217+218+ request = httpx.Request("POST", "http://example.org", content=content())219+ pickle_request = pickle.loads(pickle.dumps(request))220+ with pytest.raises(httpx.RequestNotRead):221+ pickle_request.content222+ with pytest.raises(httpx.StreamClosed):223+ pickle_request.read()224+225+ request = httpx.Request("POST", "http://example.org", content=content())226+ request.read()227+ pickle_request = pickle.loads(pickle.dumps(request))228+ assert pickle_request.content == b"test 123"modified:tests/models/test_responses.py+39 added
1 import json2+import pickle3 from unittest import mock4 5 import brotli6 import pytest846 unmodified lines853 854 headers = {"Content-Length": "8"}855 response = httpx.Response(200, content=content(), headers=headers)856 assert response.headers == {"Content-Length": "8"}857+858+859+def test_response_picklable():860+ response = httpx.Response(861+ 200,862+ content=b"Hello, world!",863+ request=httpx.Request("GET", "https://example.org"),864+ )865+ pickle_response = pickle.loads(pickle.dumps(response))866+ assert pickle_response.is_closed is True867+ assert pickle_response.is_stream_consumed is True868+ assert pickle_response.next_request is None869+ assert pickle_response.stream is not None870+ assert pickle_response.content == b"Hello, world!"871+ assert pickle_response.status_code == 200872+ assert pickle_response.request.url == response.request.url873+ assert pickle_response.extensions == {}874+ assert pickle_response.history == []875+876+877+@pytest.mark.asyncio878+async def test_response_async_streaming_picklable():879+ response = httpx.Response(200, content=async_streaming_body())880+ pickle_response = pickle.loads(pickle.dumps(response))881+ with pytest.raises(httpx.ResponseNotRead):882+ pickle_response.content883+ with pytest.raises(httpx.StreamClosed):884+ await pickle_response.aread()885+ assert pickle_response.is_stream_consumed is False886+ assert pickle_response.num_bytes_downloaded == 0887+ assert pickle_response.headers == {"Transfer-Encoding": "chunked"}888+889+ response = httpx.Response(200, content=async_streaming_body())890+ await response.aread()891+ pickle_response = pickle.loads(pickle.dumps(response))892+ assert pickle_response.is_stream_consumed is True893+ assert pickle_response.content == b"Hello, world!"894+ assert pickle_response.num_bytes_downloaded == 13