Skip to content
Myr

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

13 files+221 added−155 removed

modified:docs/advanced.md+2 added-2 removed
1068 unmodified lines
10691070 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 lines
1130 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 lines
modified:httpx/_transports/asgi.py+13 added-7 removed
1 unmodified line
2from urllib.parse import unquote34import sniffio56from .base import AsyncBaseTransport6from .base import AsyncBaseTransport, AsyncByteStream78if typing.TYPE_CHECKING: # pragma: no cover9 import asyncio10
12 unmodified lines
2324 return asyncio.Event()252627class ASGIResponseStream(AsyncByteStream):28 def __init__(self, body: typing.List[bytes]) -> None:29 self._body = body3031 async def __aiter__(self) -> typing.AsyncIterator[bytes]:32 yield b"".join(self._body)333435class 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 lines
81 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 lines
162 assert response_complete.is_set()163 assert status_code is not None164 assert response_headers is not None165158 async def response_stream() -> typing.AsyncIterator[bytes]:159 yield b"".join(body_parts)160166 stream = ASGIResponseStream(body_parts)167 extensions = {}168163 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 lines
4T = typing.TypeVar("T", bound="BaseTransport")5A = typing.TypeVar("A", bound="AsyncBaseTransport")678class SyncByteStream:9 def __iter__(self) -> typing.Iterator[bytes]:10 raise NotImplementedError(11 "The '__iter__' method must be implemented."12 ) # pragma: nocover13 yield b"" # pragma: nocover1415 def close(self) -> None:16 """17 Subclasses can override this method to release any network resources18 after a request/response cycle is complete.1920 Streaming cases should use a `try...finally` block to ensure that21 the stream `close()` method is always called.2223 Example:2425 status_code, headers, stream, extensions = transport.handle_request(...)26 try:27 ...28 finally:29 stream.close()30 """3132 def read(self) -> bytes:33 """34 Simple cases can use `.read()` as a convience method for consuming35 the entire stream and then closing it.3637 Example:3839 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()464748class 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: nocover5455 async def aclose(self) -> None:56 pass5758 async def aread(self) -> bytes:59 try:60 return b"".join([part async for part in self])61 finally:62 await self.aclose()636465class BaseTransport:66 def __enter__(self: T) -> T:67 return self68
9 unmodified lines
78 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 lines
95 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.9899 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.103104 Example usage:105106 with httpx.HTTPTransport() as transport:107 status_code, headers, stream, extensions = transport.handle_request(
2 unmodified lines
110 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)116117 Arguments:118
24 unmodified lines
143 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: nocover
18 unmodified lines
169 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: nocover
3 unmodified lines
modified:httpx/_transports/default.py+37 added-27 removed
47 unmodified lines
48 WriteError,49 WriteTimeout,50)51from .._types import CertTypes, VerifyTypes52from .base import AsyncBaseTransport, BaseTransport52from .base import AsyncBaseTransport, AsyncByteStream, BaseTransport, SyncByteStream5354T = typing.TypeVar("T", bound="HTTPTransport")55A = typing.TypeVar("A", bound="AsyncHTTPTransport")56
52 unmodified lines
109 httpcore.RemoteProtocolError: RemoteProtocolError,110}111112113class ResponseStream(SyncByteStream):114 def __init__(self, httpcore_stream: httpcore.SyncByteStream):115 self._httpcore_stream = httpcore_stream116117 def __iter__(self) -> typing.Iterator[bytes]:118 with map_httpcore_exceptions():119 for part in self._httpcore_stream:120 yield part121122 def close(self) -> None:123 with map_httpcore_exceptions():124 self._httpcore_stream.close()125126127class HTTPTransport(BaseTransport):128 def __init__(129 self,130 verify: VerifyTypes = True,
50 unmodified lines
181 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 lines
195 stream=httpcore.IteratorByteStream(iter(stream)),196 ext=extensions,197 )198185 def response_stream() -> typing.Iterator[bytes]:186 with map_httpcore_exceptions():187 for part in byte_stream:188 yield part189190 def close() -> None:191 with map_httpcore_exceptions():192 byte_stream.close()193199 ensure_http_version_reason_phrase_as_bytes(extensions)195 extensions["close"] = close200 stream = ResponseStream(byte_stream)201197 return status_code, headers, response_stream(), extensions202 return status_code, headers, stream, extensions203204 def close(self) -> None:205 self._pool.close()206207208class AsyncResponseStream(AsyncByteStream):209 def __init__(self, httpcore_stream: httpcore.AsyncByteStream):210 self._httpcore_stream = httpcore_stream211212 async def __aiter__(self) -> typing.AsyncIterator[bytes]:213 with map_httpcore_exceptions():214 async for part in self._httpcore_stream:215 yield part216217 async def aclose(self) -> None:218 with map_httpcore_exceptions():219 await self._httpcore_stream.aclose()220221222class AsyncHTTPTransport(AsyncBaseTransport):223 def __init__(224 self,225 verify: VerifyTypes = True,
50 unmodified lines
276 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 lines
290 stream=httpcore.AsyncIteratorByteStream(stream.__aiter__()),291 ext=extensions,292 )293275 async def response_stream() -> typing.AsyncIterator[bytes]:276 with map_httpcore_exceptions():277 async for part in byte_stream:278 yield part279280 async def aclose() -> None:281 with map_httpcore_exceptions():282 await byte_stream.aclose()283294 ensure_http_version_reason_phrase_as_bytes(extensions)285 extensions["aclose"] = aclose295 stream = AsyncResponseStream(byte_stream)296287 return status_code, headers, response_stream(), extensions297 return status_code, headers, stream, extensions298299 async def aclose(self) -> None:300 await self._pool.aclose()
modified:httpx/_transports/mock.py+5 added-5 removed
1import asyncio2import typing34from .._models import Request5from .base import AsyncBaseTransport, BaseTransport5from .base import AsyncBaseTransport, AsyncByteStream, BaseTransport, SyncByteStream678class MockTransport(AsyncBaseTransport, BaseTransport):9 def __init__(self, handler: typing.Callable) -> None:
3 unmodified lines
13 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 lines
38 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 lines
modified:httpx/_transports/wsgi.py+15 added-7 removed
1 unmodified line
2import itertools3import typing4from urllib.parse import unquote56from .base import BaseTransport6from .base import BaseTransport, SyncByteStream789def _skip_leading_empty_chunks(body: typing.Iterable) -> typing.Iterable:10 body = iter(body)
2 unmodified lines
13 return itertools.chain([chunk], body)14 return []151617class WSGIByteStream(SyncByteStream):18 def __init__(self, result: typing.Iterable[bytes]) -> None:19 self._result = _skip_leading_empty_chunks(result)2021 def __iter__(self) -> typing.Iterator[bytes]:22 for part in self._result:23 yield part242526class 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 lines
72 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))8283 scheme, host, port, full_path = url
35 unmodified lines
119 seen_response_headers = response_headers120 seen_exc_info = exc_info121122 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)123124 stream = WSGIByteStream(result)125126 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 lines
134 for key, value in seen_response_headers135 ]136 extensions = {}137130 return (status_code, headers, result, extensions)138 return (status_code, headers, stream, extensions)
modified:httpx/__init__.py+10 added-1 removed
1 unmodified line
2from ._api import delete, get, head, options, patch, post, put, request, stream3from ._auth import Auth, BasicAuth, DigestAuth4from ._client import AsyncClient, Client5from ._config import Limits, Proxy, Timeout, create_ssl_context6from ._content import ByteStream7from ._exceptions import (8 CloseError,9 ConnectError,10 ConnectTimeout,
25 unmodified lines
36)37from ._models import URL, Cookies, Headers, QueryParams, Request, Response38from ._status_codes import StatusCode, codes39from ._transports.asgi import ASGITransport39from ._transports.base import AsyncBaseTransport, BaseTransport40from ._transports.base import (41 AsyncBaseTransport,42 AsyncByteStream,43 BaseTransport,44 SyncByteStream,45)46from ._transports.default import AsyncHTTPTransport, HTTPTransport47from ._transports.mock import MockTransport48from ._transports.wsgi import WSGITransport49
2 unmodified lines
52 "__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 lines
104 "StatusCode",105 "stream",106 "StreamConsumed",107 "StreamError",108 "SyncByteStream",109 "Timeout",110 "TimeoutException",111 "TooManyRedirects",112 "TransportError",
12 unmodified lines
modified:httpx/_client.py+9 added-7 removed
24 unmodified lines
25)26from ._models import URL, Cookies, Headers, QueryParams, Request, Response27from ._status_codes import codes28from ._transports.asgi import ASGITransport29from ._transports.base import AsyncBaseTransport, BaseTransport29from ._transports.base import (30 AsyncBaseTransport,31 AsyncByteStream,32 BaseTransport,33 SyncByteStream,34)35from ._transports.default import AsyncHTTPTransport, HTTPTransport36from ._transports.wsgi import WSGITransport37from ._types import (38 AuthTypes,34 ByteStream,39 CertTypes,40 CookieTypes,41 HeaderTypes,42 ProxiesTypes,
469 unmodified lines
512 return headers513514 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 lines
883 )884885 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()888889 response = Response(890 status_code,891 headers=headers,
634 unmodified lines
1526 )15271528 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()15311532 response = Response(1533 status_code,1534 headers=headers,
349 unmodified lines
modified:httpx/_content.py+41 added-64 removed
12 unmodified lines
13from urllib.parse import urlencode1415from ._exceptions import StreamConsumed16from ._multipart import MultipartStream17from ._types import (18 ByteStream,19 RequestContent,20 RequestData,21 RequestFiles,22 ResponseContent,23)17from ._transports.base import AsyncByteStream, SyncByteStream18from ._types import RequestContent, RequestData, RequestFiles, ResponseContent19from ._utils import primitive_value_to_str202127class PlainByteStream:28 """29 Request content encoded as plain bytes.30 """22class ByteStream(AsyncByteStream, SyncByteStream):23 def __init__(self, stream: bytes) -> None:24 self._stream = stream2532 def __init__(self, body: bytes) -> None:33 self._body = body3426 def __iter__(self) -> Iterator[bytes]:36 yield self._body27 yield self._stream2829 async def __aiter__(self) -> AsyncIterator[bytes]:39 yield self._body30 yield self._stream313242class GeneratorStream:43 """44 Request content encoded as plain bytes, using an byte generator.45 """4647 def __init__(self, generator: Iterable[bytes]) -> None:48 self._generator = generator33class IteratorByteStream(SyncByteStream):34 def __init__(self, stream: Iterable[bytes]):35 self._stream = stream36 self._is_stream_consumed = False37 self._is_generator = inspect.isgenerator(stream)3839 def __iter__(self) -> Iterator[bytes]:52 if self._is_stream_consumed:40 if self._is_stream_consumed and self._is_generator:41 raise StreamConsumed()4243 self._is_stream_consumed = True56 for part in self._generator:44 for part in self._stream:45 yield part464760class AsyncGeneratorStream:61 """62 Request content encoded as plain bytes, using an async byte iterator.63 """6465 def __init__(self, agenerator: AsyncIterable[bytes]) -> None:66 self._agenerator = agenerator48class AsyncIteratorByteStream(AsyncByteStream):49 def __init__(self, stream: AsyncIterable[bytes]):50 self._stream = stream51 self._is_stream_consumed = False52 self._is_generator = inspect.isasyncgen(stream)5354 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()5758 self._is_stream_consumed = True74 async for part in self._agenerator:59 async for part in self._stream:60 yield part616263def 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]]:6667 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)7288 elif isinstance(content, (Iterable, AsyncIterable)):73 elif isinstance(content, Iterable):74 headers = {"Transfer-Encoding": "chunked"}75 return headers, IteratorByteStream(content) # type: ignore7691 # 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)80101 # Other iterables may be passed through as-is.102 return headers, content # type: ignore10381 raise TypeError(f"Unexpected type for 'content', {type(content)!r}")828384def encode_urlencoded_data(
8 unmodified lines
93 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)9899100def 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, multipart106107108def 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)114115116def 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)122123124def 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)130131132def 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 lines
158 return encode_urlencoded_data(data)159 elif json is not None:160 return encode_json(json)161185 return {}, PlainByteStream(b"")162 return {}, ByteStream(b"")163164165def 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 lines
180 return encode_html(html)181 elif json is not None:182 return encode_json(json)183207 return {}, PlainByteStream(b"")184 return {}, ByteStream(b"")
modified:httpx/_models.py+9 added-9 removed
9 unmodified lines
1011import rfc398612import rfc3986.exceptions1314from ._content import PlainByteStream, encode_request, encode_response14from ._content import ByteStream, encode_request, encode_response15from ._decoders import (16 SUPPORTED_DECODERS,17 ByteChunker,18 ContentDecoder,
13 unmodified lines
32 StreamConsumed,33 request_context,34)35from ._status_codes import codes36from ._transports.base import AsyncByteStream, SyncByteStream37from ._types import (37 ByteStream,38 CookieTypes,39 HeaderTypes,40 PrimitiveData,41 QueryParamTypes,
755 unmodified lines
797 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 lines
871 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._content877878 async def aread(self) -> bytes:879 """
4 unmodified lines
884 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._content890891 def __repr__(self) -> str:892 class_name = self.__class__.__name__
10 unmodified lines
903 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 lines
1221 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.")12271228 self.is_stream_consumed = True1229 self._num_bytes_downloaded = 0
87 unmodified lines
1317 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.")13231324 self.is_stream_consumed = True1325 self._num_bytes_downloaded = 01326 chunker = ByteChunker(chunk_size=chunk_size)
213 unmodified lines
modified:httpx/_multipart.py+2 added-1 removed
1 unmodified line
2import os3import typing4from pathlib import Path56from ._transports.base import AsyncByteStream, SyncByteStream7from ._types import FileContent, FileTypes, RequestFiles8from ._utils import (9 format_form_param,10 guess_content_type,
130 unmodified lines
141 yield self.render_headers()142 yield from self.render_data()143144144class MultipartStream:145class MultipartStream(SyncByteStream, AsyncByteStream):146 """147 Request content as streaming multipart encoded form data.148 """149
57 unmodified lines
modified:httpx/_types.py+2 added-3 removed
72 unmodified lines
73 "Auth",74 None,75]7677ByteStream = Union[Iterable[bytes], AsyncIterable[bytes]]78RequestContent = Union[str, bytes, ByteStream]79ResponseContent = Union[str, bytes, ByteStream]77RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]78ResponseContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]7980RequestData = dict8182FileContent = Union[IO[str], IO[bytes], str, bytes]
9 unmodified lines
modified:tests/test_content.py+9 added-9 removed
1 unmodified line
2import typing34import pytest56from httpx import StreamConsumed6import httpx7from httpx._content import encode_request, encode_response8910@pytest.mark.asyncio11async 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)1516 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()1819 assert headers == {}20 assert sync_content == b""21 assert async_content == b""
39 unmodified lines
6162 assert headers == {"Transfer-Encoding": "chunked"}63 assert content == b"Hello, world!"6465 with pytest.raises(StreamConsumed):65 with pytest.raises(httpx.StreamConsumed):66 [part for part in stream]6768 # Support 'data' for compat with requests.69 headers, stream = encode_request(data=hello_world()) # type: ignore
20 unmodified lines
9091 assert headers == {"Transfer-Encoding": "chunked"}92 assert content == b"Hello, world!"9394 with pytest.raises(StreamConsumed):94 with pytest.raises(httpx.StreamConsumed):95 [part async for part in stream]9697 # Support 'data' for compat with requests.98 headers, stream = encode_request(data=hello_world()) # type: ignore
282 unmodified lines
381382 assert headers == {"Transfer-Encoding": "chunked"}383 assert content == b"Hello, world!"384385 with pytest.raises(StreamConsumed):385 with pytest.raises(httpx.StreamConsumed):386 [part for part in stream]387388389@pytest.mark.asyncio
10 unmodified lines
400401 assert headers == {"Transfer-Encoding": "chunked"}402 assert content == b"Hello, world!"403404 with pytest.raises(StreamConsumed):404 with pytest.raises(httpx.StreamConsumed):405 [part async for part in stream]406407408def test_response_invalid_argument():
2 unmodified lines