Stream interface (#1550)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add SyncByteStream, AsyncByteStream to interface * request.stream and response.stream as httpx.SyncByteStream/httpx.AsyncByteStream * Update httpx/_transports/base.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Update httpx/_transports/default.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Move response classes in transports to module level
authored by Tom Christie · committed by GitHub · parent 535df6c · Browse files · 13 files·+221 added−155 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: Florimond Manca <florimond.manca@gmail.com>
Diff stats
13 files+221 added−155 removed
- tests:+9 added−9 removed
- other:+212 added−146 removed
Provenance
- Commit
110ce85- Tree
c1602f9- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
535df6c
13 files changed+221 added−155 removed
modified:docs/advanced.md+2 added-2 removed
1068 unmodified lines1069 1070 def handle_request(self, method, url, headers, stream, extensions):1071 message = {"text": "Hello, world!"}1072 content = json.dumps(message).encode("utf-8")1073- stream = [content]1073+ stream = httpx.ByteStream(content)1074 headers = [(b"content-type", b"application/json")]1075 extensions = {}1076 return 200, headers, stream, extensions1077 ```52 unmodified lines1130 if port is None:1131 location = b"https://%s%s" % (host, path)1132 else:1133 location = b"https://%s:%d%s" % (host, port, path)1134- stream = [b""]1134+ stream = httpx.ByteStream(b"")1135 headers = [(b"location", location)]1136 extensions = {}1137 return 303, headers, stream, extensions1138 37 unmodified linesmodified:httpx/_transports/asgi.py+13 added-7 removed
1 unmodified line2 from urllib.parse import unquote3 4 import sniffio5 6-from .base import AsyncBaseTransport6+from .base import AsyncBaseTransport, AsyncByteStream7 8 if typing.TYPE_CHECKING: # pragma: no cover9 import asyncio10 12 unmodified lines23 24 return asyncio.Event()25 26 27+class ASGIResponseStream(AsyncByteStream):28+ def __init__(self, body: typing.List[bytes]) -> None:29+ self._body = body30+31+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:32+ yield b"".join(self._body)33+34+35 class ASGITransport(AsyncBaseTransport):36 """37 A custom AsyncTransport that handles sending requests directly to an ASGI app.38 The simplest way to use this functionality is to use the `app` argument.42 unmodified lines81 self,82 method: bytes,83 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],84 headers: typing.List[typing.Tuple[bytes, bytes]],77- stream: typing.AsyncIterable[bytes],85+ stream: AsyncByteStream,86 extensions: dict,87 ) -> typing.Tuple[80- int, typing.List[typing.Tuple[bytes, bytes]], typing.AsyncIterable[bytes], dict88+ int, typing.List[typing.Tuple[bytes, bytes]], AsyncByteStream, dict89 ]:90 # ASGI scope.91 scheme, host, port, full_path = url92 path, _, query = full_path.partition(b"?")69 unmodified lines162 assert response_complete.is_set()163 assert status_code is not None164 assert response_headers is not None165 158- async def response_stream() -> typing.AsyncIterator[bytes]:159- yield b"".join(body_parts)160-166+ stream = ASGIResponseStream(body_parts)167 extensions = {}168 163- return (status_code, response_headers, response_stream(), extensions)169+ return (status_code, response_headers, stream, extensions)modified:httpx/_transports/base.py+67 added-13 removed
3 unmodified lines4 T = typing.TypeVar("T", bound="BaseTransport")5 A = typing.TypeVar("A", bound="AsyncBaseTransport")6 7 8+class SyncByteStream:9+ def __iter__(self) -> typing.Iterator[bytes]:10+ raise NotImplementedError(11+ "The '__iter__' method must be implemented."12+ ) # pragma: nocover13+ yield b"" # pragma: nocover14+15+ def close(self) -> None:16+ """17+ Subclasses can override this method to release any network resources18+ after a request/response cycle is complete.19+20+ Streaming cases should use a `try...finally` block to ensure that21+ the stream `close()` method is always called.22+23+ Example:24+25+ status_code, headers, stream, extensions = transport.handle_request(...)26+ try:27+ ...28+ finally:29+ stream.close()30+ """31+32+ def read(self) -> bytes:33+ """34+ Simple cases can use `.read()` as a convience method for consuming35+ the entire stream and then closing it.36+37+ Example:38+39+ status_code, headers, stream, extensions = transport.handle_request(...)40+ body = stream.read()41+ """42+ try:43+ return b"".join([part for part in self])44+ finally:45+ self.close()46+47+48+class AsyncByteStream:49+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:50+ raise NotImplementedError(51+ "The '__aiter__' method must be implemented."52+ ) # pragma: nocover53+ yield b"" # pragma: nocover54+55+ async def aclose(self) -> None:56+ pass57+58+ async def aread(self) -> bytes:59+ try:60+ return b"".join([part async for part in self])61+ finally:62+ await self.aclose()63+64+65 class BaseTransport:66 def __enter__(self: T) -> T:67 return self68 9 unmodified lines78 self,79 method: bytes,80 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],81 headers: typing.List[typing.Tuple[bytes, bytes]],25- stream: typing.Iterable[bytes],82+ stream: SyncByteStream,83 extensions: dict,84 ) -> typing.Tuple[28- int, typing.List[typing.Tuple[bytes, bytes]], typing.Iterable[bytes], dict85+ int, typing.List[typing.Tuple[bytes, bytes]], SyncByteStream, dict86 ]:87 """88 Send a single HTTP request and return a response.89 5 unmodified lines95 Developers shouldn't typically ever need to call into this API directly,96 since the Client class provides all the higher level user-facing API97 niceties.98 99+ In order to properly release any network resources, the response stream100+ should *either* be consumed immediately, with a call to `stream.read()`,101+ or else the `handle_request` call should be followed with a try/finally102+ block to ensuring the stream is always closed.103+104 Example usage:105 106 with httpx.HTTPTransport() as transport:107 status_code, headers, stream, extensions = transport.handle_request(2 unmodified lines110 headers=[(b'Host', b'www.example.com')],111 stream=[],112 extensions={}113 )52- try:53- body = b''.join([part for part in stream])54- finally:55- if 'close' in extensions:56- extensions['close']()114+ body = stream.read()115 print(status_code, headers, body)116 117 Arguments:118 24 unmodified lines143 for a default, as it indicates the server left the portion blank144 eg. the leading response bytes were b"HTTP/1.1 200 <CRLF>".145 http_version: The HTTP version, as bytes. Eg. b"HTTP/1.1".146 When no http_version key is included, HTTP/1.1 may be assumed.89- close: A callback which should be invoked to release any network90- resources.91- aclose: An async callback which should be invoked to release any92- network resources.147 """148 raise NotImplementedError(149 "The 'handle_request' method must be implemented."150 ) # pragma: nocover18 unmodified lines169 self,170 method: bytes,171 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],172 headers: typing.List[typing.Tuple[bytes, bytes]],119- stream: typing.AsyncIterable[bytes],173+ stream: AsyncByteStream,174 extensions: dict,175 ) -> typing.Tuple[122- int, typing.List[typing.Tuple[bytes, bytes]], typing.AsyncIterable[bytes], dict176+ int, typing.List[typing.Tuple[bytes, bytes]], AsyncByteStream, dict177 ]:178 raise NotImplementedError(179 "The 'handle_async_request' method must be implemented."180 ) # pragma: nocover3 unmodified linesmodified:httpx/_transports/default.py+37 added-27 removed
47 unmodified lines48 WriteError,49 WriteTimeout,50 )51 from .._types import CertTypes, VerifyTypes52-from .base import AsyncBaseTransport, BaseTransport52+from .base import AsyncBaseTransport, AsyncByteStream, BaseTransport, SyncByteStream53 54 T = typing.TypeVar("T", bound="HTTPTransport")55 A = typing.TypeVar("A", bound="AsyncHTTPTransport")56 52 unmodified lines109 httpcore.RemoteProtocolError: RemoteProtocolError,110 }111 112 113+class ResponseStream(SyncByteStream):114+ def __init__(self, httpcore_stream: httpcore.SyncByteStream):115+ self._httpcore_stream = httpcore_stream116+117+ def __iter__(self) -> typing.Iterator[bytes]:118+ with map_httpcore_exceptions():119+ for part in self._httpcore_stream:120+ yield part121+122+ def close(self) -> None:123+ with map_httpcore_exceptions():124+ self._httpcore_stream.close()125+126+127 class HTTPTransport(BaseTransport):128 def __init__(129 self,130 verify: VerifyTypes = True,50 unmodified lines181 self,182 method: bytes,183 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],184 headers: typing.List[typing.Tuple[bytes, bytes]],171- stream: typing.Iterable[bytes],185+ stream: SyncByteStream,186 extensions: dict,187 ) -> typing.Tuple[174- int, typing.List[typing.Tuple[bytes, bytes]], typing.Iterable[bytes], dict188+ int, typing.List[typing.Tuple[bytes, bytes]], SyncByteStream, dict189 ]:190 with map_httpcore_exceptions():191 status_code, headers, byte_stream, extensions = self._pool.request(192 method=method,2 unmodified lines195 stream=httpcore.IteratorByteStream(iter(stream)),196 ext=extensions,197 )198 185- def response_stream() -> typing.Iterator[bytes]:186- with map_httpcore_exceptions():187- for part in byte_stream:188- yield part189-190- def close() -> None:191- with map_httpcore_exceptions():192- byte_stream.close()193-199 ensure_http_version_reason_phrase_as_bytes(extensions)195- extensions["close"] = close200+ stream = ResponseStream(byte_stream)201 197- return status_code, headers, response_stream(), extensions202+ return status_code, headers, stream, extensions203 204 def close(self) -> None:205 self._pool.close()206 207 208+class AsyncResponseStream(AsyncByteStream):209+ def __init__(self, httpcore_stream: httpcore.AsyncByteStream):210+ self._httpcore_stream = httpcore_stream211+212+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:213+ with map_httpcore_exceptions():214+ async for part in self._httpcore_stream:215+ yield part216+217+ async def aclose(self) -> None:218+ with map_httpcore_exceptions():219+ await self._httpcore_stream.aclose()220+221+222 class AsyncHTTPTransport(AsyncBaseTransport):223 def __init__(224 self,225 verify: VerifyTypes = True,50 unmodified lines276 self,277 method: bytes,278 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],279 headers: typing.List[typing.Tuple[bytes, bytes]],261- stream: typing.AsyncIterable[bytes],280+ stream: AsyncByteStream,281 extensions: dict,282 ) -> typing.Tuple[264- int, typing.List[typing.Tuple[bytes, bytes]], typing.AsyncIterable[bytes], dict283+ int, typing.List[typing.Tuple[bytes, bytes]], AsyncByteStream, dict284 ]:285 with map_httpcore_exceptions():286 status_code, headers, byte_stream, extensions = await self._pool.arequest(287 method=method,2 unmodified lines290 stream=httpcore.AsyncIteratorByteStream(stream.__aiter__()),291 ext=extensions,292 )293 275- async def response_stream() -> typing.AsyncIterator[bytes]:276- with map_httpcore_exceptions():277- async for part in byte_stream:278- yield part279-280- async def aclose() -> None:281- with map_httpcore_exceptions():282- await byte_stream.aclose()283-294 ensure_http_version_reason_phrase_as_bytes(extensions)285- extensions["aclose"] = aclose295+ stream = AsyncResponseStream(byte_stream)296 287- return status_code, headers, response_stream(), extensions297+ return status_code, headers, stream, extensions298 299 async def aclose(self) -> None:300 await self._pool.aclose()modified:httpx/_transports/mock.py+5 added-5 removed
1 import asyncio2 import typing3 4 from .._models import Request5-from .base import AsyncBaseTransport, BaseTransport5+from .base import AsyncBaseTransport, AsyncByteStream, BaseTransport, SyncByteStream6 7 8 class MockTransport(AsyncBaseTransport, BaseTransport):9 def __init__(self, handler: typing.Callable) -> None:3 unmodified lines13 self,14 method: bytes,15 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],16 headers: typing.List[typing.Tuple[bytes, bytes]],17- stream: typing.Iterable[bytes],17+ stream: SyncByteStream,18 extensions: dict,19 ) -> typing.Tuple[20- int, typing.List[typing.Tuple[bytes, bytes]], typing.Iterable[bytes], dict20+ int, typing.List[typing.Tuple[bytes, bytes]], SyncByteStream, dict21 ]:22 request = Request(23 method=method,24 url=url,13 unmodified lines38 self,39 method: bytes,40 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],41 headers: typing.List[typing.Tuple[bytes, bytes]],42- stream: typing.AsyncIterable[bytes],42+ stream: AsyncByteStream,43 extensions: dict,44 ) -> typing.Tuple[45- int, typing.List[typing.Tuple[bytes, bytes]], typing.AsyncIterable[bytes], dict45+ int, typing.List[typing.Tuple[bytes, bytes]], AsyncByteStream, dict46 ]:47 request = Request(48 method=method,49 url=url,21 unmodified linesmodified:httpx/_transports/wsgi.py+15 added-7 removed
1 unmodified line2 import itertools3 import typing4 from urllib.parse import unquote5 6-from .base import BaseTransport6+from .base import BaseTransport, SyncByteStream7 8 9 def _skip_leading_empty_chunks(body: typing.Iterable) -> typing.Iterable:10 body = iter(body)2 unmodified lines13 return itertools.chain([chunk], body)14 return []15 16 17+class WSGIByteStream(SyncByteStream):18+ def __init__(self, result: typing.Iterable[bytes]) -> None:19+ self._result = _skip_leading_empty_chunks(result)20+21+ def __iter__(self) -> typing.Iterator[bytes]:22+ for part in self._result:23+ yield part24+25+26 class WSGITransport(BaseTransport):27 """28 A custom transport that handles sending requests directly to an WSGI app.29 The simplest way to use this functionality is to use the `app` argument.42 unmodified lines72 self,73 method: bytes,74 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],75 headers: typing.List[typing.Tuple[bytes, bytes]],67- stream: typing.Iterable[bytes],76+ stream: SyncByteStream,77 extensions: dict,78 ) -> typing.Tuple[70- int, typing.List[typing.Tuple[bytes, bytes]], typing.Iterable[bytes], dict79+ int, typing.List[typing.Tuple[bytes, bytes]], SyncByteStream, dict80 ]:81 wsgi_input = io.BytesIO(b"".join(stream))82 83 scheme, host, port, full_path = url35 unmodified lines119 seen_response_headers = response_headers120 seen_exc_info = exc_info121 122 result = self.app(environ, start_response)114- # This is needed because the status returned by start_response115- # shouldn't be used until the first non-empty chunk has been served.116- result = _skip_leading_empty_chunks(result)123 124+ stream = WSGIByteStream(result)125+126 assert seen_status is not None127 assert seen_response_headers is not None128 if seen_exc_info and self.raise_app_exceptions:129 raise seen_exc_info[1]4 unmodified lines134 for key, value in seen_response_headers135 ]136 extensions = {}137 130- return (status_code, headers, result, extensions)138+ return (status_code, headers, stream, extensions)modified:httpx/__init__.py+10 added-1 removed
1 unmodified line2 from ._api import delete, get, head, options, patch, post, put, request, stream3 from ._auth import Auth, BasicAuth, DigestAuth4 from ._client import AsyncClient, Client5 from ._config import Limits, Proxy, Timeout, create_ssl_context6+from ._content import ByteStream7 from ._exceptions import (8 CloseError,9 ConnectError,10 ConnectTimeout,25 unmodified lines36 )37 from ._models import URL, Cookies, Headers, QueryParams, Request, Response38 from ._status_codes import StatusCode, codes39 from ._transports.asgi import ASGITransport39-from ._transports.base import AsyncBaseTransport, BaseTransport40+from ._transports.base import (41+ AsyncBaseTransport,42+ AsyncByteStream,43+ BaseTransport,44+ SyncByteStream,45+)46 from ._transports.default import AsyncHTTPTransport, HTTPTransport47 from ._transports.mock import MockTransport48 from ._transports.wsgi import WSGITransport49 2 unmodified lines52 "__title__",53 "__version__",54 "ASGITransport",55 "AsyncBaseTransport",56+ "AsyncByteStream",57 "AsyncClient",58 "AsyncHTTPTransport",59 "Auth",60 "BaseTransport",61 "BasicAuth",62+ "ByteStream",63 "Client",64 "CloseError",65 "codes",66 "ConnectError",37 unmodified lines104 "StatusCode",105 "stream",106 "StreamConsumed",107 "StreamError",108+ "SyncByteStream",109 "Timeout",110 "TimeoutException",111 "TooManyRedirects",112 "TransportError",12 unmodified linesmodified:httpx/_client.py+9 added-7 removed
24 unmodified lines25 )26 from ._models import URL, Cookies, Headers, QueryParams, Request, Response27 from ._status_codes import codes28 from ._transports.asgi import ASGITransport29-from ._transports.base import AsyncBaseTransport, BaseTransport29+from ._transports.base import (30+ AsyncBaseTransport,31+ AsyncByteStream,32+ BaseTransport,33+ SyncByteStream,34+)35 from ._transports.default import AsyncHTTPTransport, HTTPTransport36 from ._transports.wsgi import WSGITransport37 from ._types import (38 AuthTypes,34- ByteStream,39 CertTypes,40 CookieTypes,41 HeaderTypes,42 ProxiesTypes,469 unmodified lines512 return headers513 514 def _redirect_stream(515 self, request: Request, method: str512- ) -> typing.Optional[ByteStream]:516+ ) -> typing.Optional[typing.Union[SyncByteStream, AsyncByteStream]]:517 """518 Return the body that should be used for the redirect request.519 """520 if method != request.method and method == "GET":362 unmodified lines883 )884 885 def on_close(response: Response) -> None:886 response.elapsed = datetime.timedelta(seconds=timer.sync_elapsed())883- if "close" in extensions:884- extensions["close"]()887+ stream.close()888 889 response = Response(890 status_code,891 headers=headers,634 unmodified lines1526 )1527 1528 async def on_close(response: Response) -> None:1529 response.elapsed = datetime.timedelta(seconds=await timer.async_elapsed())1527- if "aclose" in extensions:1528- await extensions["aclose"]()1530+ await stream.aclose()1531 1532 response = Response(1533 status_code,1534 headers=headers,349 unmodified linesmodified:httpx/_content.py+41 added-64 removed
12 unmodified lines13 from urllib.parse import urlencode14 15 from ._exceptions import StreamConsumed16 from ._multipart import MultipartStream17-from ._types import (18- ByteStream,19- RequestContent,20- RequestData,21- RequestFiles,22- ResponseContent,23-)17+from ._transports.base import AsyncByteStream, SyncByteStream18+from ._types import RequestContent, RequestData, RequestFiles, ResponseContent19 from ._utils import primitive_value_to_str20 21 27-class PlainByteStream:28- """29- Request content encoded as plain bytes.30- """22+class ByteStream(AsyncByteStream, SyncByteStream):23+ def __init__(self, stream: bytes) -> None:24+ self._stream = stream25 32- def __init__(self, body: bytes) -> None:33- self._body = body34-26 def __iter__(self) -> Iterator[bytes]:36- yield self._body27+ yield self._stream28 29 async def __aiter__(self) -> AsyncIterator[bytes]:39- yield self._body30+ yield self._stream31 32 42-class GeneratorStream:43- """44- Request content encoded as plain bytes, using an byte generator.45- """46-47- def __init__(self, generator: Iterable[bytes]) -> None:48- self._generator = generator33+class IteratorByteStream(SyncByteStream):34+ def __init__(self, stream: Iterable[bytes]):35+ self._stream = stream36 self._is_stream_consumed = False37+ self._is_generator = inspect.isgenerator(stream)38 39 def __iter__(self) -> Iterator[bytes]:52- if self._is_stream_consumed:40+ if self._is_stream_consumed and self._is_generator:41 raise StreamConsumed()42 43 self._is_stream_consumed = True56- for part in self._generator:44+ for part in self._stream:45 yield part46 47 60-class AsyncGeneratorStream:61- """62- Request content encoded as plain bytes, using an async byte iterator.63- """64-65- def __init__(self, agenerator: AsyncIterable[bytes]) -> None:66- self._agenerator = agenerator48+class AsyncIteratorByteStream(AsyncByteStream):49+ def __init__(self, stream: AsyncIterable[bytes]):50+ self._stream = stream51 self._is_stream_consumed = False52+ self._is_generator = inspect.isasyncgen(stream)53 54 async def __aiter__(self) -> AsyncIterator[bytes]:70- if self._is_stream_consumed:55+ if self._is_stream_consumed and self._is_generator:56 raise StreamConsumed()57 58 self._is_stream_consumed = True74- async for part in self._agenerator:59+ async for part in self._stream:60 yield part61 62 63 def encode_content(79- content: Union[str, bytes, ByteStream]80-) -> Tuple[Dict[str, str], ByteStream]:81- if isinstance(content, (str, bytes)):64+ content: Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]65+) -> Tuple[Dict[str, str], Union[SyncByteStream, AsyncByteStream]]:66+67+ if isinstance(content, (bytes, str)):68 body = content.encode("utf-8") if isinstance(content, str) else content69 content_length = str(len(body))70 headers = {"Content-Length": content_length} if body else {}85- stream = PlainByteStream(body)86- return headers, stream71+ return headers, ByteStream(body)72 88- elif isinstance(content, (Iterable, AsyncIterable)):73+ elif isinstance(content, Iterable):74 headers = {"Transfer-Encoding": "chunked"}75+ return headers, IteratorByteStream(content) # type: ignore76 91- # Generators should be wrapped in GeneratorStream/AsyncGeneratorStream92- # which will raise `StreamConsumed` if the stream is accessed more93- # than once. (Eg. Following HTTP 307 or HTTP 308 redirects.)94- if inspect.isgenerator(content):95- generator_stream = GeneratorStream(content) # type: ignore96- return headers, generator_stream97- if inspect.isasyncgen(content):98- agenerator_stream = AsyncGeneratorStream(content) # type: ignore99- return headers, agenerator_stream77+ elif isinstance(content, AsyncIterable):78+ headers = {"Transfer-Encoding": "chunked"}79+ return headers, AsyncIteratorByteStream(content)80 101- # Other iterables may be passed through as-is.102- return headers, content # type: ignore103-81 raise TypeError(f"Unexpected type for 'content', {type(content)!r}")82 83 84 def encode_urlencoded_data(8 unmodified lines93 body = urlencode(plain_data, doseq=True).encode("utf-8")94 content_length = str(len(body))95 content_type = "application/x-www-form-urlencoded"96 headers = {"Content-Length": content_length, "Content-Type": content_type}120- return headers, PlainByteStream(body)97+ return headers, ByteStream(body)98 99 100 def encode_multipart_data(101 data: dict, files: RequestFiles, boundary: bytes = None125-) -> Tuple[Dict[str, str], ByteStream]:126- stream = MultipartStream(data=data, files=files, boundary=boundary)127- headers = stream.get_headers()128- return headers, stream102+) -> Tuple[Dict[str, str], MultipartStream]:103+ multipart = MultipartStream(data=data, files=files, boundary=boundary)104+ headers = multipart.get_headers()105+ return headers, multipart106 107 108 def encode_text(text: str) -> Tuple[Dict[str, str], ByteStream]:109 body = text.encode("utf-8")110 content_length = str(len(body))111 content_type = "text/plain; charset=utf-8"112 headers = {"Content-Length": content_length, "Content-Type": content_type}136- return headers, PlainByteStream(body)113+ return headers, ByteStream(body)114 115 116 def encode_html(html: str) -> Tuple[Dict[str, str], ByteStream]:117 body = html.encode("utf-8")118 content_length = str(len(body))119 content_type = "text/html; charset=utf-8"120 headers = {"Content-Length": content_length, "Content-Type": content_type}144- return headers, PlainByteStream(body)121+ return headers, ByteStream(body)122 123 124 def encode_json(json: Any) -> Tuple[Dict[str, str], ByteStream]:125 body = json_dumps(json).encode("utf-8")126 content_length = str(len(body))127 content_type = "application/json"128 headers = {"Content-Length": content_length, "Content-Type": content_type}152- return headers, PlainByteStream(body)129+ return headers, ByteStream(body)130 131 132 def encode_request(133 content: RequestContent = None,134 data: RequestData = None,135 files: RequestFiles = None,136 json: Any = None,137 boundary: bytes = None,161-) -> Tuple[Dict[str, str], ByteStream]:138+) -> Tuple[Dict[str, str], Union[SyncByteStream, AsyncByteStream]]:139 """140 Handles encoding the given `content`, `data`, `files`, and `json`,141 returning a two-tuple of (<headers>, <stream>).142 """15 unmodified lines158 return encode_urlencoded_data(data)159 elif json is not None:160 return encode_json(json)161 185- return {}, PlainByteStream(b"")162+ return {}, ByteStream(b"")163 164 165 def encode_response(166 content: ResponseContent = None,167 text: str = None,168 html: str = None,169 json: Any = None,193-) -> Tuple[Dict[str, str], ByteStream]:170+) -> Tuple[Dict[str, str], Union[SyncByteStream, AsyncByteStream]]:171 """172 Handles encoding the given `content`, returning a two-tuple of173 (<headers>, <stream>).174 """5 unmodified lines180 return encode_html(html)181 elif json is not None:182 return encode_json(json)183 207- return {}, PlainByteStream(b"")184+ return {}, ByteStream(b"")modified:httpx/_models.py+9 added-9 removed
9 unmodified lines10 11 import rfc398612 import rfc3986.exceptions13 14-from ._content import PlainByteStream, encode_request, encode_response14+from ._content import ByteStream, encode_request, encode_response15 from ._decoders import (16 SUPPORTED_DECODERS,17 ByteChunker,18 ContentDecoder,13 unmodified lines32 StreamConsumed,33 request_context,34 )35 from ._status_codes import codes36+from ._transports.base import AsyncByteStream, SyncByteStream37 from ._types import (37- ByteStream,38 CookieTypes,39 HeaderTypes,40 PrimitiveData,41 QueryParamTypes,755 unmodified lines797 content: RequestContent = None,798 data: RequestData = None,799 files: RequestFiles = None,800 json: typing.Any = None,801- stream: ByteStream = None,801+ stream: typing.Union[SyncByteStream, AsyncByteStream] = None,802 ):803 if isinstance(method, bytes):804 self.method = method.decode("ascii").upper()805 else:65 unmodified lines871 self._content = b"".join(self.stream)872 # If a streaming request has been read entirely into memory, then873 # we can replace the stream with a raw bytes implementation,874 # to ensure that any non-replayable streams can still be used.875- self.stream = PlainByteStream(self._content)875+ self.stream = ByteStream(self._content)876 return self._content877 878 async def aread(self) -> bytes:879 """4 unmodified lines884 self._content = b"".join([part async for part in self.stream])885 # If a streaming request has been read entirely into memory, then886 # we can replace the stream with a raw bytes implementation,887 # to ensure that any non-replayable streams can still be used.888- self.stream = PlainByteStream(self._content)888+ self.stream = ByteStream(self._content)889 return self._content890 891 def __repr__(self) -> str:892 class_name = self.__class__.__name__10 unmodified lines903 content: ResponseContent = None,904 text: str = None,905 html: str = None,906 json: typing.Any = None,907- stream: ByteStream = None,907+ stream: typing.Union[SyncByteStream, AsyncByteStream] = None,908 request: Request = None,909 extensions: dict = None,910 history: typing.List["Response"] = None,911 on_close: typing.Callable = None,309 unmodified lines1221 if self.is_stream_consumed:1222 raise StreamConsumed()1223 if self.is_closed:1224 raise ResponseClosed()1225- if not isinstance(self.stream, typing.Iterable):1225+ if not isinstance(self.stream, SyncByteStream):1226 raise RuntimeError("Attempted to call a sync iterator on an async stream.")1227 1228 self.is_stream_consumed = True1229 self._num_bytes_downloaded = 087 unmodified lines1317 if self.is_stream_consumed:1318 raise StreamConsumed()1319 if self.is_closed:1320 raise ResponseClosed()1321- if not isinstance(self.stream, typing.AsyncIterable):1322- raise RuntimeError("Attempted to call a async iterator on a sync stream.")1321+ if not isinstance(self.stream, AsyncByteStream):1322+ raise RuntimeError("Attempted to call an async iterator on an sync stream.")1323 1324 self.is_stream_consumed = True1325 self._num_bytes_downloaded = 01326 chunker = ByteChunker(chunk_size=chunk_size)213 unmodified linesmodified:httpx/_multipart.py+2 added-1 removed
1 unmodified line2 import os3 import typing4 from pathlib import Path5 6+from ._transports.base import AsyncByteStream, SyncByteStream7 from ._types import FileContent, FileTypes, RequestFiles8 from ._utils import (9 format_form_param,10 guess_content_type,130 unmodified lines141 yield self.render_headers()142 yield from self.render_data()143 144 144-class MultipartStream:145+class MultipartStream(SyncByteStream, AsyncByteStream):146 """147 Request content as streaming multipart encoded form data.148 """149 57 unmodified linesmodified:httpx/_types.py+2 added-3 removed
72 unmodified lines73 "Auth",74 None,75 ]76 77-ByteStream = Union[Iterable[bytes], AsyncIterable[bytes]]78-RequestContent = Union[str, bytes, ByteStream]79-ResponseContent = Union[str, bytes, ByteStream]77+RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]78+ResponseContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]79 80 RequestData = dict81 82 FileContent = Union[IO[str], IO[bytes], str, bytes]9 unmodified linesmodified:tests/test_content.py+9 added-9 removed
1 unmodified line2 import typing3 4 import pytest5 6-from httpx import StreamConsumed6+import httpx7 from httpx._content import encode_request, encode_response8 9 10 @pytest.mark.asyncio11 async def test_empty_content():12 headers, stream = encode_request()13- assert isinstance(stream, typing.Iterable)14- assert isinstance(stream, typing.AsyncIterable)13+ assert isinstance(stream, httpx.SyncByteStream)14+ assert isinstance(stream, httpx.AsyncByteStream)15 16- sync_content = b"".join([part for part in stream])17- async_content = b"".join([part async for part in stream])16+ sync_content = stream.read()17+ async_content = await stream.aread()18 19 assert headers == {}20 assert sync_content == b""21 assert async_content == b""39 unmodified lines61 62 assert headers == {"Transfer-Encoding": "chunked"}63 assert content == b"Hello, world!"64 65- with pytest.raises(StreamConsumed):65+ with pytest.raises(httpx.StreamConsumed):66 [part for part in stream]67 68 # Support 'data' for compat with requests.69 headers, stream = encode_request(data=hello_world()) # type: ignore20 unmodified lines90 91 assert headers == {"Transfer-Encoding": "chunked"}92 assert content == b"Hello, world!"93 94- with pytest.raises(StreamConsumed):94+ with pytest.raises(httpx.StreamConsumed):95 [part async for part in stream]96 97 # Support 'data' for compat with requests.98 headers, stream = encode_request(data=hello_world()) # type: ignore282 unmodified lines381 382 assert headers == {"Transfer-Encoding": "chunked"}383 assert content == b"Hello, world!"384 385- with pytest.raises(StreamConsumed):385+ with pytest.raises(httpx.StreamConsumed):386 [part for part in stream]387 388 389 @pytest.mark.asyncio10 unmodified lines400 401 assert headers == {"Transfer-Encoding": "chunked"}402 assert content == b"Hello, world!"403 404- with pytest.raises(StreamConsumed):404+ with pytest.raises(httpx.StreamConsumed):405 [part async for part in stream]406 407 408 def test_response_invalid_argument():2 unmodified lines