Support Response(text=...), Response(html=...), Response(json=...) (#1297)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Refactor content_streams internally * Tidy up multipart * Use ByteStream annotation internally * Support Response(text=...), Response(html=...), Response(json=...) * Add tests for Response(text=..., html=..., json=...)
authored by Tom Christie · committed by GitHub · parent 8ee08af · Browse files · 8 files·+115 added−42 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+115 added−42 removed
- tests:+59 added−23 removed
- other:+56 added−19 removed
Provenance
- Commit
f3c2941- Tree
d485392- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
8ee08af
8 files changed+115 added−42 removed
modified:httpx/_content.py+50 added-16 removed
1 import inspect2-import typing2 from json import dumps as json_dumps3+from typing import (4+ Any,5+ AsyncIterable,6+ AsyncIterator,7+ Dict,8+ Iterable,9+ Iterator,10+ Tuple,11+ Union,12+)13 from urllib.parse import urlencode14 15 from ._exceptions import StreamConsumed16 from ._multipart import MultipartStream13 unmodified lines30 31 def __init__(self, body: bytes) -> None:32 self._body = body33 25- def __iter__(self) -> typing.Iterator[bytes]:34+ def __iter__(self) -> Iterator[bytes]:35 yield self._body36 28- async def __aiter__(self) -> typing.AsyncIterator[bytes]:37+ async def __aiter__(self) -> AsyncIterator[bytes]:38 yield self._body39 40 41 class GeneratorStream:42 """43 Request content encoded as plain bytes, using an byte generator.44 """45 37- def __init__(self, generator: typing.Iterable[bytes]) -> None:46+ def __init__(self, generator: Iterable[bytes]) -> None:47 self._generator = generator48 self._is_stream_consumed = False49 41- def __iter__(self) -> typing.Iterator[bytes]:50+ def __iter__(self) -> Iterator[bytes]:51 if self._is_stream_consumed:52 raise StreamConsumed()53 54 self._is_stream_consumed = True5 unmodified lines60 """61 Request content encoded as plain bytes, using an async byte iterator.62 """63 55- def __init__(self, agenerator: typing.AsyncIterable[bytes]) -> None:64+ def __init__(self, agenerator: AsyncIterable[bytes]) -> None:65 self._agenerator = agenerator66 self._is_stream_consumed = False67 59- async def __aiter__(self) -> typing.AsyncIterator[bytes]:68+ async def __aiter__(self) -> AsyncIterator[bytes]:69 if self._is_stream_consumed:70 raise StreamConsumed()71 72 self._is_stream_consumed = True1 unmodified line74 yield part75 76 77 def encode_content(69- content: typing.Union[str, bytes, ByteStream]70-) -> typing.Tuple[typing.Dict[str, str], ByteStream]:78+ content: Union[str, bytes, ByteStream]79+) -> Tuple[Dict[str, str], ByteStream]:80 if isinstance(content, (str, bytes)):81 body = content.encode("utf-8") if isinstance(content, str) else content82 content_length = str(len(body))83 headers = {"Content-Length": content_length} if body else {}84 stream = PlainByteStream(body)85 return headers, stream86 78- elif isinstance(content, (typing.Iterable, typing.AsyncIterable)):87+ elif isinstance(content, (Iterable, AsyncIterable)):88 headers = {"Transfer-Encoding": "chunked"}89 90 # Generators should be wrapped in GeneratorStream/AsyncGeneratorStream91 # which will raise `StreamConsumed` if the stream is accessed more12 unmodified lines104 105 106 def encode_urlencoded_data(107 data: dict,99-) -> typing.Tuple[typing.Dict[str, str], ByteStream]:108+) -> Tuple[Dict[str, str], ByteStream]:109 body = urlencode(data, doseq=True).encode("utf-8")110 content_length = str(len(body))111 content_type = "application/x-www-form-urlencoded"112 headers = {"Content-Length": content_length, "Content-Type": content_type}1 unmodified line114 115 116 def encode_multipart_data(117 data: dict, files: RequestFiles, boundary: bytes = None109-) -> typing.Tuple[typing.Dict[str, str], ByteStream]:118+) -> Tuple[Dict[str, str], ByteStream]:119 stream = MultipartStream(data=data, files=files, boundary=boundary)120 headers = stream.get_headers()121 return headers, stream122 123 115-def encode_json(json: typing.Any) -> typing.Tuple[typing.Dict[str, str], ByteStream]:124+def encode_text(text: str) -> Tuple[Dict[str, str], ByteStream]:125+ body = text.encode("utf-8")126+ content_length = str(len(body))127+ content_type = "text/plain; charset=utf-8"128+ headers = {"Content-Length": content_length, "Content-Type": content_type}129+ return headers, PlainByteStream(body)130+131+132+def encode_html(html: str) -> Tuple[Dict[str, str], ByteStream]:133+ body = html.encode("utf-8")134+ content_length = str(len(body))135+ content_type = "text/html; charset=utf-8"136+ headers = {"Content-Length": content_length, "Content-Type": content_type}137+ return headers, PlainByteStream(body)138+139+140+def encode_json(json: Any) -> Tuple[Dict[str, str], ByteStream]:141 body = json_dumps(json).encode("utf-8")142 content_length = str(len(body))143 content_type = "application/json"144 headers = {"Content-Length": content_length, "Content-Type": content_type}3 unmodified lines148 def encode_request(149 content: RequestContent = None,150 data: RequestData = None,151 files: RequestFiles = None,127- json: typing.Any = None,152+ json: Any = None,153 boundary: bytes = None,129-) -> typing.Tuple[typing.Dict[str, str], ByteStream]:154+) -> Tuple[Dict[str, str], ByteStream]:155 """156 Handles encoding the given `content`, `data`, `files`, and `json`,157 returning a two-tuple of (<headers>, <stream>).158 """20 unmodified lines179 180 181 def encode_response(182 content: ResponseContent = None,183+ text: str = None,184+ html: str = None,185+ json: Any = None,158-) -> typing.Tuple[typing.Dict[str, str], ByteStream]:186+) -> Tuple[Dict[str, str], ByteStream]:187 """188 Handles encoding the given `content`, returning a two-tuple of189 (<headers>, <stream>).190 """191 if content is not None:192 return encode_content(content)193+ elif text is not None:194+ return encode_text(text)195+ elif html is not None:196+ return encode_html(html)197+ elif json is not None:198+ return encode_json(json)199 200 return {}, PlainByteStream(b"")modified:httpx/_models.py+6 added-3 removed
702 unmodified lines703 def __init__(704 self,705 status_code: int,706 *,707- request: Request = None,708- http_version: str = None,707 headers: HeaderTypes = None,708 content: ResponseContent = None,709+ text: str = None,710+ html: str = None,711+ json: typing.Any = None,712 stream: ByteStream = None,713+ http_version: str = None,714+ request: Request = None,715 history: typing.List["Response"] = None,716 on_close: typing.Callable = None,717 ):718 self.status_code = status_code23 unmodified lines742 # useful when creating response instances having received a stream743 # from the transport API.744 self.stream = stream745 else:743- headers, stream = encode_response(content)746+ headers, stream = encode_response(content, text, html, json)747 self._prepare(headers)748 self.stream = stream749 if content is None or isinstance(content, bytes):750 # Load the response body, except for streaming content.558 unmodified linesmodified:tests/client/test_auth.py+2 added-5 removed
3 unmodified lines4 Unit tests for auth classes also exist in tests/test_auth.py5 """6 import asyncio7 import hashlib8-import json8 import os9 import threading10 import typing11 13 unmodified lines25 26 def __call__(self, request: httpx.Request) -> httpx.Response:27 headers = {"www-authenticate": self.auth_header} if self.auth_header else {}28 data = {"auth": request.headers.get("Authorization")}30- content = json.dumps(data).encode("utf-8")31- return httpx.Response(self.status_code, headers=headers, content=content)29+ return httpx.Response(self.status_code, headers=headers, json=data)30 31 32 class DigestApp:33 def __init__(13 unmodified lines47 if self._response_count < self.send_response_after_attempt:48 return self.challenge_send(request)49 50 data = {"auth": request.headers.get("Authorization")}53- content = json.dumps(data).encode("utf-8")54- return httpx.Response(200, content=content)51+ return httpx.Response(200, json=data)52 53 def challenge_send(self, request: httpx.Request) -> httpx.Response:54 self._response_count += 155 nonce = (626 unmodified linesmodified:tests/client/test_cookies.py+1 added-3 removed
1-import json1 from http.cookiejar import Cookie, CookieJar2 3 import httpx4 from tests.utils import MockTransport1 unmodified line6 7 def get_and_set_cookies(request: httpx.Request) -> httpx.Response:8 if request.url.path == "/echo_cookies":9 data = {"cookies": request.headers.get("cookie")}11- content = json.dumps(data).encode("utf-8")12- return httpx.Response(200, content=content)10+ return httpx.Response(200, json=data)11 elif request.url.path == "/set_cookie":12 return httpx.Response(200, headers={"set-cookie": "example-name=example-value"})13 else:14 raise NotImplementedError() # pragma: no cover132 unmodified linesmodified:tests/client/test_headers.py+1 added-4 removed
1 #!/usr/bin/env python32 3-import json4-3 import pytest4 5 import httpx6 from tests.utils import MockTransport7 8 9 def echo_headers(request: httpx.Request) -> httpx.Response:10 data = {"headers": dict(request.headers)}13- content = json.dumps(data).encode("utf-8")14- return httpx.Response(200, content=content)11+ return httpx.Response(200, json=data)12 13 14 def test_client_header():15 """172 unmodified linesmodified:tests/client/test_queryparams.py+1 added-1 removed
1 unmodified line2 from tests.utils import MockTransport3 4 5 def hello_world(request: httpx.Request) -> httpx.Response:6- return httpx.Response(200, content=b"Hello, world")6+ return httpx.Response(200, text="Hello, world")7 8 9 def test_client_queryparams():10 client = httpx.Client(params={"a": "b"})26 unmodified linesmodified:tests/client/test_redirects.py+12 added-10 removed
1-import json2-1 import httpcore2 import pytest3 4 import httpx70 unmodified lines75 return httpx.Response(status_code, headers=headers)76 77 elif request.url.path == "/cross_domain_target":78 status_code = httpx.codes.OK81- content = json.dumps({"headers": dict(request.headers)}).encode("utf-8")82- return httpx.Response(status_code, content=content)79+ data = {80+ "body": request.content.decode("ascii"),81+ "headers": dict(request.headers),82+ }83+ return httpx.Response(status_code, json=data)84 85 elif request.url.path == "/redirect_body":86 status_code = httpx.codes.PERMANENT_REDIRECT87 headers = {"location": "/redirect_body_target"}4 unmodified lines92 headers = {"location": "/redirect_body_target"}93 return httpx.Response(status_code, headers=headers)94 95 elif request.url.path == "/redirect_body_target":95- content = json.dumps(96- {"body": request.content.decode("ascii"), "headers": dict(request.headers)}97- ).encode("utf-8")98- return httpx.Response(200, content=content)96+ data = {97+ "body": request.content.decode("ascii"),98+ "headers": dict(request.headers),99+ }100+ return httpx.Response(200, json=data)101 102 elif request.url.path == "/cross_subdomain":103 if request.headers["Host"] != "www.example.org":104 status_code = httpx.codes.PERMANENT_REDIRECT105 headers = {"location": "https://www.example.org/cross_subdomain"}106 return httpx.Response(status_code, headers=headers)107 else:106- return httpx.Response(200, content=b"Hello, world!")108+ return httpx.Response(200, text="Hello, world!")109 110 elif request.url.path == "/redirect_custom_scheme":111 status_code = httpx.codes.MOVED_PERMANENTLY112 headers = {"location": "market://details?id=42"}1 unmodified line114 115 if request.method == "HEAD":116 return httpx.Response(200)117 116- return httpx.Response(200, content=b"Hello, world!")118+ return httpx.Response(200, html="<html><body>Hello, world!</body></html>")119 120 121 def test_no_redirect():122 client = httpx.Client(transport=MockTransport(redirects))294 unmodified linesmodified:tests/models/test_responses.py+42 added
36 unmodified lines37 assert response.request.url == "https://example.org"38 assert not response.is_error39 40 41+def test_response_text():42+ response = httpx.Response(200, text="Hello, world!")43+44+ assert response.status_code == 20045+ assert response.reason_phrase == "OK"46+ assert response.text == "Hello, world!"47+ assert response.headers == httpx.Headers(48+ {49+ "Content-Length": "13",50+ "Content-Type": "text/plain; charset=utf-8",51+ }52+ )53+54+55+def test_response_html():56+ response = httpx.Response(200, html="<html><body>Hello, world!</html></body>")57+58+ assert response.status_code == 20059+ assert response.reason_phrase == "OK"60+ assert response.text == "<html><body>Hello, world!</html></body>"61+ assert response.headers == httpx.Headers(62+ {63+ "Content-Length": "39",64+ "Content-Type": "text/html; charset=utf-8",65+ }66+ )67+68+69+def test_response_json():70+ response = httpx.Response(200, json={"hello": "world"})71+72+ assert response.status_code == 20073+ assert response.reason_phrase == "OK"74+ assert response.json() == {"hello": "world"}75+ assert response.headers == httpx.Headers(76+ {77+ "Content-Length": "18",78+ "Content-Type": "application/json",79+ }80+ )81+82+83 def test_raise_for_status():84 request = httpx.Request("GET", "https://example.org")85 86 # 2xx status codes are not an error.655 unmodified lines