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
Provenance
- Commit
8d4f182- Tree
a041a1e- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
2c2d497
9 files changed+319 added−101 removed
modified:httpx/client.py+7 added-6 removed
17 unmodified lines18 TimeoutTypes,19 UnsetType,20 VerifyTypes,21 )22+from .content import RequestContent23 from .dispatch.asgi import ASGIDispatch24 from .dispatch.base import Dispatcher25 from .dispatch.connection_pool import ConnectionPool26 from .dispatch.proxy_http import HTTPProxy473 unmodified lines500 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 request507 508 def redirect_method(self, request: Request, response: Response) -> str:509 """510 When being redirected we may want to change the method of the request59 unmodified lines570 headers.pop("Cookie", None)571 572 return headers573 573- 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.content583 584 async def send_single_request(380 unmodified linesadded:httpx/content.py+171 added
1+import typing2+from json import dumps as json_dumps3+from urllib.parse import urlencode4+5+from .multipart import multipart_encode6+7+RequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]8+9+RequestFiles = 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+]26+27+28+class RequestContent:29+ """30+ Base class for request content.31+ Defaults to a "no request body" implementation.32+ """33+34+ 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 {}39+40+ def can_replay(self) -> bool:41+ """42+ Return `True` if `__aiter__` can be called multiple times.43+44+ We need this in order to determine if we can re-issue a request body45+ when we receive a redirect response.46+ """47+ return True48+49+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:50+ yield b""51+52+ async def aread(self) -> bytes:53+ return b"".join([part async for part in self])54+55+56+class BytesRequestContent(RequestContent):57+ """58+ Request content encoded as plain bytes.59+ """60+61+ def __init__(self, body: typing.Union[str, bytes]) -> None:62+ self.body = body.encode("utf-8") if isinstance(body, str) else body63+64+ def get_headers(self) -> typing.Dict[str, str]:65+ content_length = str(len(self.body))66+ return {"Content-Length": content_length}67+68+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:69+ yield self.body70+71+72+class StreamingRequestContent(RequestContent):73+ """74+ Request content encoded as plain bytes, using an async byte iterator.75+ """76+77+ def __init__(self, aiterator: typing.AsyncIterator[bytes]) -> None:78+ self.aiterator = aiterator79+80+ def can_replay(self) -> bool:81+ return False82+83+ def get_headers(self) -> typing.Dict[str, str]:84+ return {"Transfer-Encoding": "chunked"}85+86+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:87+ async for part in self.aiterator:88+ yield part89+90+91+class JSONRequestContent(RequestContent):92+ """93+ Request content encoded as JSON.94+ """95+96+ def __init__(self, json: typing.Any) -> None:97+ self.body = json_dumps(json).encode("utf-8")98+99+ 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}103+104+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:105+ yield self.body106+107+108+class URLEncodedRequestContent(RequestContent):109+ """110+ Request content as URL encoded form data.111+ """112+113+ def __init__(self, data: dict) -> None:114+ self.body = urlencode(data, doseq=True).encode("utf-8")115+116+ 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}120+121+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:122+ yield self.body123+124+125+class MultipartRequestContent(RequestContent):126+ """127+ Request content as multipart encoded form data.128+ """129+130+ def __init__(self, data: dict, files: dict, boundary: bytes = None) -> None:131+ self.body, self.content_type = multipart_encode(data, files, boundary)132+133+ 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}137+138+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:139+ yield self.body140+141+142+def 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.152+153+ 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 lines12 import chardet13 import rfc398614 15 from .config import USER_AGENT16+from .content import RequestData, RequestFiles, encode17 from .decoders import (18 ACCEPT_ENCODING,19 SUPPORTED_DECODERS,20 Decoder,10 unmodified lines31 ResponseClosed,32 ResponseNotRead,33 StreamConsumed,34 )34-from .multipart import multipart_encode35 from .status_codes import StatusCode36 from .utils import (37 flatten_queryparams,38 guess_json_utf,37 unmodified lines76 ProxiesTypes = typing.Union[77 URLTypes, "Dispatcher", typing.Dict[URLTypes, typing.Union[URLTypes, "Dispatcher"]]78 ]79 80-RequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]81-82-RequestFiles = 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-]99-80 ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]81 82 83 class URL:514 unmodified lines598 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()604 638- 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_type653-605 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)608 609 auto_headers: typing.List[typing.Tuple[bytes, bytes]] = []610 611 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.headers616 617 if not has_host:4 unmodified lines622 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 lines645 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()650 651 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.content654 655 656 class Response:657 def __init__(461 unmodified linesmodified:httpx/multipart.py+5 added-2 removed
93 unmodified lines94 for name, value in files.items():95 yield FileField(name=name, value=value)96 97 98-def multipart_encode(data: dict, files: dict) -> typing.Tuple[bytes, str]:98+def 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))104 105 for field in iter_fields(data, files):106 body.write(b"--%s\r\n" % boundary)107 body.write(field.render_headers())19 unmodified linesmodified:tests/client/test_redirects.py-1 removed
75 unmodified lines76 content = json.dumps({"headers": headers}).encode()77 return Response(codes.OK, content=content, request=request)78 79 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)82 83 elif request.url.path == "/redirect_no_body":270 unmodified linesmodified:tests/dispatch/test_http2.py+5 added-6 removed
9 unmodified lines10 11 from .utils import MockHTTP2Backend12 13 14-def app(request):14+async 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 linesmodified:tests/dispatch/utils.py+9 added-12 removed
51 unmodified lines52 await sleep(self.backend, 0)53 send, self.buffer = self.buffer[:n], self.buffer[n:]54 return send55 56- 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 lines74 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)81 80- async def write(self, data: bytes, timeout) -> None:81- self.write_no_block(data)82-82 async def close(self) -> None:83 pass84 85 def is_connection_dropped(self) -> bool:14 unmodified lines100 Handler for when a data part of the HTTP request is received.101 """102 self.requests[stream_id][-1]["data"] += data103 105- 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 lines121 data = request["data"]122 123 # 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)126 127 # 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.raw60 unmodified lines190 191 def get_http_version(self) -> str:192 return "HTTP/1.1"193 195- 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)198 198- async def write(self, data: bytes, timeout: Timeout = None) -> None:199- if data:200- self.write_no_block(data)201-199 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 linesmodified:tests/models/test_requests.py+6 added-4 removed
16 unmodified lines17 request = httpx.Request("POST", "http://example.org", data=b"test 123")18 assert request.headers["Content-Length"] == "8"19 20 21+@pytest.mark.asyncio21-def test_url_encoded_data():22+async 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"26 27 28+@pytest.mark.asyncio27-def test_json_encoded_data():29+async 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}'33 34 35 def test_transfer_encoding_header():36 async def streaming_body(data):54 unmodified linesadded:tests/test_content.py+109 added
1+import io2+3+import pytest4+5+from httpx.content import encode6+7+8+@pytest.mark.asyncio9+async def test_empty_content():10+ content = encode()11+12+ assert content.can_replay()13+ assert content.get_headers() == {}14+ assert await content.aread() == b""15+16+17+@pytest.mark.asyncio18+async def test_bytes_content():19+ content = encode(data=b"Hello, world!")20+21+ assert content.can_replay()22+ assert content.get_headers() == {"Content-Length": "13"}23+ assert await content.aread() == b"Hello, world!"24+25+26+@pytest.mark.asyncio27+async def test_aiterator_content():28+ async def hello_world():29+ yield b"Hello, "30+ yield b"world!"31+32+ content = encode(data=hello_world())33+34+ assert not content.can_replay()35+ assert content.get_headers() == {"Transfer-Encoding": "chunked"}36+ assert await content.aread() == b"Hello, world!"37+38+39+@pytest.mark.asyncio40+async def test_json_content():41+ content = encode(json={"Hello": "world!"})42+43+ 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!"}'49+50+51+@pytest.mark.asyncio52+async def test_urlencoded_content():53+ content = encode(data={"Hello": "world!"})54+55+ 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"61+62+63+@pytest.mark.asyncio64+async def test_multipart_files_content():65+ files = {"file": io.BytesIO(b"<file content>")}66+ content = encode(files=files, boundary=b"+++")67+68+ 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+ )83+84+85+@pytest.mark.asyncio86+async 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"+++")90+91+ 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+ )