Skip to content
Myr

Seperate `content=...` and `data=...` parameters (#1266)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Seperate content=... and data=... parameters * Update compatibility.md

authored by Tom Christie · committed by GitHub · parent 54f7708 · Browse files · 17 files+169 added−55 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

17 files+169 added−55 removed

  • tests:+56 added−30 removed
  • other:+113 added−25 removed

17 files+169 added−55 removed

modified:docs/compatibility.md+22 added
modified:docs/quickstart.md+9 added-4 removed
247 unmodified lines
248```249250## Sending Binary Request Data251252For other encodings, you should use either a `bytes` type or a generator253that yields `bytes`.252For other encodings, you should use the `content=...` parameter, passing253either a `bytes` type or a generator that yields `bytes`.254255```pycon256>>> content = b'Hello, world'257>>> r = httpx.post("https://httpbin.org/post", content=content)258```259255You'll probably also want to set a custom `Content-Type` header when uploading260You may also want to set a custom `Content-Type` header when uploading261binary data.262258## Response Status Codes263## Response Status Codes264265We can inspect the HTTP status code of the response:266267```pycon
224 unmodified lines
modified:httpx/_api.py+15 added-2 removed
8 unmodified lines
9 CookieTypes,10 HeaderTypes,11 ProxiesTypes,12 QueryParamTypes,13 RequestContent,14 RequestData,15 RequestFiles,16 TimeoutTypes,17 URLTypes,
5 unmodified lines
23 method: str,24 url: URLTypes,25 *,26 params: QueryParamTypes = None,27 content: RequestContent = None,28 data: RequestData = None,29 files: RequestFiles = None,30 json: typing.Any = None,31 headers: HeaderTypes = None,
15 unmodified lines
47 `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`.48 * **url** - URL for the new `Request` object.49 * **params** - *(optional)* Query parameters to include in the URL, as a50 string, dictionary, or list of two-tuples.49 * **data** - *(optional)* Data to include in the body of the request, as a50 dictionary51 * **content** - *(optional)* Binary content to include in the body of the52 request, as bytes or a byte iterator.53 * **data** - *(optional)* Form data to include in the body of the request,54 as a dictionary.55 * **files** - *(optional)* A dictionary of upload files to include in the56 body of the request.57 * **json** - *(optional)* A JSON serializable object to include in the body58 of the request.
33 unmodified lines
92 ) as client:93 return client.request(94 method=method,95 url=url,96 content=content,97 data=data,98 files=files,99 json=json,100 params=params,
8 unmodified lines
109 method: str,110 url: URLTypes,111 *,112 params: QueryParamTypes = None,113 content: RequestContent = None,114 data: RequestData = None,115 files: RequestFiles = None,116 json: typing.Any = None,117 headers: HeaderTypes = None,
20 unmodified lines
138 request = Request(139 method=method,140 url=url,141 params=params,142 content=content,143 data=data,144 files=files,145 json=json,146 headers=headers,
125 unmodified lines
272273def post(274 url: URLTypes,275 *,276 content: RequestContent = None,277 data: RequestData = None,278 files: RequestFiles = None,279 json: typing.Any = None,280 params: QueryParamTypes = None,
14 unmodified lines
295 """296 return request(297 "POST",298 url,299 content=content,300 data=data,301 files=files,302 json=json,303 params=params,
11 unmodified lines
315316def put(317 url: URLTypes,318 *,319 content: RequestContent = None,320 data: RequestData = None,321 files: RequestFiles = None,322 json: typing.Any = None,323 params: QueryParamTypes = None,
14 unmodified lines
338 """339 return request(340 "PUT",341 url,342 content=content,343 data=data,344 files=files,345 json=json,346 params=params,
11 unmodified lines
358359def patch(360 url: URLTypes,361 *,362 content: RequestContent = None,363 data: RequestData = None,364 files: RequestFiles = None,365 json: typing.Any = None,366 params: QueryParamTypes = None,
14 unmodified lines
381 """382 return request(383 "PATCH",384 url,385 content=content,386 data=data,387 files=files,388 json=json,389 params=params,
48 unmodified lines
modified:httpx/_client.py+21 added
37 unmodified lines
38 CookieTypes,39 HeaderTypes,40 ProxiesTypes,41 QueryParamTypes,42 RequestContent,43 RequestData,44 RequestFiles,45 TimeoutTypes,46 URLTypes,
179 unmodified lines
226 self,227 method: str,228 url: URLTypes,229 *,230 content: RequestContent = None,231 data: RequestData = None,232 files: RequestFiles = None,233 json: typing.Any = None,234 params: QueryParamTypes = None,
15 unmodified lines
250 """251 request = self.build_request(252 method=method,253 url=url,254 content=content,255 data=data,256 files=files,257 json=json,258 params=params,
12 unmodified lines
271 self,272 method: str,273 url: URLTypes,274 *,275 content: RequestContent = None,276 data: RequestData = None,277 files: RequestFiles = None,278 json: typing.Any = None,279 params: QueryParamTypes = None,
17 unmodified lines
297 params = self._merge_queryparams(params)298 return Request(299 method,300 url,301 content=content,302 data=data,303 files=files,304 json=json,305 params=params,
377 unmodified lines
683 self,684 method: str,685 url: URLTypes,686 *,687 content: RequestContent = None,688 data: RequestData = None,689 files: RequestFiles = None,690 json: typing.Any = None,691 params: QueryParamTypes = None,
21 unmodified lines
713 """714 request = self.build_request(715 method=method,716 url=url,717 content=content,718 data=data,719 files=files,720 json=json,721 params=params,
246 unmodified lines
968 def post(969 self,970 url: URLTypes,971 *,972 content: RequestContent = None,973 data: RequestData = None,974 files: RequestFiles = None,975 json: typing.Any = None,976 params: QueryParamTypes = None,
10 unmodified lines
987 """988 return self.request(989 "POST",990 url,991 content=content,992 data=data,993 files=files,994 json=json,995 params=params,
7 unmodified lines
1003 def put(1004 self,1005 url: URLTypes,1006 *,1007 content: RequestContent = None,1008 data: RequestData = None,1009 files: RequestFiles = None,1010 json: typing.Any = None,1011 params: QueryParamTypes = None,
10 unmodified lines
1022 """1023 return self.request(1024 "PUT",1025 url,1026 content=content,1027 data=data,1028 files=files,1029 json=json,1030 params=params,
7 unmodified lines
1038 def patch(1039 self,1040 url: URLTypes,1041 *,1042 content: RequestContent = None,1043 data: RequestData = None,1044 files: RequestFiles = None,1045 json: typing.Any = None,1046 params: QueryParamTypes = None,
10 unmodified lines
1057 """1058 return self.request(1059 "PATCH",1060 url,1061 content=content,1062 data=data,1063 files=files,1064 json=json,1065 params=params,
259 unmodified lines
1325 self,1326 method: str,1327 url: URLTypes,1328 *,1329 content: RequestContent = None,1330 data: RequestData = None,1331 files: RequestFiles = None,1332 json: typing.Any = None,1333 params: QueryParamTypes = None,
21 unmodified lines
1355 """1356 request = self.build_request(1357 method=method,1358 url=url,1359 content=content,1360 data=data,1361 files=files,1362 json=json,1363 params=params,
249 unmodified lines
1613 async def post(1614 self,1615 url: URLTypes,1616 *,1617 content: RequestContent = None,1618 data: RequestData = None,1619 files: RequestFiles = None,1620 json: typing.Any = None,1621 params: QueryParamTypes = None,
10 unmodified lines
1632 """1633 return await self.request(1634 "POST",1635 url,1636 content=content,1637 data=data,1638 files=files,1639 json=json,1640 params=params,
7 unmodified lines
1648 async def put(1649 self,1650 url: URLTypes,1651 *,1652 content: RequestContent = None,1653 data: RequestData = None,1654 files: RequestFiles = None,1655 json: typing.Any = None,1656 params: QueryParamTypes = None,
10 unmodified lines
1667 """1668 return await self.request(1669 "PUT",1670 url,1671 content=content,1672 data=data,1673 files=files,1674 json=json,1675 params=params,
7 unmodified lines
1683 async def patch(1684 self,1685 url: URLTypes,1686 *,1687 content: RequestContent = None,1688 data: RequestData = None,1689 files: RequestFiles = None,1690 json: typing.Any = None,1691 params: QueryParamTypes = None,
10 unmodified lines
1702 """1703 return await self.request(1704 "PATCH",1705 url,1706 content=content,1707 data=data,1708 files=files,1709 json=json,1710 params=params,
135 unmodified lines
modified:httpx/_content_streams.py+41 added-17 removed
6 unmodified lines
78import httpcore910from ._exceptions import StreamConsumed11from ._types import FileContent, FileTypes, RequestData, RequestFiles, ResponseContent11from ._types import (12 FileContent,13 FileTypes,14 RequestContent,15 RequestData,16 RequestFiles,17 ResponseContent,18)19from ._utils import (20 format_form_param,21 guess_content_type,22 peek_filelike_length,
340 unmodified lines
363 yield chunk364365366def encode(367 content: RequestContent = None,368 data: RequestData = None,369 files: RequestFiles = None,370 json: typing.Any = None,371 boundary: bytes = None,372) -> ContentStream:373 """366 Handles encoding the given `data`, `files`, and `json`, returning367 a `ContentStream` implementation.374 Handles encoding the given `content`, `data`, `files`, and `json`,375 returning a `ContentStream` implementation.376 """369 if not data:370 if json is not None:371 return JSONStream(json=json)372 elif files:373 return MultipartStream(data={}, files=files, boundary=boundary)377 if data is not None and not isinstance(data, dict):378 # We prefer to seperate `content=<bytes|byte iterator|bytes aiterator>`379 # for raw request content, and `data=<form data>` for url encoded or380 # multipart form content.381 #382 # However for compat with requests, we *do* still support383 # `data=<bytes...>` usages. We deal with that case here, treating it384 # as if `content=<...>` had been supplied instead.385 content = data386 data = None387388 if content is not None:389 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)397 else:375 return ByteStream(body=b"")376 elif isinstance(data, dict):398 raise TypeError(f"Unexpected type for 'content', {type(content)!r}")399400 elif data:401 if files:402 return MultipartStream(data=data, files=files, boundary=boundary)403 else:404 return URLEncodedStream(data=data)381 elif isinstance(data, (str, bytes)):382 return ByteStream(body=data)383 elif isinstance(data, typing.AsyncIterator):384 return AsyncIteratorStream(aiterator=data)385 elif isinstance(data, typing.Iterator):386 return IteratorStream(iterator=data)405388 raise TypeError(f"Unexpected type for 'data', {type(data)!r}")406 elif files:407 return MultipartStream(data={}, files=files, boundary=boundary)408409 elif json is not None:410 return JSONStream(json=json)411412 return ByteStream(body=b"")413414415def encode_response(content: ResponseContent = None) -> ContentStream:416 if content is None:417 return ByteStream(b"")418 elif isinstance(content, bytes):
7 unmodified lines
modified:httpx/_models.py+3 added-1 removed
39 unmodified lines
40 CookieTypes,41 HeaderTypes,42 PrimitiveData,43 QueryParamTypes,44 RequestContent,45 RequestData,46 RequestFiles,47 ResponseContent,48 URLTypes,
541 unmodified lines
590 *,591 params: QueryParamTypes = None,592 headers: HeaderTypes = None,593 cookies: CookieTypes = None,594 content: RequestContent = None,595 data: RequestData = None,596 files: RequestFiles = None,597 json: typing.Any = None,598 stream: ContentStream = None,
6 unmodified lines
605606 if stream is not None:607 self.stream = stream608 else:607 self.stream = encode(data, files, json)609 self.stream = encode(content, data, files, json)610611 self._prepare()612613 def _prepare(self) -> None:
634 unmodified lines
modified:httpx/_types.py+2 added-1 removed
62 unmodified lines
63 "Auth",64 None,65]6667RequestContent = Union[str, bytes, Iterator[bytes], AsyncIterator[bytes]]68ResponseContent = Union[bytes, Iterator[bytes], AsyncIterator[bytes]]6969RequestData = Union[dict, str, bytes, Iterator[bytes], AsyncIterator[bytes]]70RequestData = dict7172FileContent = Union[IO[str], IO[bytes], str, bytes]73FileTypes = Union[74 # file (or text)
7 unmodified lines
modified:tests/client/test_async_client.py+7 added-7 removed
54 unmodified lines
55@pytest.mark.usefixtures("async_environment")56async def test_post(server):57 url = server.url58 async with httpx.AsyncClient() as client:59 response = await client.post(url, data=b"Hello, world!")59 response = await client.post(url, content=b"Hello, world!")60 assert response.status_code == 200616263@pytest.mark.usefixtures("async_environment")
32 unmodified lines
96 yield b"Hello, "97 yield b"world!"9899 async with httpx.AsyncClient() as client:100 response = await client.request("POST", server.url, data=hello_world())100 response = await client.request("POST", server.url, content=hello_world())101 assert response.status_code == 200102103104@pytest.mark.usefixtures("async_environment")
30 unmodified lines
135136@pytest.mark.usefixtures("async_environment")137async def test_put(server):138 async with httpx.AsyncClient() as client:139 response = await client.put(server.url, data=b"Hello, world!")139 response = await client.put(server.url, content=b"Hello, world!")140 assert response.status_code == 200141142143@pytest.mark.usefixtures("async_environment")144async def test_patch(server):145 async with httpx.AsyncClient() as client:146 response = await client.patch(server.url, data=b"Hello, world!")146 response = await client.patch(server.url, content=b"Hello, world!")147 assert response.status_code == 200148149150@pytest.mark.usefixtures("async_environment")
6 unmodified lines
157158@pytest.mark.usefixtures("async_environment")159async def test_100_continue(server):160 headers = {"Expect": "100-continue"}161 data = b"Echo request body"161 content = b"Echo request body"162163 async with httpx.AsyncClient() as client:164 response = await client.post(165 server.url.copy_with(path="/echo_body"), headers=headers, data=data165 server.url.copy_with(path="/echo_body"), headers=headers, content=content166 )167168 assert response.status_code == 200169 assert response.content == data169 assert response.content == content170171172@pytest.mark.usefixtures("async_environment")173async def test_context_managed_transport():
77 unmodified lines
modified:tests/client/test_client.py+3 added-3 removed
71 unmodified lines
727374def test_post(server):75 with httpx.Client() as client:76 response = client.post(server.url, data=b"Hello, world!")76 response = client.post(server.url, content=b"Hello, world!")77 assert response.status_code == 20078 assert response.reason_phrase == "OK"7980
66 unmodified lines
147148149def test_put(server):150 with httpx.Client() as client:151 response = client.put(server.url, data=b"Hello, world!")151 response = client.put(server.url, content=b"Hello, world!")152 assert response.status_code == 200153 assert response.reason_phrase == "OK"154155156def test_patch(server):157 with httpx.Client() as client:158 response = client.patch(server.url, data=b"Hello, world!")158 response = client.patch(server.url, content=b"Hello, world!")159 assert response.status_code == 200160 assert response.reason_phrase == "OK"161162
113 unmodified lines
modified:tests/client/test_redirects.py+5 added-5 removed
296 unmodified lines
297 A 308 redirect should preserve the request body.298 """299 client = httpx.Client(transport=MockTransport(redirects))300 url = "https://example.org/redirect_body"301 data = b"Example request body"302 response = client.post(url, data=data)301 content = b"Example request body"302 response = client.post(url, content=content)303 assert response.url == "https://example.org/redirect_body_target"304 assert response.json()["body"] == "Example request body"305 assert "content-length" in response.json()["headers"]306
3 unmodified lines
310 A 303 redirect should remove the request body.311 """312 client = httpx.Client(transport=MockTransport(redirects))313 url = "https://example.org/redirect_no_body"314 data = b"Example request body"315 response = client.post(url, data=data)314 content = b"Example request body"315 response = client.post(url, content=content)316 assert response.url == "https://example.org/redirect_body_target"317 assert response.json()["body"] == ""318 assert "content-length" not in response.json()["headers"]319
14 unmodified lines
334 def streaming_body():335 yield b"Example request body" # pragma: nocover336337 with pytest.raises(httpx.RequestBodyUnavailable):338 client.post(url, data=streaming_body())338 client.post(url, content=streaming_body())339340341def test_cross_subdomain_redirect():342 client = httpx.Client(transport=MockTransport(redirects))
72 unmodified lines
modified:tests/models/test_requests.py+1 added-1 removed
12 unmodified lines
13 assert "Content-Length" not in request.headers141516def test_content_length_header():17 request = httpx.Request("POST", "http://example.org", data=b"test 123")17 request = httpx.Request("POST", "http://example.org", content=b"test 123")18 assert request.headers["Content-Length"] == "8"192021def test_url_encoded_data():
120 unmodified lines
modified:tests/test_api.py+4 added-4 removed
10 unmodified lines
11 assert response.http_version == "HTTP/1.1"121314def test_post(server):15 response = httpx.post(server.url, data=b"Hello, world!")15 response = httpx.post(server.url, content=b"Hello, world!")16 assert response.status_code == 20017 assert response.reason_phrase == "OK"1819
2 unmodified lines
22 yield b"Hello"23 yield b", "24 yield b"world!"2526 response = httpx.post(server.url, data=data())26 response = httpx.post(server.url, content=data())27 assert response.status_code == 20028 assert response.reason_phrase == "OK"2930
9 unmodified lines
40 assert response.reason_phrase == "OK"414243def test_put(server):44 response = httpx.put(server.url, data=b"Hello, world!")44 response = httpx.put(server.url, content=b"Hello, world!")45 assert response.status_code == 20046 assert response.reason_phrase == "OK"474849def test_patch(server):50 response = httpx.patch(server.url, data=b"Hello, world!")50 response = httpx.patch(server.url, content=b"Hello, world!")51 assert response.status_code == 20052 assert response.reason_phrase == "OK"5354
19 unmodified lines
modified:tests/test_asgi.py+2 added-2 removed
49 unmodified lines
5051@pytest.mark.usefixtures("async_environment")52async def test_asgi_upload():53 async with httpx.AsyncClient(app=echo_body) as client:54 response = await client.post("http://www.example.org/", data=b"example")54 response = await client.post("http://www.example.org/", content=b"example")5556 assert response.status_code == 20057 assert response.text == "example"58
39 unmodified lines
98 message = await receive()99 disconnect = message.get("type") == "http.disconnect"100101 async with httpx.AsyncClient(app=read_body) as client:102 response = await client.post("http://www.example.org/", data=b"example")102 response = await client.post("http://www.example.org/", content=b"example")103104 assert response.status_code == 200105 assert disconnect
modified:tests/test_content_streams.py+29 added-3 removed
30 unmodified lines
313233@pytest.mark.asyncio34async def test_bytes_content():35 stream = encode(data=b"Hello, world!")35 stream = encode(content=b"Hello, world!")36 sync_content = b"".join([part for part in stream])37 async_content = b"".join([part async for part in stream])3839 assert stream.can_replay()40 assert stream.get_headers() == {"Content-Length": "13"}41 assert sync_content == b"Hello, world!"42 assert async_content == b"Hello, world!"4344 # Support 'data' for compat with requests.45 stream = encode(data=b"Hello, world!") # type: ignore46 sync_content = b"".join([part for part in stream])47 async_content = b"".join([part async for part in stream])4849 assert stream.can_replay()50 assert stream.get_headers() == {"Content-Length": "13"}51 assert sync_content == b"Hello, world!"52 assert async_content == b"Hello, world!"535455@pytest.mark.asyncio56async def test_iterator_content():57 def hello_world():58 yield b"Hello, "59 yield b"world!"6051 stream = encode(data=hello_world())61 stream = encode(content=hello_world())62 content = b"".join([part for part in stream])6364 assert not stream.can_replay()65 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}
4 unmodified lines
7071 with pytest.raises(StreamConsumed):72 [part for part in stream]7374 # Support 'data' for compat with requests.75 stream = encode(data=hello_world()) # type: ignore76 content = b"".join([part for part in stream])7778 assert not stream.can_replay()79 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}80 assert content == b"Hello, world!"818283@pytest.mark.asyncio84async def test_aiterator_content():85 async def hello_world():86 yield b"Hello, "87 yield b"world!"8871 stream = encode(data=hello_world())89 stream = encode(content=hello_world())90 content = b"".join([part async for part in stream])9192 assert not stream.can_replay()93 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}
4 unmodified lines
9899 with pytest.raises(StreamConsumed):100 [part async for part in stream]101102 # Support 'data' for compat with requests.103 stream = encode(data=hello_world()) # type: ignore104 content = b"".join([part async for part in stream])105106 assert not stream.can_replay()107 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}108 assert content == b"Hello, world!"109110111@pytest.mark.asyncio112async def test_json_content():113 stream = encode(json={"Hello": "world!"})114 sync_content = b"".join([part for part in stream])
234 unmodified lines
modified:tests/test_timeouts.py+1 added-1 removed
17 unmodified lines
1819 async with httpx.AsyncClient(timeout=timeout) as client:20 with pytest.raises(httpx.WriteTimeout):21 data = b"*" * 1024 * 1024 * 10022 await client.put(server.url.copy_with(path="/slow_response"), data=data)22 await client.put(server.url.copy_with(path="/slow_response"), content=data)232425@pytest.mark.usefixtures("async_environment")26async def test_connect_timeout(server):
31 unmodified lines
modified:tests/test_wsgi.py+2 added-2 removed
76 unmodified lines
777879def test_wsgi_upload():80 client = httpx.Client(app=echo_body)81 response = client.post("http://www.example.org/", data=b"example")81 response = client.post("http://www.example.org/", content=b"example")82 assert response.status_code == 20083 assert response.text == "example"848586def test_wsgi_upload_with_response_stream():87 client = httpx.Client(app=echo_body_with_response_stream)88 response = client.post("http://www.example.org/", data=b"example")88 response = client.post("http://www.example.org/", content=b"example")89 assert response.status_code == 20090 assert response.text == "example"9192
26 unmodified lines
modified:tests/utils.py+2 added-2 removed
41 unmodified lines
42 port_str = "" if port is None else f":{port}"43 path = raw_path.decode("ascii")4445 request_headers = httpx.Headers(headers)46 data = (46 content = (47 (item for item in stream)48 if stream49 and (50 "Content-Length" in request_headers
5 unmodified lines
56 request = httpx.Request(57 method=method.decode("ascii"),58 url=f"{scheme}://{host}{port_str}{path}",59 headers=request_headers,60 data=data,60 content=content,61 )62 request.read()63 response = self.handler(request)64 return (
47 unmodified lines