Skip to content
Myr

Added RequestContent (#636)

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

* Request Content * Added RequestContent interface * Docstrings on 'encode(data, files, json)' * Update httpx/content.py Co-Authored-By: Florimond Manca <florimond.manca@gmail.com> * can_rewind -> can_replay

authored by Tom Christie · committed by GitHub · parent 2c2d497 · Browse files · 9 files+319 added−101 removed
This commit

State

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

Diff stats

9 files+319 added−101 removed

  • tests:+129 added−23 removed
  • other:+190 added−78 removed

9 files+319 added−101 removed

modified:httpx/client.py+7 added-6 removed
17 unmodified lines
18 TimeoutTypes,19 UnsetType,20 VerifyTypes,21)22from .content import RequestContent23from .dispatch.asgi import ASGIDispatch24from .dispatch.base import Dispatcher25from .dispatch.connection_pool import ConnectionPool26from .dispatch.proxy_http import HTTPProxy
473 unmodified lines
500 url = self.redirect_url(request, response)501 headers = self.redirect_headers(request, url, method)502 content = self.redirect_content(request, method)503 cookies = Cookies(self.cookies)503 return Request(504 method=method, url=url, headers=headers, data=content, cookies=cookies505 )504 request = Request(method=method, url=url, headers=headers, cookies=cookies)505 request.content = content506 return request507508 def redirect_method(self, request: Request, response: Response) -> str:509 """510 When being redirected we may want to change the method of the request
59 unmodified lines
570 headers.pop("Cookie", None)571572 return headers573573 def redirect_content(self, request: Request, method: str) -> bytes:574 def redirect_content(self, request: Request, method: str) -> RequestContent:575 """576 Return the body that should be used for the redirect request.577 """578 if method != request.method and method == "GET":578 return b""579 if request.is_streaming:579 return RequestContent()580 if not request.content.can_replay():581 raise RedirectBodyUnavailable()582 return request.content583584 async def send_single_request(
380 unmodified lines
added:httpx/content.py+171 added
1import typing2from json import dumps as json_dumps3from urllib.parse import urlencode45from .multipart import multipart_encode67RequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]89RequestFiles = typing.Dict[10 str,11 typing.Union[12 # file (or str)13 typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],14 # (filename, file (or str))15 typing.Tuple[16 typing.Optional[str], typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],17 ],18 # (filename, file (or str), content_type)19 typing.Tuple[20 typing.Optional[str],21 typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],22 typing.Optional[str],23 ],24 ],25]262728class RequestContent:29 """30 Base class for request content.31 Defaults to a "no request body" implementation.32 """3334 def get_headers(self) -> typing.Dict[str, str]:35 """36 Return a dictionary of request headers that are implied by the encoding.37 """38 return {}3940 def can_replay(self) -> bool:41 """42 Return `True` if `__aiter__` can be called multiple times.4344 We need this in order to determine if we can re-issue a request body45 when we receive a redirect response.46 """47 return True4849 async def __aiter__(self) -> typing.AsyncIterator[bytes]:50 yield b""5152 async def aread(self) -> bytes:53 return b"".join([part async for part in self])545556class BytesRequestContent(RequestContent):57 """58 Request content encoded as plain bytes.59 """6061 def __init__(self, body: typing.Union[str, bytes]) -> None:62 self.body = body.encode("utf-8") if isinstance(body, str) else body6364 def get_headers(self) -> typing.Dict[str, str]:65 content_length = str(len(self.body))66 return {"Content-Length": content_length}6768 async def __aiter__(self) -> typing.AsyncIterator[bytes]:69 yield self.body707172class StreamingRequestContent(RequestContent):73 """74 Request content encoded as plain bytes, using an async byte iterator.75 """7677 def __init__(self, aiterator: typing.AsyncIterator[bytes]) -> None:78 self.aiterator = aiterator7980 def can_replay(self) -> bool:81 return False8283 def get_headers(self) -> typing.Dict[str, str]:84 return {"Transfer-Encoding": "chunked"}8586 async def __aiter__(self) -> typing.AsyncIterator[bytes]:87 async for part in self.aiterator:88 yield part899091class JSONRequestContent(RequestContent):92 """93 Request content encoded as JSON.94 """9596 def __init__(self, json: typing.Any) -> None:97 self.body = json_dumps(json).encode("utf-8")9899 def get_headers(self) -> typing.Dict[str, str]:100 content_length = str(len(self.body))101 content_type = "application/json"102 return {"Content-Length": content_length, "Content-Type": content_type}103104 async def __aiter__(self) -> typing.AsyncIterator[bytes]:105 yield self.body106107108class URLEncodedRequestContent(RequestContent):109 """110 Request content as URL encoded form data.111 """112113 def __init__(self, data: dict) -> None:114 self.body = urlencode(data, doseq=True).encode("utf-8")115116 def get_headers(self) -> typing.Dict[str, str]:117 content_length = str(len(self.body))118 content_type = "application/x-www-form-urlencoded"119 return {"Content-Length": content_length, "Content-Type": content_type}120121 async def __aiter__(self) -> typing.AsyncIterator[bytes]:122 yield self.body123124125class MultipartRequestContent(RequestContent):126 """127 Request content as multipart encoded form data.128 """129130 def __init__(self, data: dict, files: dict, boundary: bytes = None) -> None:131 self.body, self.content_type = multipart_encode(data, files, boundary)132133 def get_headers(self) -> typing.Dict[str, str]:134 content_length = str(len(self.body))135 content_type = self.content_type136 return {"Content-Length": content_length, "Content-Type": content_type}137138 async def __aiter__(self) -> typing.AsyncIterator[bytes]:139 yield self.body140141142def encode(143 data: RequestData = None,144 files: RequestFiles = None,145 json: typing.Any = None,146 boundary: bytes = None,147) -> RequestContent:148 """149 Handles encoding the given `data`, `files`, and `json`, returning150 a `RequestContent` implementation which provides a byte iterator onto151 the content, as well as `.is_rewindable()` and `.get_headers()` interfaces.152153 The `boundary` argument is also included for reproducible test cases154 when working with multipart data.155 """156 if data is None:157 if json is not None:158 return JSONRequestContent(json)159 elif files:160 return MultipartRequestContent({}, files, boundary=boundary)161 else:162 return RequestContent()163 elif isinstance(data, dict):164 if files is not None:165 return MultipartRequestContent(data, files, boundary=boundary)166 else:167 return URLEncodedRequestContent(data)168 elif isinstance(data, (str, bytes)):169 return BytesRequestContent(data)170 else:171 return StreamingRequestContent(data)
modified:httpx/models.py+7 added-70 removed
11 unmodified lines
12import chardet13import rfc39861415from .config import USER_AGENT16from .content import RequestData, RequestFiles, encode17from .decoders import (18 ACCEPT_ENCODING,19 SUPPORTED_DECODERS,20 Decoder,
10 unmodified lines
31 ResponseClosed,32 ResponseNotRead,33 StreamConsumed,34)34from .multipart import multipart_encode35from .status_codes import StatusCode36from .utils import (37 flatten_queryparams,38 guess_json_utf,
37 unmodified lines
76ProxiesTypes = typing.Union[77 URLTypes, "Dispatcher", typing.Dict[URLTypes, typing.Union[URLTypes, "Dispatcher"]]78]7980RequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]8182RequestFiles = typing.Dict[83 str,84 typing.Union[85 # file (or str)86 typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],87 # (filename, file (or str))88 typing.Tuple[89 typing.Optional[str], typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],90 ],91 # (filename, file (or str), content_type)92 typing.Tuple[93 typing.Optional[str],94 typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],95 typing.Optional[str],96 ],97 ],98]9980ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]818283class URL:
514 unmodified lines
598 self.headers = Headers(headers)599 if cookies:600 self._cookies = Cookies(cookies)601 self._cookies.set_cookie_header(self)622 if data is None or isinstance(data, dict):623 content, content_type = self.encode_data(data, files, json)624 self.is_streaming = False625 self.content = content626 if content_type:627 self.headers.setdefault("Content-Type", content_type)628 elif isinstance(data, (str, bytes)):629 data = data.encode("utf-8") if isinstance(data, str) else data630 self.is_streaming = False631 self.content = data632 else:633 assert hasattr(data, "__aiter__")634 self.is_streaming = True635 self.content_aiter = data602 self.content = encode(data, files, json)603 self.prepare()604638 def encode_data(639 self, data: dict = None, files: RequestFiles = None, json: typing.Any = None640 ) -> typing.Tuple[bytes, str]:641 if json is not None:642 content = jsonlib.dumps(json).encode("utf-8")643 content_type = "application/json"644 elif files is not None:645 content, content_type = multipart_encode(data or {}, files)646 elif data is not None:647 content = urlencode(data, doseq=True).encode("utf-8")648 content_type = "application/x-www-form-urlencoded"649 else:650 content = b""651 content_type = ""652 return content, content_type653605 def prepare(self) -> None:655 content: typing.Optional[bytes] = getattr(self, "content", None)656 is_streaming = getattr(self, "is_streaming", False)606 for key, value in self.content.get_headers().items():607 self.headers.setdefault(key, value)608609 auto_headers: typing.List[typing.Tuple[bytes, bytes]] = []610611 has_host = "host" in self.headers612 has_user_agent = "user-agent" in self.headers613 has_accept = "accept" in self.headers663 has_content_length = (664 "content-length" in self.headers or "transfer-encoding" in self.headers665 )614 has_accept_encoding = "accept-encoding" in self.headers615 has_connection = "connection" in self.headers616617 if not has_host:
4 unmodified lines
622 if not has_user_agent:623 auto_headers.append((b"user-agent", USER_AGENT.encode("ascii")))624 if not has_accept:625 auto_headers.append((b"accept", b"*/*"))678 if not has_content_length:679 if is_streaming:680 auto_headers.append((b"transfer-encoding", b"chunked"))681 elif content:682 content_length = str(len(content)).encode()683 auto_headers.append((b"content-length", content_length))626 if not has_accept_encoding:627 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))628 if not has_connection:629 auto_headers.append((b"connection", b"keep-alive"))
15 unmodified lines
645 async def read(self) -> bytes:646 """647 Read and return the request content.648 """707 if not hasattr(self, "content"):708 self.content = b"".join([part async for part in self.stream()])709 return self.content649 return await self.content.aread()650651 async def stream(self) -> typing.AsyncIterator[bytes]:712 if self.is_streaming:713 async for part in self.content_aiter:714 yield part652 async for part in self.content:653 yield part715 elif self.content:716 yield self.content654655656class Response:657 def __init__(
461 unmodified lines
modified:httpx/multipart.py+5 added-2 removed
93 unmodified lines
94 for name, value in files.items():95 yield FileField(name=name, value=value)969798def multipart_encode(data: dict, files: dict) -> typing.Tuple[bytes, str]:98def multipart_encode(99 data: dict, files: dict, boundary: bytes = None100) -> typing.Tuple[bytes, str]:101 body = BytesIO()102 if boundary is None:100 boundary = binascii.hexlify(os.urandom(16))103 boundary = binascii.hexlify(os.urandom(16))104105 for field in iter_fields(data, files):106 body.write(b"--%s\r\n" % boundary)107 body.write(field.render_headers())
19 unmodified lines
modified:tests/client/test_redirects.py-1 removed
75 unmodified lines
76 content = json.dumps({"headers": headers}).encode()77 return Response(codes.OK, content=content, request=request)7879 elif request.url.path == "/redirect_body":80 await request.read()80 headers = {"location": "/redirect_body_target"}81 return Response(codes.PERMANENT_REDIRECT, headers=headers, request=request)8283 elif request.url.path == "/redirect_no_body":
270 unmodified lines
modified:tests/dispatch/test_http2.py+5 added-6 removed
9 unmodified lines
1011from .utils import MockHTTP2Backend121314def app(request):14async def app(request):15 method = request.method16 path = request.url.path17 body = await request.read()18 content = json.dumps(16 {17 "method": request.method,18 "path": request.url.path,19 "body": request.content.decode(),20 }19 {"method": method, "path": path, "body": body.decode()}20 ).encode()21 headers = {"Content-Length": str(len(content))}22 return Response(200, headers=headers, content=content)23
126 unmodified lines
modified:tests/dispatch/utils.py+9 added-12 removed
51 unmodified lines
52 await sleep(self.backend, 0)53 send, self.buffer = self.buffer[:n], self.buffer[n:]54 return send5556 def write_no_block(self, data: bytes) -> None:56 async def write(self, data: bytes, timeout) -> None:57 if not data:58 return59 events = self.conn.receive_data(data)60 self.buffer += self.conn.data_to_send()61 for event in events:62 if isinstance(event, h2.events.RequestReceived):
11 unmodified lines
74 flow_control_consumed, event.stream_id75 )76 self.buffer += self.conn.data_to_send()77 elif isinstance(event, h2.events.StreamEnded):76 self.stream_complete(event.stream_id)78 await self.stream_complete(event.stream_id)79 elif isinstance(event, h2.events.RemoteSettingsChanged):80 self.settings_changed.append(event)8180 async def write(self, data: bytes, timeout) -> None:81 self.write_no_block(data)8282 async def close(self) -> None:83 pass8485 def is_connection_dropped(self) -> bool:
14 unmodified lines
100 Handler for when a data part of the HTTP request is received.101 """102 self.requests[stream_id][-1]["data"] += data103105 def stream_complete(self, stream_id):104 async def stream_complete(self, stream_id):105 """106 Handler for when the HTTP request is completed.107 """108 request = self.requests[stream_id].pop(0)
12 unmodified lines
121 data = request["data"]122123 # Call out to the app.124 request = Request(method, url, headers=headers, data=data)126 response = self.app(request)125 response = await self.app(request)126127 # Write the response to the buffer.128 status_code_bytes = str(response.status_code).encode("ascii")129 response_headers = [(b":status", status_code_bytes)] + response.headers.raw
60 unmodified lines
190191 def get_http_version(self) -> str:192 return "HTTP/1.1"193195 def write_no_block(self, data: bytes) -> None:194 async def write(self, data: bytes, timeout) -> None:195 if not data:196 return197 self.backend.received_data.append(data)198198 async def write(self, data: bytes, timeout: Timeout = None) -> None:199 if data:200 self.write_no_block(data)201199 async def read(self, n, timeout, flag=None) -> bytes:200 await sleep(self.backend.backend, 0)201 if not self.backend.data_to_send:202 return b""
7 unmodified lines
modified:tests/models/test_requests.py+6 added-4 removed
16 unmodified lines
17 request = httpx.Request("POST", "http://example.org", data=b"test 123")18 assert request.headers["Content-Length"] == "8"192021@pytest.mark.asyncio21def test_url_encoded_data():22async def test_url_encoded_data():23 request = httpx.Request("POST", "http://example.org", data={"test": "123"})24 assert request.headers["Content-Type"] == "application/x-www-form-urlencoded"24 assert request.content == b"test=123"25 assert await request.content.aread() == b"test=123"262728@pytest.mark.asyncio27def test_json_encoded_data():29async def test_json_encoded_data():30 request = httpx.Request("POST", "http://example.org", json={"test": 123})31 assert request.headers["Content-Type"] == "application/json"30 assert request.content == b'{"test": 123}'32 assert await request.content.aread() == b'{"test": 123}'333435def test_transfer_encoding_header():36 async def streaming_body(data):
54 unmodified lines
added:tests/test_content.py+109 added
1import io23import pytest45from httpx.content import encode678@pytest.mark.asyncio9async def test_empty_content():10 content = encode()1112 assert content.can_replay()13 assert content.get_headers() == {}14 assert await content.aread() == b""151617@pytest.mark.asyncio18async def test_bytes_content():19 content = encode(data=b"Hello, world!")2021 assert content.can_replay()22 assert content.get_headers() == {"Content-Length": "13"}23 assert await content.aread() == b"Hello, world!"242526@pytest.mark.asyncio27async def test_aiterator_content():28 async def hello_world():29 yield b"Hello, "30 yield b"world!"3132 content = encode(data=hello_world())3334 assert not content.can_replay()35 assert content.get_headers() == {"Transfer-Encoding": "chunked"}36 assert await content.aread() == b"Hello, world!"373839@pytest.mark.asyncio40async def test_json_content():41 content = encode(json={"Hello": "world!"})4243 assert content.can_replay()44 assert content.get_headers() == {45 "Content-Length": "19",46 "Content-Type": "application/json",47 }48 assert await content.aread() == b'{"Hello": "world!"}'495051@pytest.mark.asyncio52async def test_urlencoded_content():53 content = encode(data={"Hello": "world!"})5455 assert content.can_replay()56 assert content.get_headers() == {57 "Content-Length": "14",58 "Content-Type": "application/x-www-form-urlencoded",59 }60 assert await content.aread() == b"Hello=world%21"616263@pytest.mark.asyncio64async def test_multipart_files_content():65 files = {"file": io.BytesIO(b"<file content>")}66 content = encode(files=files, boundary=b"+++")6768 assert content.can_replay()69 assert content.get_headers() == {70 "Content-Length": "138",71 "Content-Type": "multipart/form-data; boundary=+++",72 }73 assert await content.aread() == b"".join(74 [75 b"--+++\r\n",76 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',77 b"Content-Type: application/octet-stream\r\n",78 b"\r\n",79 b"<file content>\r\n",80 b"--+++--\r\n",81 ]82 )838485@pytest.mark.asyncio86async def test_multipart_data_and_files_content():87 data = {"message": "Hello, world!"}88 files = {"file": io.BytesIO(b"<file content>")}89 content = encode(data=data, files=files, boundary=b"+++")9091 assert content.can_replay()92 assert content.get_headers() == {93 "Content-Length": "210",94 "Content-Type": "multipart/form-data; boundary=+++",95 }96 assert await content.aread() == b"".join(97 [98 b"--+++\r\n",99 b'Content-Disposition: form-data; name="message"\r\n',100 b"\r\n",101 b"Hello, world!\r\n",102 b"--+++\r\n",103 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',104 b"Content-Type: application/octet-stream\r\n",105 b"\r\n",106 b"<file content>\r\n",107 b"--+++--\r\n",108 ]109 )