Skip to content
Myr

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

8 files+115 added−42 removed

modified:httpx/_content.py+50 added-16 removed
1import inspect2import typing2from json import dumps as json_dumps3from typing import (4 Any,5 AsyncIterable,6 AsyncIterator,7 Dict,8 Iterable,9 Iterator,10 Tuple,11 Union,12)13from urllib.parse import urlencode1415from ._exceptions import StreamConsumed16from ._multipart import MultipartStream
13 unmodified lines
3031 def __init__(self, body: bytes) -> None:32 self._body = body3325 def __iter__(self) -> typing.Iterator[bytes]:34 def __iter__(self) -> Iterator[bytes]:35 yield self._body3628 async def __aiter__(self) -> typing.AsyncIterator[bytes]:37 async def __aiter__(self) -> AsyncIterator[bytes]:38 yield self._body394041class GeneratorStream:42 """43 Request content encoded as plain bytes, using an byte generator.44 """4537 def __init__(self, generator: typing.Iterable[bytes]) -> None:46 def __init__(self, generator: Iterable[bytes]) -> None:47 self._generator = generator48 self._is_stream_consumed = False4941 def __iter__(self) -> typing.Iterator[bytes]:50 def __iter__(self) -> Iterator[bytes]:51 if self._is_stream_consumed:52 raise StreamConsumed()5354 self._is_stream_consumed = True
5 unmodified lines
60 """61 Request content encoded as plain bytes, using an async byte iterator.62 """6355 def __init__(self, agenerator: typing.AsyncIterable[bytes]) -> None:64 def __init__(self, agenerator: AsyncIterable[bytes]) -> None:65 self._agenerator = agenerator66 self._is_stream_consumed = False6759 async def __aiter__(self) -> typing.AsyncIterator[bytes]:68 async def __aiter__(self) -> AsyncIterator[bytes]:69 if self._is_stream_consumed:70 raise StreamConsumed()7172 self._is_stream_consumed = True
1 unmodified line
74 yield part757677def 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, stream8678 elif isinstance(content, (typing.Iterable, typing.AsyncIterable)):87 elif isinstance(content, (Iterable, AsyncIterable)):88 headers = {"Transfer-Encoding": "chunked"}8990 # Generators should be wrapped in GeneratorStream/AsyncGeneratorStream91 # which will raise `StreamConsumed` if the stream is accessed more
12 unmodified lines
104105106def 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 line
114115116def 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, stream122123115def encode_json(json: typing.Any) -> typing.Tuple[typing.Dict[str, str], ByteStream]:124def 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)130131132def 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)138139140def 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 lines
148def 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 lines
179180181def 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)199200 return {}, PlainByteStream(b"")
modified:httpx/_models.py+6 added-3 removed
702 unmodified lines
703 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_code
23 unmodified lines
742 # 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 lines
modified:tests/client/test_auth.py+2 added-5 removed
3 unmodified lines
4Unit tests for auth classes also exist in tests/test_auth.py5"""6import asyncio7import hashlib8import json8import os9import threading10import typing11
13 unmodified lines
2526 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)303132class DigestApp:33 def __init__(
13 unmodified lines
47 if self._response_count < self.send_response_after_attempt:48 return self.challenge_send(request)4950 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)5253 def challenge_send(self, request: httpx.Request) -> httpx.Response:54 self._response_count += 155 nonce = (
626 unmodified lines
modified:tests/client/test_cookies.py+1 added-3 removed
1import json1from http.cookiejar import Cookie, CookieJar23import httpx4from tests.utils import MockTransport
1 unmodified line
67def 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 cover
132 unmodified lines
modified:tests/client/test_headers.py+1 added-4 removed
1#!/usr/bin/env python323import json43import pytest45import httpx6from tests.utils import MockTransport789def 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)121314def test_client_header():15 """
172 unmodified lines
modified:tests/client/test_queryparams.py+1 added-1 removed
1 unmodified line
2from tests.utils import MockTransport345def hello_world(request: httpx.Request) -> httpx.Response:6 return httpx.Response(200, content=b"Hello, world")6 return httpx.Response(200, text="Hello, world")789def test_client_queryparams():10 client = httpx.Client(params={"a": "b"})
26 unmodified lines
modified:tests/client/test_redirects.py+12 added-10 removed
1import json21import httpcore2import pytest34import httpx
70 unmodified lines
75 return httpx.Response(status_code, headers=headers)7677 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)8485 elif request.url.path == "/redirect_body":86 status_code = httpx.codes.PERMANENT_REDIRECT87 headers = {"location": "/redirect_body_target"}
4 unmodified lines
92 headers = {"location": "/redirect_body_target"}93 return httpx.Response(status_code, headers=headers)9495 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)101102 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!")109110 elif request.url.path == "/redirect_custom_scheme":111 status_code = httpx.codes.MOVED_PERMANENTLY112 headers = {"location": "market://details?id=42"}
1 unmodified line
114115 if request.method == "HEAD":116 return httpx.Response(200)117116 return httpx.Response(200, content=b"Hello, world!")118 return httpx.Response(200, html="<html><body>Hello, world!</body></html>")119120121def test_no_redirect():122 client = httpx.Client(transport=MockTransport(redirects))
294 unmodified lines
modified:tests/models/test_responses.py+42 added
36 unmodified lines
37 assert response.request.url == "https://example.org"38 assert not response.is_error394041def test_response_text():42 response = httpx.Response(200, text="Hello, world!")4344 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 )535455def test_response_html():56 response = httpx.Response(200, html="<html><body>Hello, world!</html></body>")5758 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 )676869def test_response_json():70 response = httpx.Response(200, json={"hello": "world"})7172 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 )818283def test_raise_for_status():84 request = httpx.Request("GET", "https://example.org")8586 # 2xx status codes are not an error.
655 unmodified lines