Prefer 'content' over 'body'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by Tom Christie · parent 4c55113 · Browse files · 10 files·+60 added−60 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+60 added−60 removed
- tests:+19 added−17 removed
- other:+41 added−43 removed
Provenance
- Commit
4255d41- Tree
7e31c67- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
4c55113
10 files changed+60 added−60 removed
modified:httpcore/adapters/redirects.py+4 added-4 removed
64 unmodified lines65 def build_redirect_request(self, request: Request, response: Response) -> Request:66 method = self.redirect_method(request, response)67 url = self.redirect_url(request, response)68 headers = self.redirect_headers(request, url)69- body = self.redirect_body(request, method)70- return Request(method=method, url=url, headers=headers, body=body)69+ content = self.redirect_content(request, method)70+ return Request(method=method, url=url, headers=headers, content=content)71 72 def redirect_method(self, request: Request, response: Response) -> str:73 """74 When being redirected we may want to change the method of the request52 unmodified lines127 if url.origin != request.url.origin:128 del headers["Authorization"]129 return headers130 131- def redirect_body(self, request: Request, method: str) -> bytes:131+ def redirect_content(self, request: Request, method: str) -> bytes:132 """133 Return the body that should be used for the redirect request.134 """135 if method != request.method and method == "GET":136 return b""137 if request.is_streaming:138 raise RedirectBodyUnavailable()139- return request.body139+ return request.contentmodified:httpcore/dispatch/http11.py+2 added-2 removed
76 unmodified lines77 assert isinstance(event, h11.Response)78 reason_phrase = event.reason.decode("latin1")79 status_code = event.status_code80 headers = event.headers81- body = self._body_iter(timeout)81+ content = self._body_iter(timeout)82 83 response = Response(84 status_code=status_code,85 reason_phrase=reason_phrase,86 protocol="HTTP/1.1",87 headers=headers,88- content=body,88+ content=content,89 on_close=self.response_closed,90 request=request,91 )92 56 unmodified linesmodified:httpcore/dispatch/http2.py+2 added-2 removed
64 unmodified lines65 status_code = int(v.decode())66 elif not k.startswith(b":"):67 headers.append((k, v))68 69- body = self.body_iter(stream_id, timeout)69+ content = self.body_iter(stream_id, timeout)70 on_close = functools.partial(self.response_closed, stream_id=stream_id)71 72 response = Response(73 status_code=status_code,74 protocol="HTTP/2",75 headers=headers,76- content=body,76+ content=content,77 on_close=on_close,78 request=request,79 )80 76 unmodified linesmodified:httpcore/client.py+11 added-11 removed
13 unmodified lines14 SSLConfig,15 TimeoutConfig,16 )17 from .dispatch.connection_pool import ConnectionPool18-from .models import URL, BodyTypes, HeaderTypes, Request, Response, URLTypes18+from .models import URL, ByteOrByteStream, HeaderTypes, Request, Response, URLTypes19 20 21 class Client:22 def __init__(15 unmodified lines38 self,39 method: str,40 url: URLTypes,41 *,42- body: BodyTypes = b"",42+ content: ByteOrByteStream = b"",43 headers: HeaderTypes = None,44 stream: bool = False,45 allow_redirects: bool = True,46 ssl: SSLConfig = None,47 timeout: TimeoutConfig = None,48 ) -> Response:49- request = Request(method, url, headers=headers, body=body)49+ request = Request(method, url, headers=headers, content=content)50 self.prepare_request(request)51 response = await self.send(52 request,53 stream=stream,66 unmodified lines120 async def post(121 self,122 url: URLTypes,123 *,124- body: BodyTypes = b"",124+ content: ByteOrByteStream = b"",125 headers: HeaderTypes = None,126 stream: bool = False,127 allow_redirects: bool = True,128 ssl: SSLConfig = None,1 unmodified line130 ) -> Response:131 return await self.request(132 "POST",133 url,134- body=body,134+ content=content,135 headers=headers,136 stream=stream,137 allow_redirects=allow_redirects,138 ssl=ssl,3 unmodified lines142 async def put(143 self,144 url: URLTypes,145 *,146- body: BodyTypes = b"",146+ content: ByteOrByteStream = b"",147 headers: HeaderTypes = None,148 stream: bool = False,149 allow_redirects: bool = True,150 ssl: SSLConfig = None,1 unmodified line152 ) -> Response:153 return await self.request(154 "PUT",155 url,156- body=body,156+ content=content,157 headers=headers,158 stream=stream,159 allow_redirects=allow_redirects,160 ssl=ssl,3 unmodified lines164 async def patch(165 self,166 url: URLTypes,167 *,168- body: BodyTypes = b"",168+ content: ByteOrByteStream = b"",169 headers: HeaderTypes = None,170 stream: bool = False,171 allow_redirects: bool = True,172 ssl: SSLConfig = None,1 unmodified line174 ) -> Response:175 return await self.request(176 "PATCH",177 url,178- body=body,178+ content=content,179 headers=headers,180 stream=stream,181 allow_redirects=allow_redirects,182 ssl=ssl,3 unmodified lines186 async def delete(187 self,188 url: URLTypes,189 *,190- body: BodyTypes = b"",190+ content: ByteOrByteStream = b"",191 headers: HeaderTypes = None,192 stream: bool = False,193 allow_redirects: bool = True,194 ssl: SSLConfig = None,1 unmodified line196 ) -> Response:197 return await self.request(198 "DELETE",199 url,200- body=body,200+ content=content,201 headers=headers,202 stream=stream,203 allow_redirects=allow_redirects,204 ssl=ssl,40 unmodified linesmodified:httpcore/interfaces.py+5 added-5 removed
1 import typing2 from types import TracebackType3 4 from .config import TimeoutConfig5-from .models import URL, Request, Response5+from .models import URL, ByteOrByteStream, HeaderTypes, Request, Response, URLTypes6 7 OptionalTimeout = typing.Optional[TimeoutConfig]8 9 10 class Adapter:11 async def request(12 self,13 method: str,14- url: typing.Union[str, URL],14+ url: URLTypes,15 *,16- headers: typing.List[typing.Tuple[bytes, bytes]] = [],17- body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",16+ headers: HeaderTypes = None,17+ content: ByteOrByteStream = b"",18 **options: typing.Any,19 ) -> Response:20- request = Request(method, url, headers=headers, body=body)20+ request = Request(method, url, headers=headers, content=content)21 self.prepare_request(request)22 response = await self.send(request, **options)23 return response24 43 unmodified linesmodified:httpcore/models.py+17 added-19 removed
19 unmodified lines20 typing.Dict[typing.AnyStr, typing.AnyStr],21 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],22 ]23 24-BodyTypes = typing.Union[bytes, typing.AsyncIterator[bytes]]24+ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]25 26 27 class URL:28 def __init__(self, url: URLTypes) -> None:167 unmodified lines196 return self[key]197 except KeyError:198 return default199 200- def getlist(201- self, key: str, split_commas: bool=False202- ) -> typing.List[str]:200+ def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:201 """202 Return multiple header values.203 204 If there are header values that include commas, then we default to112 unmodified lines317 method: str,318 url: typing.Union[str, URL],319 *,320 headers: HeaderTypes = None,323- body: BodyTypes = b"",321+ content: ByteOrByteStream = b"",322 ):323 self.method = method.upper()324 self.url = URL(url) if isinstance(url, str) else url327- if isinstance(body, bytes):325+ if isinstance(content, bytes):326 self.is_streaming = False329- self.body = body327+ self.content = content328 else:329 self.is_streaming = True332- self.body_aiter = body330+ self.content_aiter = content331 self.headers = Headers(headers)332 333 async def read(self) -> bytes:334 """335 Read and return the response content.336 """339- if not hasattr(self, "body"):340- body = b""337+ if not hasattr(self, "content"):338+ content = b""339 async for part in self.stream():342- body += part343- self.body = body344- return self.body340+ content += part341+ self.content = content342+ return self.content343 344 async def stream(self) -> typing.AsyncIterator[bytes]:345 if self.is_streaming:348- async for part in self.body_aiter:346+ async for part in self.content_aiter:347 yield part350- elif self.body:351- yield self.body348+ elif self.content:349+ yield self.content350 351 def prepare(self) -> None:352 """353 Adds in any default headers. When using the `Client`, this will14 unmodified lines368 auto_headers.append((b"host", self.url.netloc.encode("ascii")))369 if not has_content_length:370 if self.is_streaming:371 auto_headers.append((b"transfer-encoding", b"chunked"))374- elif self.body:375- content_length = str(len(self.body)).encode()372+ elif self.content:373+ content_length = str(len(self.content)).encode()374 auto_headers.append((b"content-length", content_length))375 if not has_accept_encoding:376 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))377 8 unmodified lines386 *,387 reason_phrase: str = None,388 protocol: str = None,389 headers: HeaderTypes = None,392- content: BodyTypes = b"",390+ content: ByteOrByteStream = b"",391 on_close: typing.Callable = None,392 request: Request = None,393 history: typing.List["Response"] = None,394 ):125 unmodified linesmodified:tests/adapters/test_redirects.py+9 added-9 removed
63 unmodified lines64 return Response(codes.see_other, headers=headers, request=request)65 66 elif request.url.path == "/cross_domain_target":67 headers = dict(request.headers.items())68- body = json.dumps({"headers": headers}).encode()69- return Response(codes.ok, content=body, request=request)68+ content = json.dumps({"headers": headers}).encode()69+ return Response(codes.ok, content=content, request=request)70 71 elif request.url.path == "/redirect_body":72- body = await request.read()72+ await request.read()73 headers = {"location": "/redirect_body_target"}74 return Response(codes.permanent_redirect, headers=headers, request=request)75 76 elif request.url.path == "/redirect_body_target":77- body = await request.read()78- body = json.dumps({"body": body.decode()}).encode()77+ content = await request.read()78+ body = json.dumps({"body": content.decode()}).encode()79 return Response(codes.ok, content=body, request=request)80 81 return Response(codes.ok, content=b"Hello, world!", request=request)82 138 unmodified lines221 @pytest.mark.asyncio222 async def test_body_redirect():223 client = RedirectAdapter(MockDispatch())224 url = "https://example.org/redirect_body"225- body = b"Example request body"226- response = await client.request("POST", url, body=body)225+ content = b"Example request body"226+ response = await client.request("POST", url, content=content)227 data = json.loads(response.content.decode())228 assert response.url == URL("https://example.org/redirect_body_target")229 assert data == {"body": "Example request body"}230 2 unmodified lines233 async def test_cannot_redirect_streaming_body():234 client = RedirectAdapter(MockDispatch())235 url = "https://example.org/redirect_body"236 237- async def body():237+ async def streaming_body():238 yield b"Example request body"239 240 with pytest.raises(RedirectBodyUnavailable):241- await client.request("POST", url, body=body())241+ await client.request("POST", url, content=streaming_body())modified:tests/dispatch/test_http2.py+1 added-1 removed
87 unmodified lines88 @pytest.mark.asyncio89 async def test_http2_post_request():90 server = MockServer()91 async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:92- response = await conn.request("POST", "http://example.org", body=b"<data>")92+ response = await conn.request("POST", "http://example.org", content=b"<data>")93 assert response.status_code == 20094 assert json.loads(response.content) == {95 "method": "POST",96 "path": "/",20 unmodified linesmodified:tests/models/test_requests.py+7 added-5 removed
10 unmodified lines11 )12 13 14 def test_content_length_header():15- request = httpcore.Request("POST", "http://example.org", body=b"test 123")15+ request = httpcore.Request("POST", "http://example.org", content=b"test 123")16 request.prepare()17 assert request.headers == httpcore.Headers(18 [19 (b"host", b"example.org"),6 unmodified lines26 def test_transfer_encoding_header():27 async def streaming_body(data):28 yield data # pragma: nocover29 30- body = streaming_body(b"test 123")30+ content = streaming_body(b"test 123")31 32- request = httpcore.Request("POST", "http://example.org", body=body)32+ request = httpcore.Request("POST", "http://example.org", content=content)33 request.prepare()34 assert request.headers == httpcore.Headers(35 [36 (b"host", b"example.org"),26 unmodified lines63 def test_override_content_length_header():64 async def streaming_body(data):65 yield data # pragma: nocover66 67- body = streaming_body(b"test 123")67+ content = streaming_body(b"test 123")68 headers = [(b"content-length", b"8")]69 70- request = httpcore.Request("POST", "http://example.org", body=body, headers=headers)70+ request = httpcore.Request(71+ "POST", "http://example.org", content=content, headers=headers72+ )73 request.prepare()74 assert request.headers == httpcore.Headers(75 [76 (b"host", b"example.org"),27 unmodified linesmodified:tests/test_client.py+2 added-2 removed
14 unmodified lines15 @pytest.mark.asyncio16 async def test_post(server):17 url = "http://127.0.0.1:8000/"18 async with httpcore.Client() as client:19- response = await client.post(url, body=b"Hello, world!")19+ response = await client.post(url, content=b"Hello, world!")20 assert response.status_code == 20021 22 23 @pytest.mark.asyncio22 unmodified lines46 yield b"world!"47 48 async with httpcore.Client() as client:49 response = await client.request(50- "POST", "http://127.0.0.1:8000/", body=hello_world()50+ "POST", "http://127.0.0.1:8000/", content=hello_world()51 )52 assert response.status_code == 200