Drop ContentStream (#1295)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Drop ContentStream
authored by Tom Christie · committed by GitHub · parent e1f7791 · Browse files · 15 files·+416 added−311 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+416 added−311 removed
- tests:+244 added−143 removed
- other:+172 added−168 removed
Provenance
- Commit
fbb21fb- Tree
5df7b20- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
e1f7791
15 files changed+416 added−311 removed
modified:docs/exceptions.md-4 removed
72 unmodified lines73747576777778798066 unmodified lines14714814915015215315415115215315422 unmodified lines72 unmodified lines * ProxyError * UnsupportedProtocol * DecodingError * TooManyRedirects * RequestBodyUnavailable * HTTPStatusError* InvalidURL* NotRedirectResponse* CookieConflict66 unmodified lines
::: httpx.TooManyRedirects :docstring:
::: httpx.RequestBodyUnavailable :docstring:
::: httpx.HTTPStatusError :docstring:
::: httpx.InvalidURL22 unmodified linesmodified:httpx/__init__.py-2 removed
19 unmodified lines20 ProxyError,21 ReadError,22 ReadTimeout,23 RemoteProtocolError,24- RequestBodyUnavailable,24 RequestError,25 RequestNotRead,26 ResponseClosed,27 ResponseNotRead,54 unmodified lines82 "ReadTimeout",83 "RemoteProtocolError",84 "request",85 "Request",87- "RequestBodyUnavailable",86 "RequestError",87 "RequestNotRead",88 "Response",89 "ResponseClosed",21 unmodified linesmodified:httpx/_auth.py+1 added-8 removed
4 unmodified lines5 import typing6 from base64 import b64encode7 from urllib.request import parse_http_list8 9-from ._exceptions import ProtocolError, RequestBodyUnavailable9+from ._exceptions import ProtocolError10 from ._models import Request, Response11 from ._utils import to_bytes, to_str, unquote12 13 142 unmodified lines156 self._username = to_bytes(username)157 self._password = to_bytes(password)158 159 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:160- if not request.stream.can_replay():161- raise RequestBodyUnavailable(162- "Cannot use digest auth with streaming requests that are unable "163- "to replay the request body if a second request is required.",164- request=request,165- )166-160 response = yield request161 162 if response.status_code != 401 or "www-authenticate" not in response.headers:163 # If the response is not a 401 then we don't149 unmodified linesmodified:httpx/_client.py+19 added-14 removed
1+import datetime2 import functools3 import typing4 import warnings5 from types import TracebackType12 unmodified lines18 Timeout,19 UnsetType,20 create_ssl_context,21 )21-from ._content_streams import ContentStream22 from ._decoders import SUPPORTED_DECODERS23 from ._exceptions import (24 HTTPCORE_EXC_MAP,25 InvalidURL,26 RemoteProtocolError,27- RequestBodyUnavailable,27 TooManyRedirects,28 map_exceptions,29 )30 from ._models import URL, Cookies, Headers, QueryParams, Request, Response1 unmodified line32 from ._transports.asgi import ASGITransport33 from ._transports.wsgi import WSGITransport34 from ._types import (35 AuthTypes,36+ ByteStream,37 CertTypes,38 CookieTypes,39 HeaderTypes,40 ProxiesTypes,438 unmodified lines479 return headers480 481 def _redirect_stream(482 self, request: Request, method: str483- ) -> typing.Optional[ContentStream]:483+ ) -> typing.Optional[ByteStream]:484 """485 Return the body that should be used for the redirect request.486 """487 if method != request.method and method == "GET":488 return None489 490- if not request.stream.can_replay():491- raise RequestBodyUnavailable(492- "Got a redirect response, but the request body was streaming "493- "and is no longer available.",494- request=request,495- )496-490 return request.stream491 492 493 class Client(BaseClient):362 unmodified lines856 ) = transport.request(857 request.method.encode(),858 request.url.raw,859 headers=request.headers.raw,867- stream=request.stream,860+ stream=request.stream, # type: ignore861 timeout=timeout.as_dict(),862 )863+864+ def on_close(response: Response) -> None:865+ response.elapsed = datetime.timedelta(timer.sync_elapsed())866+ if hasattr(stream, "close"):867+ stream.close()868+869 response = Response(870 status_code,871 http_version=http_version.decode("ascii"),872 headers=headers,873 stream=stream, # type: ignore874 request=request,876- elapsed_func=timer.sync_elapsed,875+ on_close=on_close,876 )877 878 self.cookies.extract_cookies(response)879 627 unmodified lines1507 ) = await transport.request(1508 request.method.encode(),1509 request.url.raw,1510 headers=request.headers.raw,1512- stream=request.stream,1511+ stream=request.stream, # type: ignore1512 timeout=timeout.as_dict(),1513 )1514+1515+ async def on_close(response: Response) -> None:1516+ response.elapsed = datetime.timedelta(await timer.async_elapsed())1517+ if hasattr(stream, "close"):1518+ await stream.aclose()1519+1520 response = Response(1521 status_code,1522 http_version=http_version.decode("ascii"),1523 headers=headers,1524 stream=stream, # type: ignore1525 request=request,1521- elapsed_func=timer.async_elapsed,1526+ on_close=on_close,1527 )1528 1529 self.cookies.extract_cookies(response)1530 320 unmodified linesmodified:httpx/_content_streams.py+73 added-103 removed
1 import binascii2+import inspect3 import os4 import typing5 from json import dumps as json_dumps6 from pathlib import Path7 from urllib.parse import urlencode8 8-import httpcore9-9 from ._exceptions import StreamConsumed10 from ._types import (11+ ByteStream,12 FileContent,13 FileTypes,14 RequestContent,15 RequestData,7 unmodified lines23 to_bytes,24 )25 26 27-class ContentStream(httpcore.AsyncByteStream, httpcore.SyncByteStream):28- def get_headers(self) -> typing.Dict[str, str]:29- """30- Return a dictionary of headers that are implied by the encoding.31- """32- return {}33-34- def can_replay(self) -> bool:35- """36- Return `True` if `__aiter__` can be called multiple times.37-38- We need this in cases such determining if we can re-issue a request39- body when we receive a redirect response.40- """41- return True42-43- def __iter__(self) -> typing.Iterator[bytes]:44- yield b""45-46- def close(self) -> None:47- pass48-49- async def __aiter__(self) -> typing.AsyncIterator[bytes]:50- yield b""51-52- async def aclose(self) -> None:53- pass54-55-56-class ByteStream(ContentStream):27+class PlainByteStream:28 """29 Request content encoded as plain bytes.30 """31 12 unmodified lines44 async def __aiter__(self) -> typing.AsyncIterator[bytes]:45 yield self.body46 47 77-class IteratorStream(ContentStream):48+class GeneratorStream:49 """79- Request content encoded as plain bytes, using an byte iterator.50+ Request content encoded as plain bytes, using an byte generator.51 """52 82- def __init__(self, iterator: typing.Iterator[bytes]) -> None:83- self.iterator = iterator84- self.is_stream_consumed = False53+ def __init__(self, generator: typing.Iterable[bytes]) -> None:54+ self._generator = generator55+ self._is_stream_consumed = False56 86- def can_replay(self) -> bool:87- return False88-89- def get_headers(self) -> typing.Dict[str, str]:90- return {"Transfer-Encoding": "chunked"}91-57 def __iter__(self) -> typing.Iterator[bytes]:93- if self.is_stream_consumed:58+ if self._is_stream_consumed:59 raise StreamConsumed()95- self.is_stream_consumed = True96- for part in self.iterator:60+ self._is_stream_consumed = True61+ for part in self._generator:62 yield part63 99- def __aiter__(self) -> typing.AsyncIterator[bytes]:100- raise RuntimeError("Attempted to call a async iterator on an sync stream.")64 102-103-class AsyncIteratorStream(ContentStream):65+class AsyncGeneratorStream:66 """67 Request content encoded as plain bytes, using an async byte iterator.68 """69 108- def __init__(self, aiterator: typing.AsyncIterator[bytes]) -> None:109- self.aiterator = aiterator110- self.is_stream_consumed = False70+ def __init__(self, agenerator: typing.AsyncIterable[bytes]) -> None:71+ self._agenerator = agenerator72+ self._is_stream_consumed = False73 112- def can_replay(self) -> bool:113- return False114-115- def get_headers(self) -> typing.Dict[str, str]:116- return {"Transfer-Encoding": "chunked"}117-118- def __iter__(self) -> typing.Iterator[bytes]:119- raise RuntimeError("Attempted to call a sync iterator on an async stream.")120-74 async def __aiter__(self) -> typing.AsyncIterator[bytes]:122- if self.is_stream_consumed:75+ if self._is_stream_consumed:76 raise StreamConsumed()124- self.is_stream_consumed = True125- async for part in self.aiterator:77+ self._is_stream_consumed = True78+ async for part in self._agenerator:79 yield part80 81 129-class JSONStream(ContentStream):82+class JSONStream:83 """84 Request content encoded as JSON.85 """86 11 unmodified lines98 async def __aiter__(self) -> typing.AsyncIterator[bytes]:99 yield self.body100 101 149-class URLEncodedStream(ContentStream):102+class URLEncodedStream:103 """104 Request content as URL encoded form data.105 """106 11 unmodified lines118 async def __aiter__(self) -> typing.AsyncIterator[bytes]:119 yield self.body120 121 169-class MultipartStream(ContentStream):122+class MultipartStream:123 """124 Request content as streaming multipart encoded form data.125 """126 33 unmodified lines160 headers = self.render_headers()161 data = self.render_data()162 return len(headers) + len(data)163 211- def can_replay(self) -> bool:212- return True213-164 def render(self) -> typing.Iterator[bytes]:165 yield self.render_headers()166 yield self.render_data()167 20 unmodified lines188 189 self.filename = filename190 self.file = fileobj191 self.content_type = content_type192+ self._consumed = False193 194 def get_length(self) -> int:195 headers = self.render_headers()196 37 unmodified lines234 # Already rendered.235 yield self._data236 return237 238+ if self._consumed: # pragma: nocover239+ self.file.seek(0)240+ self._consumed = True241+242 for chunk in self.file:243 yield to_bytes(chunk)244 290- # Get ready for the next replay, if possible.291- if self.can_replay():292- assert self.file.seekable()293- self.file.seek(0)294-295- def can_replay(self) -> bool:296- return True if isinstance(self.file, (str, bytes)) else self.file.seekable()297-245 def render(self) -> typing.Iterator[bytes]:246 yield self.render_headers()247 yield from self.render_data()248 43 unmodified lines292 return sum(self.iter_chunks_lengths())293 294 # Content stream interface.295 349- def can_replay(self) -> bool:350- return all(field.can_replay() for field in self.fields)351-296 def get_headers(self) -> typing.Dict[str, str]:297 content_length = str(self.get_content_length())298 content_type = self.content_type299 return {"Content-Length": content_length, "Content-Type": content_type}12 unmodified lines312 data: RequestData = None,313 files: RequestFiles = None,314 json: typing.Any = None,315 boundary: bytes = None,372-) -> ContentStream:316+) -> typing.Tuple[typing.Dict[str, str], ByteStream]:317 """318 Handles encoding the given `content`, `data`, `files`, and `json`,375- returning a `ContentStream` implementation.319+ returning a two-tuple of (<headers>, <stream>).320 """321 if data is not None and not isinstance(data, dict):322 # We prefer to seperate `content=<bytes|byte iterator|bytes aiterator>`323 # for raw request content, and `data=<form data>` for url encoded or6 unmodified lines330 data = None331 332 if content is not None:333 if isinstance(content, (str, bytes)):390- return ByteStream(body=content)391- elif hasattr(content, "__aiter__"):392- content = typing.cast(typing.AsyncIterator[bytes], content)393- return AsyncIteratorStream(aiterator=content)394- elif hasattr(content, "__iter__"):395- content = typing.cast(typing.Iterator[bytes], content)396- return IteratorStream(iterator=content)334+ byte_stream = PlainByteStream(body=content)335+ headers = byte_stream.get_headers()336+ return headers, byte_stream337+ elif isinstance(content, (typing.Iterable, typing.AsyncIterable)):338+ if inspect.isgenerator(content):339+ generator_stream = GeneratorStream(content) # type: ignore340+ return {"Transfer-Encoding": "chunked"}, generator_stream341+ if inspect.isasyncgen(content):342+ agenerator_stream = AsyncGeneratorStream(content) # type: ignore343+ return {"Transfer-Encoding": "chunked"}, agenerator_stream344+ return {"Transfer-Encoding": "chunked"}, content # type: ignore345 else:346 raise TypeError(f"Unexpected type for 'content', {type(content)!r}")347 348 elif data:349 if files:402- return MultipartStream(data=data, files=files, boundary=boundary)350+ multipart_stream = MultipartStream(351+ data=data, files=files, boundary=boundary352+ )353+ headers = multipart_stream.get_headers()354+ return headers, multipart_stream355 else:404- return URLEncodedStream(data=data)356+ urlencoded_stream = URLEncodedStream(data=data)357+ headers = urlencoded_stream.get_headers()358+ return headers, urlencoded_stream359 360 elif files:407- return MultipartStream(data={}, files=files, boundary=boundary)361+ multipart_stream = MultipartStream(data={}, files=files, boundary=boundary)362+ headers = multipart_stream.get_headers()363+ return headers, multipart_stream364 365 elif json is not None:410- return JSONStream(json=json)366+ json_stream = JSONStream(json=json)367+ headers = json_stream.get_headers()368+ return headers, json_stream369 412- return ByteStream(body=b"")370+ byte_stream = PlainByteStream(body=b"")371+ headers = byte_stream.get_headers()372+ return headers, byte_stream373 374 415-def encode_response(content: ResponseContent = None) -> ContentStream:375+def encode_response(376+ content: ResponseContent = None,377+) -> typing.Tuple[typing.Dict[str, str], ByteStream]:378 if content is None:417- return ByteStream(b"")379+ byte_stream = PlainByteStream(b"")380+ headers = byte_stream.get_headers()381+ return headers, byte_stream382 elif isinstance(content, bytes):419- return ByteStream(body=content)420- elif isinstance(content, typing.AsyncIterator):421- return AsyncIteratorStream(aiterator=content)422- elif isinstance(content, typing.Iterator):423- return IteratorStream(iterator=content)383+ byte_stream = PlainByteStream(body=content)384+ headers = byte_stream.get_headers()385+ return headers, byte_stream386+ elif isinstance(content, (typing.Iterable, typing.AsyncIterable)):387+ if inspect.isgenerator(content):388+ generator_stream = GeneratorStream(content) # type: ignore389+ return {"Transfer-Encoding": "chunked"}, generator_stream390+ elif inspect.isasyncgen(content):391+ agenerator_stream = AsyncGeneratorStream(content) # type: ignore392+ return {"Transfer-Encoding": "chunked"}, agenerator_stream393+ return {"Transfer-Encoding": "chunked"}, content # type: ignore394 395 raise TypeError(f"Unexpected type for 'content', {type(content)!r}")modified:httpx/_exceptions.py+7 added-10 removed
205 unmodified lines206 Too many redirects.207 """208 209 210-class RequestBodyUnavailable(RequestError):211- """212- Had to send the request again, but the request body was streaming, and is213- no longer available.214- """215-216-210 # Client errors211 212 213 class HTTPStatusError(HTTPError):61 unmodified lines275 276 277 class StreamConsumed(StreamError):278 """286- Attempted to read or stream response content, but the content has already279+ Attempted to read or stream content, but the content has already280 been streamed.281 """282 283 def __init__(self) -> None:284 message = (292- "Attempted to read or stream response content, but the content has "293- "already been streamed."285+ "Attempted to read or stream some content, but the content has "286+ "already been streamed. For requests, this could be due to passing "287+ "a generator as request content, and then receiving a redirect "288+ "response or a secondary request as part of an authentication flow."289+ "For responses, this could be due to attempting to stream the response "290+ "content more than once."291 )292 super().__init__(message)293 294 81 unmodified linesmodified:httpx/_models.py+67 added-23 removed
11 unmodified lines12 13 import rfc398614 import rfc3986.exceptions15 16-from ._content_streams import ByteStream, ContentStream, encode_request, encode_response16+from ._content_streams import PlainByteStream, encode_request, encode_response17 from ._decoders import (18 SUPPORTED_DECODERS,19 ContentDecoder,20 IdentityDecoder,15 unmodified lines36 map_exceptions,37 )38 from ._status_codes import codes39 from ._types import (40+ ByteStream,41 CookieTypes,42 HeaderTypes,43 PrimitiveData,44 QueryParamTypes,561 unmodified lines606 content: RequestContent = None,607 data: RequestData = None,608 files: RequestFiles = None,609 json: typing.Any = None,609- stream: ContentStream = None,610+ stream: ByteStream = None,611 ):612 if isinstance(method, bytes):613 self.method = method.decode("ascii").upper()614 else:3 unmodified lines618 if cookies:619 Cookies(cookies).set_cookie_header(self)620 621 if stream is not None:622+ # There's an important distinction between `Request(content=...)`,623+ # and `Request(stream=...)`.624+ #625+ # Using `content=...` implies automatically populated content headers,626+ # of either `Content-Length: ...` or `Transfer-Encoding: chunked`.627+ #628+ # Using `stream=...` will not automatically include any content headers.629+ #630+ # As an end-user you don't really need `stream=...`. It's only631+ # useful when:632+ #633+ # * Preserving the request stream when copying requests, eg for redirects.634+ # * Creating request instances on the *server-side* of the transport API.635 self.stream = stream636+ self._prepare({})637 else:623- self.stream = encode_request(content, data, files, json)638+ headers, stream = encode_request(content, data, files, json)639+ self._prepare(headers)640+ self.stream = stream641 625- self._prepare()626-627- def _prepare(self) -> None:628- for key, value in self.stream.get_headers().items():642+ def _prepare(self, default_headers: typing.Dict[str, str]) -> None:643+ for key, value in default_headers.items():644 # Ignore Transfer-Encoding if the Content-Length has been set explicitly.645 if key.lower() == "transfer-encoding" and "content-length" in self.headers:646 continue647 self.headers.setdefault(key, value)23 unmodified lines671 """672 Read and return the request content.673 """674 if not hasattr(self, "_content"):675+ assert isinstance(self.stream, typing.Iterable)676 self._content = b"".join(self.stream)677 # If a streaming request has been read entirely into memory, then678 # we can replace the stream with a raw bytes implementation,679 # to ensure that any non-replayable streams can still be used.664- self.stream = ByteStream(self._content)680+ self.stream = PlainByteStream(self._content)681 return self._content682 683 async def aread(self) -> bytes:684 """685 Read and return the request content.686 """687 if not hasattr(self, "_content"):688+ assert isinstance(self.stream, typing.AsyncIterable)689 self._content = b"".join([part async for part in self.stream])690 # If a streaming request has been read entirely into memory, then691 # we can replace the stream with a raw bytes implementation,692 # to ensure that any non-replayable streams can still be used.676- self.stream = ByteStream(self._content)693+ self.stream = PlainByteStream(self._content)694 return self._content695 696 def __repr__(self) -> str:697 class_name = self.__class__.__name__8 unmodified lines706 *,707 request: Request = None,708 http_version: str = None,709 headers: HeaderTypes = None,693- stream: ContentStream = None,710 content: ResponseContent = None,711+ stream: ByteStream = None,712 history: typing.List["Response"] = None,696- elapsed_func: typing.Callable = None,713+ on_close: typing.Callable = None,714 ):715 self.status_code = status_code716 self.http_version = http_version717 self.headers = Headers(headers)2 unmodified lines720 721 self.call_next: typing.Optional[typing.Callable] = None722 723 self.history = [] if history is None else list(history)707- self._elapsed_func = elapsed_func724+ self._on_close = on_close725 726 self.is_closed = False727 self.is_stream_consumed = False728+729 if stream is not None:730+ # There's an important distinction between `Response(content=...)`,731+ # and `Response(stream=...)`.732+ #733+ # Using `content=...` implies automatically populated content headers,734+ # of either `Content-Length: ...` or `Transfer-Encoding: chunked`.735+ #736+ # Using `stream=...` will not automatically include any content headers.737+ #738+ # As an end-user you don't really need `stream=...`. It's only739+ # useful when creating response instances having received a stream740+ # from the transport API.712- self._raw_stream = stream741+ self.stream = stream742 else:714- self._raw_stream = encode_response(content)743+ headers, stream = encode_response(content)744+ self._prepare(headers)745+ self.stream = stream746 if content is None or isinstance(content, bytes):747 # Load the response body, except for streaming content.748 self.read()749 750 self._num_bytes_downloaded = 0751 752+ def _prepare(self, default_headers: typing.Dict[str, str]) -> None:753+ for key, value in default_headers.items():754+ # Ignore Transfer-Encoding if the Content-Length has been set explicitly.755+ if key.lower() == "transfer-encoding" and "content-length" in self.headers:756+ continue757+ self.headers.setdefault(key, value)758+759 @property760 def elapsed(self) -> datetime.timedelta:761 """762 Returns the time taken for the complete request/response3 unmodified lines766 raise RuntimeError(767 "'.elapsed' may only be accessed after the response "768 "has been read or closed."769 )732- return datetime.timedelta(seconds=self._elapsed)770+ return self._elapsed771 772+ @elapsed.setter773+ def elapsed(self, elapsed: datetime.timedelta) -> None:774+ self._elapsed = elapsed775+776 @property777 def request(self) -> Request:778 """779 Returns the request instance associated to the current response.224 unmodified lines1004 if self.is_stream_consumed:1005 raise StreamConsumed()1006 if self.is_closed:1007 raise ResponseClosed()1008+ if not isinstance(self.stream, typing.Iterable):1009+ raise RuntimeError("Attempted to call a sync iterator on an async stream.")1010 1011 self.is_stream_consumed = True1012 self._num_bytes_downloaded = 01013 with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):970- for part in self._raw_stream:1014+ for part in self.stream:1015 self._num_bytes_downloaded += len(part)1016 yield part1017 self.close()1018 16 unmodified lines1035 Automatically called if the response body is read to completion.1036 """1037 if not self.is_closed:1038 self.is_closed = True995- if self._elapsed_func is not None:996- self._elapsed = self._elapsed_func()997- self._raw_stream.close()1039+ if self._on_close is not None:1040+ self._on_close(self)1041 1042 async def aread(self) -> bytes:1043 """1044 Read and return the response content.44 unmodified lines1089 if self.is_stream_consumed:1090 raise StreamConsumed()1091 if self.is_closed:1092 raise ResponseClosed()1093+ if not isinstance(self.stream, typing.AsyncIterable):1094+ raise RuntimeError("Attempted to call a async iterator on a sync stream.")1095 1096 self.is_stream_consumed = True1097 self._num_bytes_downloaded = 01098 with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):1054- async for part in self._raw_stream:1099+ async for part in self.stream:1100 self._num_bytes_downloaded += len(part)1101 yield part1102 await self.aclose()1103 15 unmodified lines1119 Automatically called if the response body is read to completion.1120 """1121 if not self.is_closed:1122 self.is_closed = True1078- if self._elapsed_func is not None:1079- self._elapsed = await self._elapsed_func()1080- await self._raw_stream.aclose()1123+ if self._on_close is not None:1124+ await self._on_close(self)1125 1126 1127 class Cookies(MutableMapping):1128 """177 unmodified linesmodified:httpx/_types.py+5 added-4 removed
5 unmodified lines6 from http.cookiejar import CookieJar7 from typing import (8 IO,9 TYPE_CHECKING,10- AsyncIterator,10+ AsyncIterable,11 Callable,12 Dict,13- Iterator,13+ Iterable,14 List,15 Mapping,16 Optional,17 Sequence,47 unmodified lines65 "Auth",66 None,67 ]68 69-RequestContent = Union[str, bytes, Iterator[bytes], AsyncIterator[bytes]]70-ResponseContent = Union[bytes, Iterator[bytes], AsyncIterator[bytes]]69+RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]70+ResponseContent = Union[bytes, Iterable[bytes], AsyncIterable[bytes]]71+ByteStream = Union[Iterable[bytes], AsyncIterable[bytes]]72 73 RequestData = dict74 75 FileContent = Union[IO[str], IO[bytes], str, bytes]9 unmodified linesmodified:tests/client/test_auth.py+3 added-12 removed
11 unmodified lines12 13 import pytest14 15 import httpx16-from httpx import (17- URL,18- Auth,19- BasicAuth,20- DigestAuth,21- ProtocolError,22- Request,23- RequestBodyUnavailable,24- Response,25-)16+from httpx import URL, Auth, BasicAuth, DigestAuth, ProtocolError, Request, Response17 from tests.utils import AsyncMockTransport, MockTransport18 19 from ..common import FIXTURES_DIR20 586 unmodified lines607 @pytest.mark.asyncio608 async def test_digest_auth_unavailable_streaming_body():609 url = "https://example.org/"610 auth = DigestAuth(username="tomchristie", password="password123")620- app = App()611+ app = DigestApp()612 613 async def streaming_body():614 yield b"Example request body" # pragma: nocover615 616 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:626- with pytest.raises(RequestBodyUnavailable):617+ with pytest.raises(httpx.StreamConsumed):618 await client.post(url, data=streaming_body(), auth=auth)619 620 621 @pytest.mark.asyncio63 unmodified linesmodified:tests/client/test_redirects.py+1 added-1 removed
332 unmodified lines333 334 def streaming_body():335 yield b"Example request body" # pragma: nocover336 337- with pytest.raises(httpx.RequestBodyUnavailable):337+ with pytest.raises(httpx.StreamConsumed):338 client.post(url, content=streaming_body())339 340 341 def test_cross_subdomain_redirect():73 unmodified linesmodified:tests/models/test_requests.py+41 added-1 removed
1+import typing2+3 import pytest4 5 import httpx6 12 unmodified lines19 request = httpx.Request("POST", "http://example.org", content=b"test 123")20 assert request.headers["Content-Length"] == "8"21 22 23+def test_iterable_content():24+ class Content:25+ def __iter__(self):26+ yield b"test 123" # pragma: nocover27+28+ request = httpx.Request("POST", "http://example.org", content=Content())29+ assert request.headers == httpx.Headers(30+ {"Host": "example.org", "Transfer-Encoding": "chunked"}31+ )32+33+34+def test_generator_with_transfer_encoding_header():35+ def content():36+ yield b"test 123" # pragma: nocover37+38+ request = httpx.Request("POST", "http://example.org", content=content())39+ assert request.headers == httpx.Headers(40+ {"Host": "example.org", "Transfer-Encoding": "chunked"}41+ )42+43+44+def test_generator_with_content_length_header():45+ def content():46+ yield b"test 123" # pragma: nocover47+48+ headers = {"Content-Length": "8"}49+ request = httpx.Request(50+ "POST", "http://example.org", content=content(), headers=headers51+ )52+ assert request.headers == httpx.Headers(53+ {"Host": "example.org", "Content-Length": "8"}54+ )55+56+57 def test_url_encoded_data():58 request = httpx.Request("POST", "http://example.org", data={"test": "123"})59 request.read()60 25 unmodified lines86 # Ensure a request may still be streamed if it has been read.87 # Needed for cases such as authentication classes that read the request body.88 request = httpx.Request("POST", "http://example.org", json={"test": 123})89 request.read()90+ assert request.stream is not None91+ assert isinstance(request.stream, typing.Iterable)92 content = b"".join([part for part in request.stream])93 assert content == request.content94 95 2 unmodified lines98 # Ensure a request may still be streamed if it has been read.99 # Needed for cases such as authentication classes that read the request body.100 request = httpx.Request("POST", "http://example.org", json={"test": 123})101 await request.aread()102+ assert request.stream is not None103+ assert isinstance(request.stream, typing.AsyncIterable)104 content = b"".join([part async for part in request.stream])105 assert content == request.content106 107 108 @pytest.mark.asyncio109 async def test_cannot_access_content_without_read():110 # Ensure a request may still be streamed if it has been read.71- # Needed for cases such as authentication classes that read the request body.111+ # Needed for cases such as authentication classes that read the request body.112 request = httpx.Request("POST", "http://example.org", json={"test": 123})113 with pytest.raises(httpx.RequestNotRead):114 request.content115 66 unmodified linesmodified:tests/models/test_responses.py+87 added
5 unmodified lines6 7 import httpx8 9 10+class StreamingBody:11+ def __iter__(self):12+ yield b"Hello, "13+ yield b"world!"14+15+16 def streaming_body():17 yield b"Hello, "18 yield b"world!"19 215 unmodified lines235 assert response.content == b"Hello, world!"236 assert response.is_closed237 238 239+def test_empty_read():240+ response = httpx.Response(200)241+242+ assert response.status_code == 200243+ assert response.text == ""244+ assert response.encoding is None245+ assert response.is_closed246+247+ content = response.read()248+249+ assert content == b""250+ assert response.content == b""251+ assert response.is_closed252+253+254 @pytest.mark.asyncio255 async def test_aread():256 response = httpx.Response(257 200,11 unmodified lines269 assert response.content == b"Hello, world!"270 assert response.is_closed271 272 273+@pytest.mark.asyncio274+async def test_empty_aread():275+ response = httpx.Response(200)276+277+ assert response.status_code == 200278+ assert response.text == ""279+ assert response.encoding is None280+ assert response.is_closed281+282+ content = await response.aread()283+284+ assert content == b""285+ assert response.content == b""286+ assert response.is_closed287+288+289 def test_iter_raw():290 response = httpx.Response(291 200,292 content=streaming_body(),4 unmodified lines297 raw += part298 assert raw == b"Hello, world!"299 300 301+def test_iter_raw_on_iterable():302+ response = httpx.Response(303+ 200,304+ content=StreamingBody(),305+ )306+307+ raw = b""308+ for part in response.iter_raw():309+ raw += part310+ assert raw == b"Hello, world!"311+312+313+def test_iter_raw_on_async():314+ response = httpx.Response(315+ 200,316+ content=async_streaming_body(),317+ )318+319+ with pytest.raises(RuntimeError):320+ [part for part in response.iter_raw()]321+322+323 def test_iter_raw_increments_updates_counter():324 response = httpx.Response(200, content=streaming_body())325 326 num_downloaded = response.num_bytes_downloaded12 unmodified lines339 assert raw == b"Hello, world!"340 341 342 @pytest.mark.asyncio343+async def test_aiter_raw_on_sync():344+ response = httpx.Response(345+ 200,346+ content=streaming_body(),347+ )348+349+ with pytest.raises(RuntimeError):350+ [part async for part in response.aiter_raw()]351+352+353+@pytest.mark.asyncio354 async def test_aiter_raw_increments_updates_counter():355 response = httpx.Response(200, content=async_streaming_body())356 357 num_downloaded = response.num_bytes_downloaded321 unmodified lines679 response = httpx.Response(200, content=b"Hello, world!")680 681 with pytest.raises(RuntimeError):682 response.request683+684+685+def test_generator_with_transfer_encoding_header():686+ def content():687+ yield b"test 123" # pragma: nocover688+689+ response = httpx.Response(200, content=content())690+ assert response.headers == httpx.Headers({"Transfer-Encoding": "chunked"})691+692+693+def test_generator_with_content_length_header():694+ def content():695+ yield b"test 123" # pragma: nocover696+697+ headers = {"Content-Length": "8"}698+ response = httpx.Response(200, content=content(), headers=headers)699+ assert response.headers == httpx.Headers({"Content-Length": "8"})modified:tests/test_content_streams.py+87 added-76 removed
1 import io2+import typing3 4 import pytest5 6 from httpx import StreamConsumed6-from httpx._content_streams import ContentStream, encode_request, encode_response7+from httpx._content_streams import encode_request, encode_response8 9 10 @pytest.mark.asyncio10-async def test_base_content():11- stream = ContentStream()12- sync_content = b"".join([part for part in stream])13- async_content = b"".join([part async for part in stream])14-15- assert stream.can_replay()16- assert stream.get_headers() == {}17- assert sync_content == b""18- assert async_content == b""19-20-21-@pytest.mark.asyncio11 async def test_empty_content():23- stream = encode_request()12+ headers, stream = encode_request()13+ assert isinstance(stream, typing.Iterable)14+ assert isinstance(stream, typing.AsyncIterable)15+16 sync_content = b"".join([part for part in stream])17 async_content = b"".join([part async for part in stream])18 27- assert stream.can_replay()28- assert stream.get_headers() == {}19+ assert headers == {}20 assert sync_content == b""21 assert async_content == b""22 23 24 @pytest.mark.asyncio25 async def test_bytes_content():35- stream = encode_request(content=b"Hello, world!")26+ headers, stream = encode_request(content=b"Hello, world!")27+ assert isinstance(stream, typing.Iterable)28+ assert isinstance(stream, typing.AsyncIterable)29+30 sync_content = b"".join([part for part in stream])31 async_content = b"".join([part async for part in stream])32 39- assert stream.can_replay()40- assert stream.get_headers() == {"Content-Length": "13"}33+ assert headers == {"Content-Length": "13"}34 assert sync_content == b"Hello, world!"35 assert async_content == b"Hello, world!"36 37 # Support 'data' for compat with requests.45- stream = encode_request(data=b"Hello, world!") # type: ignore38+ headers, stream = encode_request(data=b"Hello, world!") # type: ignore39+ assert isinstance(stream, typing.Iterable)40+ assert isinstance(stream, typing.AsyncIterable)41+42 sync_content = b"".join([part for part in stream])43 async_content = b"".join([part async for part in stream])44 49- assert stream.can_replay()50- assert stream.get_headers() == {"Content-Length": "13"}45+ assert headers == {"Content-Length": "13"}46 assert sync_content == b"Hello, world!"47 assert async_content == b"Hello, world!"48 49 2 unmodified lines52 def hello_world():53 yield b"Hello, "54 yield b"world!"55 61- stream = encode_request(content=hello_world())56+ headers, stream = encode_request(content=hello_world())57+ assert isinstance(stream, typing.Iterable)58+ assert not isinstance(stream, typing.AsyncIterable)59+60 content = b"".join([part for part in stream])61 64- assert not stream.can_replay()65- assert stream.get_headers() == {"Transfer-Encoding": "chunked"}62+ assert headers == {"Transfer-Encoding": "chunked"}63 assert content == b"Hello, world!"64 68- with pytest.raises(RuntimeError):69- [part async for part in stream]70-65 with pytest.raises(StreamConsumed):66 [part for part in stream]67 68 # Support 'data' for compat with requests.75- stream = encode_request(data=hello_world()) # type: ignore69+ headers, stream = encode_request(data=hello_world()) # type: ignore70+ assert isinstance(stream, typing.Iterable)71+ assert not isinstance(stream, typing.AsyncIterable)72+73 content = b"".join([part for part in stream])74 78- assert not stream.can_replay()79- assert stream.get_headers() == {"Transfer-Encoding": "chunked"}75+ assert headers == {"Transfer-Encoding": "chunked"}76 assert content == b"Hello, world!"77 78 79 @pytest.mark.asyncio1 unmodified line81 async def hello_world():82 yield b"Hello, "83 yield b"world!"84 89- stream = encode_request(content=hello_world())85+ headers, stream = encode_request(content=hello_world())86+ assert not isinstance(stream, typing.Iterable)87+ assert isinstance(stream, typing.AsyncIterable)88+89 content = b"".join([part async for part in stream])90 92- assert not stream.can_replay()93- assert stream.get_headers() == {"Transfer-Encoding": "chunked"}91+ assert headers == {"Transfer-Encoding": "chunked"}92 assert content == b"Hello, world!"93 96- with pytest.raises(RuntimeError):97- [part for part in stream]98-94 with pytest.raises(StreamConsumed):95 [part async for part in stream]96 97 # Support 'data' for compat with requests.103- stream = encode_request(data=hello_world()) # type: ignore98+ headers, stream = encode_request(data=hello_world()) # type: ignore99+ assert not isinstance(stream, typing.Iterable)100+ assert isinstance(stream, typing.AsyncIterable)101+102 content = b"".join([part async for part in stream])103 106- assert not stream.can_replay()107- assert stream.get_headers() == {"Transfer-Encoding": "chunked"}104+ assert headers == {"Transfer-Encoding": "chunked"}105 assert content == b"Hello, world!"106 107 108 @pytest.mark.asyncio109 async def test_json_content():113- stream = encode_request(json={"Hello": "world!"})110+ headers, stream = encode_request(json={"Hello": "world!"})111+ assert isinstance(stream, typing.Iterable)112+ assert isinstance(stream, typing.AsyncIterable)113+114 sync_content = b"".join([part for part in stream])115 async_content = b"".join([part async for part in stream])116 117- assert stream.can_replay()118- assert stream.get_headers() == {117+ assert headers == {118 "Content-Length": "19",119 "Content-Type": "application/json",120 }121 assert sync_content == b'{"Hello": "world!"}'1 unmodified line123 124 125 @pytest.mark.asyncio126 async def test_urlencoded_content():128- stream = encode_request(data={"Hello": "world!"})127+ headers, stream = encode_request(data={"Hello": "world!"})128+ assert isinstance(stream, typing.Iterable)129+ assert isinstance(stream, typing.AsyncIterable)130+131 sync_content = b"".join([part for part in stream])132 async_content = b"".join([part async for part in stream])133 132- assert stream.can_replay()133- assert stream.get_headers() == {134+ assert headers == {135 "Content-Length": "14",136 "Content-Type": "application/x-www-form-urlencoded",137 }138 assert sync_content == b"Hello=world%21"2 unmodified lines141 142 @pytest.mark.asyncio143 async def test_multipart_files_content():144 files = {"file": io.BytesIO(b"<file content>")}144- stream = encode_request(files=files, boundary=b"+++")145+ headers, stream = encode_request(files=files, boundary=b"+++")146+ assert isinstance(stream, typing.Iterable)147+ assert isinstance(stream, typing.AsyncIterable)148+149 sync_content = b"".join([part for part in stream])150 async_content = b"".join([part async for part in stream])151 148- assert stream.can_replay()149- assert stream.get_headers() == {152+ assert headers == {153 "Content-Length": "138",154 "Content-Type": "multipart/form-data; boundary=+++",155 }156 assert sync_content == b"".join(21 unmodified lines178 @pytest.mark.asyncio179 async def test_multipart_data_and_files_content():180 data = {"message": "Hello, world!"}181 files = {"file": io.BytesIO(b"<file content>")}179- stream = encode_request(data=data, files=files, boundary=b"+++")182+ headers, stream = encode_request(data=data, files=files, boundary=b"+++")183+ assert isinstance(stream, typing.Iterable)184+ assert isinstance(stream, typing.AsyncIterable)185+186 sync_content = b"".join([part for part in stream])187 async_content = b"".join([part async for part in stream])188 183- assert stream.can_replay()184- assert stream.get_headers() == {189+ assert headers == {190 "Content-Length": "210",191 "Content-Type": "multipart/form-data; boundary=+++",192 }193 assert sync_content == b"".join(27 unmodified lines221 222 223 @pytest.mark.asyncio224 async def test_empty_request():220- stream = encode_request(data={}, files={})225+ headers, stream = encode_request(data={}, files={})226+ assert isinstance(stream, typing.Iterable)227+ assert isinstance(stream, typing.AsyncIterable)228+229 sync_content = b"".join([part for part in stream])230 async_content = b"".join([part async for part in stream])231 224- assert stream.can_replay()225- assert stream.get_headers() == {}232+ assert headers == {}233 assert sync_content == b""234 assert async_content == b""235 236 7 unmodified lines244 files = [245 ("file", io.BytesIO(b"<file content 1>")),246 ("file", io.BytesIO(b"<file content 2>")),247 ]241- stream = encode_request(files=files, boundary=b"+++")248+ headers, stream = encode_request(files=files, boundary=b"+++")249+ assert isinstance(stream, typing.Iterable)250+ assert isinstance(stream, typing.AsyncIterable)251+252 sync_content = b"".join([part for part in stream])253 async_content = b"".join([part async for part in stream])254 245- assert stream.can_replay()246- assert stream.get_headers() == {255+ assert headers == {256 "Content-Length": "271",257 "Content-Type": "multipart/form-data; boundary=+++",258 }259 assert sync_content == b"".join(29 unmodified lines289 290 291 @pytest.mark.asyncio292 async def test_response_empty_content():284- stream = encode_response()293+ headers, stream = encode_response()294+ assert isinstance(stream, typing.Iterable)295+ assert isinstance(stream, typing.AsyncIterable)296+297 sync_content = b"".join([part for part in stream])298 async_content = b"".join([part async for part in stream])299 288- assert stream.can_replay()289- assert stream.get_headers() == {}300+ assert headers == {}301 assert sync_content == b""302 assert async_content == b""303 304 305 @pytest.mark.asyncio306 async def test_response_bytes_content():296- stream = encode_response(content=b"Hello, world!")307+ headers, stream = encode_response(content=b"Hello, world!")308+ assert isinstance(stream, typing.Iterable)309+ assert isinstance(stream, typing.AsyncIterable)310+311 sync_content = b"".join([part for part in stream])312 async_content = b"".join([part async for part in stream])313 300- assert stream.can_replay()301- assert stream.get_headers() == {"Content-Length": "13"}314+ assert headers == {"Content-Length": "13"}315 assert sync_content == b"Hello, world!"316 assert async_content == b"Hello, world!"317 318 2 unmodified lines321 def hello_world():322 yield b"Hello, "323 yield b"world!"324 312- stream = encode_response(content=hello_world())325+ headers, stream = encode_response(content=hello_world())326+ assert isinstance(stream, typing.Iterable)327+ assert not isinstance(stream, typing.AsyncIterable)328+329 content = b"".join([part for part in stream])330 315- assert not stream.can_replay()316- assert stream.get_headers() == {"Transfer-Encoding": "chunked"}331+ assert headers == {"Transfer-Encoding": "chunked"}332 assert content == b"Hello, world!"333 319- with pytest.raises(RuntimeError):320- [part async for part in stream]321-334 with pytest.raises(StreamConsumed):335 [part for part in stream]336 337 2 unmodified lines340 async def hello_world():341 yield b"Hello, "342 yield b"world!"343 332- stream = encode_response(content=hello_world())344+ headers, stream = encode_response(content=hello_world())345+ assert not isinstance(stream, typing.Iterable)346+ assert isinstance(stream, typing.AsyncIterable)347+348 content = b"".join([part async for part in stream])349 335- assert not stream.can_replay()336- assert stream.get_headers() == {"Transfer-Encoding": "chunked"}350+ assert headers == {"Transfer-Encoding": "chunked"}351 assert content == b"Hello, world!"352 339- with pytest.raises(RuntimeError):340- [part for part in stream]341-353 with pytest.raises(StreamConsumed):354 [part async for part in stream]355 356 3 unmodified linesmodified:tests/test_multipart.py+9 added-16 removed
108 unmodified lines109 110 with mock.patch("os.urandom", return_value=os.urandom(16)):111 boundary = os.urandom(16).hex()112 113- stream = encode_request(data=data, files=files)113+ headers, stream = encode_request(data=data, files=files)114 assert isinstance(stream, MultipartStream)115- assert stream.can_replay()115 116 assert stream.content_type == f"multipart/form-data; boundary={boundary}"117 content = (118 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'7 unmodified lines126 "Content-Type: text/plain\r\n\r\n<file content>\r\n"127 "--{0}--\r\n"128 "".format(boundary).encode("ascii")129 )131- assert stream.get_headers()["Content-Length"] == str(len(content))130+ assert headers["Content-Length"] == str(len(content))131 assert b"".join(stream) == content132 133 134 def test_multipart_encode_files_allows_filenames_as_none() -> None:135 files = {"file": (None, io.BytesIO(b"<file content>"))}136 with mock.patch("os.urandom", return_value=os.urandom(16)):137 boundary = os.urandom(16).hex()138 140- stream = encode_request(data={}, files=files)139+ headers, stream = encode_request(data={}, files=files)140 assert isinstance(stream, MultipartStream)142- assert stream.can_replay()141 142 assert stream.content_type == f"multipart/form-data; boundary={boundary}"143 assert b"".join(stream) == (144 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'16 unmodified lines161 files = {"file": (file_name, io.BytesIO(b"<file content>"))}162 with mock.patch("os.urandom", return_value=os.urandom(16)):163 boundary = os.urandom(16).hex()164 167- stream = encode_request(data={}, files=files)165+ headers, stream = encode_request(data={}, files=files)166 assert isinstance(stream, MultipartStream)169- assert stream.can_replay()167 168 assert stream.content_type == f"multipart/form-data; boundary={boundary}"169 assert b"".join(stream) == (170 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '13 unmodified lines184 files = {"file": ("test.txt", value, "text/plain")}185 with mock.patch("os.urandom", return_value=os.urandom(16)):186 boundary = os.urandom(16).hex()187 191- stream = encode_request(data={}, files=files)188+ headers, stream = encode_request(data={}, files=files)189 assert isinstance(stream, MultipartStream)193- assert stream.can_replay()190 191 assert stream.content_type == f"multipart/form-data; boundary={boundary}"192 content = (193 '--{0}\r\nContent-Disposition: form-data; name="file"; '1 unmodified line195 "Content-Type: text/plain\r\n\r\n{1}\r\n"196 "--{0}--\r\n"197 "".format(boundary, output).encode("ascii")198 )203- assert stream.get_headers()["Content-Length"] == str(len(content))199+ assert headers["Content-Length"] == str(len(content))200 assert b"".join(stream) == content201 202 203 def test_multipart_encode_non_seekable_filelike() -> None:5 unmodified lines209 class IteratorIO(io.IOBase):210 def __init__(self, iterator: typing.Iterator[bytes]) -> None:211 self._iterator = iterator212 217- def seekable(self) -> bool:218- return False219-213 def read(self, *args: typing.Any) -> bytes:214 return b"".join(self._iterator)215 216 def data() -> typing.Iterator[bytes]:1 unmodified line218 yield b"World"219 220 fileobj: typing.Any = IteratorIO(data())221 files = {"file": fileobj}229- stream = encode_request(files=files, boundary=b"+++")230- assert not stream.can_replay()222+ headers, stream = encode_request(files=files, boundary=b"+++")223+ assert isinstance(stream, typing.Iterable)224 225 content = (226 b"--+++\r\n"227 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'1 unmodified line229 b"\r\n"230 b"HelloWorld\r\n"231 b"--+++--\r\n"232 )240- assert stream.get_headers() == {233+ assert headers == {234 "Content-Type": "multipart/form-data; boundary=+++",235 "Content-Length": str(len(content)),236 }237 assert b"".join(stream) == content18 unmodified linesmodified:tests/utils.py+16 added-37 removed
34 unmodified lines35 headers: List[Tuple[bytes, bytes]] = None,36 stream: httpcore.SyncByteStream = None,37 timeout: Mapping[str, Optional[float]] = None,38 ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.SyncByteStream]:39- request_headers = httpx.Headers(headers)40- content = (41- (item for item in stream)42- if stream43- and (44- "Content-Length" in request_headers45- or "Transfer-Encoding" in request_headers46- )47- else None48- )49-39 request = httpx.Request(40 method=method,41 url=url,53- headers=request_headers,54- content=content,42+ headers=headers,43+ stream=stream,44 )45 request.read()46 response = self.handler(request)47 return (48 (response.http_version or "HTTP/1.1").encode("ascii"),49 response.status_code,50 response.reason_phrase.encode("ascii"),51 response.headers.raw,63- response._raw_stream,52+ response.stream,53 )54 55 56 class AsyncMockTransport(httpcore.AsyncHTTPTransport):57 def __init__(self, handler: Callable) -> None:69- self.impl = MockTransport(handler)58+ self.handler = handler59 60 async def request(61 self,62 method: bytes,1 unmodified line64 headers: List[Tuple[bytes, bytes]] = None,65 stream: httpcore.AsyncByteStream = None,66 timeout: Mapping[str, Optional[float]] = None,67 ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream]:79- content = (80- httpcore.PlainByteStream(b"".join([part async for part in stream]))81- if stream82- else httpcore.PlainByteStream(b"")68+ request = httpx.Request(69+ method=method,70+ url=url,71+ headers=headers,72+ stream=stream,73 )84-85- (86- http_version,87- status_code,88- reason_phrase,89- headers,90- response_stream,91- ) = self.impl.request(92- method, url, headers=headers, stream=content, timeout=timeout93- )94-95- content = httpcore.PlainByteStream(b"".join([part for part in response_stream]))96-74+ await request.aread()75+ response = self.handler(request)76 return (98- http_version,99- status_code,100- reason_phrase,101- headers,102- content,77+ (response.http_version or "HTTP/1.1").encode("ascii"),78+ response.status_code,79+ response.reason_phrase.encode("ascii"),80+ response.headers.raw,81+ response.stream,82 )