Use Streams API for both requests and responses. (#648)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Internal ContentStreams API
authored by Tom Christie · committed by GitHub · parent 36af9d9 · Browse files · 18 files·+511 added−474 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
18 files+511 added−474 removed
- tests:+158 added−138 removed
- other:+353 added−336 removed
Provenance
- Commit
cee1fcc- Tree
c23d907- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
36af9d9
18 files changed+511 added−474 removed
modified:httpx/dispatch/asgi.py+7 added-3 removed
1 import typing2 3 from ..config import CertTypes, TimeoutTypes, VerifyTypes4+from ..content_streams import ByteStream5 from ..models import Request, Response6 from .base import Dispatcher7 8 68 unmodified lines77 }78 status_code = None79 headers = None80 body_parts = []80- request_stream = request.stream()81 response_started = False82 response_complete = False83 84+ request_body_chunks = request.stream.__aiter__()85+86 async def receive() -> dict:87 try:86- body = await request_stream.__anext__()88+ body = await request_body_chunks.__anext__()89 except StopAsyncIteration:90 return {"type": "http.request", "body": b"", "more_body": False}91 return {"type": "http.request", "body": body, "more_body": True}92 28 unmodified lines121 assert response_complete122 assert status_code is not None123 assert headers is not None124 125+ stream = ByteStream(b"".join(body_parts))126+127 return Response(128 status_code=status_code,129 http_version="HTTP/1.1",130 headers=headers,127- content=b"".join(body_parts),131+ stream=stream,132 request=request,133 )modified:httpx/dispatch/http11.py+7 added-4 removed
2 unmodified lines3 import h114 5 from ..concurrency.base import BaseSocketStream6 from ..config import Timeout7+from ..content_streams import AsyncIteratorStream8 from ..exceptions import ConnectionClosed, ProtocolError9 from ..models import Request, Response10 from ..utils import get_logger11 from .base import OpenConnection38 unmodified lines50 51 await self._send_request(request, timeout)52 await self._send_request_body(request, timeout)53 http_version, status_code, headers = await self._receive_response(timeout)53- content = self._receive_response_data(timeout)54+ stream = AsyncIteratorStream(55+ aiterator=self._receive_response_data(timeout),56+ close_func=self.response_closed,57+ )58 59 return Response(60 status_code=status_code,61 http_version=http_version,62 headers=headers,59- content=content,60- on_close=self.response_closed,63+ stream=stream,64 request=request,65 )66 67 async def close(self) -> None:27 unmodified lines95 Send the request body to the network.96 """97 try:98 # Send the request body.96- async for chunk in request.stream():99+ async for chunk in request.stream:100 logger.trace(f"send_data data=Data(<{len(chunk)} bytes>)")101 event = h11.Data(data=chunk)102 await self._send_event(event, timeout)103 104 unmodified linesmodified:httpx/dispatch/http2.py+7 added-4 removed
10 unmodified lines11 ConcurrencyBackend,12 lookup_backend,13 )14 from ..config import Timeout15+from ..content_streams import AsyncIteratorStream16 from ..exceptions import ProtocolError17 from ..models import Request, Response18 from ..utils import get_logger19 from .base import OpenConnection189 unmodified lines209 await self.send_body(request, timeout)210 211 # Receive the response.212 status_code, headers = await self.receive_response(timeout)212- content = self.body_iter(timeout)213+ stream = AsyncIteratorStream(214+ aiterator=self.body_iter(timeout), close_func=self.close215+ )216+217 return Response(218 status_code=status_code,219 http_version="HTTP/2",220 headers=headers,217- content=content,218- on_close=self.close,221+ stream=stream,222 request=request,223 )224 225 async def send_headers(self, request: Request, timeout: Timeout) -> None:14 unmodified lines240 await self.connection.send_headers(self.stream_id, headers, timeout)241 242 async def send_body(self, request: Request, timeout: Timeout) -> None:243 logger.trace(f"send_body stream_id={self.stream_id}")241- async for data in request.stream():244+ async for data in request.stream:245 while data:246 max_flow = await self.connection.wait_for_outgoing_flow(247 self.stream_id, timeout248 )41 unmodified linesmodified:httpx/dispatch/proxy_http.py+3 added-2 removed
165 unmodified lines166 request=proxy_request,167 response=proxy_response,168 )169 else:170- proxy_response.on_close = None171- await proxy_response.read()170+ # Hack to ingest the response, without closing it.171+ async for chunk in proxy_response._raw_stream:172+ pass173 174 return connection175 176 def should_forward_origin(self, origin: Origin) -> bool:37 unmodified linesmodified:httpx/client.py+11 added-9 removed
17 unmodified lines18 TimeoutTypes,19 UnsetType,20 VerifyTypes,21 )22-from .content import RequestContent22+from .content_streams import ContentStream23 from .dispatch.asgi import ASGIDispatch24 from .dispatch.base import Dispatcher25 from .dispatch.connection_pool import ConnectionPool26 from .dispatch.proxy_http import HTTPProxy467 unmodified lines494 """495 method = self.redirect_method(request, response)496 url = self.redirect_url(request, response)497 headers = self.redirect_headers(request, url, method)498- content = self.redirect_content(request, method)498+ stream = self.redirect_stream(request, method)499 cookies = Cookies(self.cookies)500- request = Request(method=method, url=url, headers=headers, cookies=cookies)501- request.content = content502- return request500+ return Request(501+ method=method, url=url, headers=headers, cookies=cookies, stream=stream502+ )503 504 def redirect_method(self, request: Request, response: Response) -> str:505 """506 When being redirected we may want to change the method of the request59 unmodified lines566 headers.pop("Cookie", None)567 568 return headers569 570- def redirect_content(self, request: Request, method: str) -> RequestContent:570+ def redirect_stream(571+ self, request: Request, method: str572+ ) -> typing.Optional[ContentStream]:573 """574 Return the body that should be used for the redirect request.575 """576 if method != request.method and method == "GET":575- return RequestContent()576- if not request.content.can_replay():577+ return None578+ if not request.stream.can_replay():579 raise RedirectBodyUnavailable()578- return request.content580+ return request.stream581 582 async def send_handling_auth(583 self,584 request: Request,401 unmodified linesadded:httpx/content_streams.py+279 added
1+import binascii2+import mimetypes3+import os4+import typing5+from io import BytesIO6+from json import dumps as json_dumps7+from pathlib import Path8+from urllib.parse import urlencode9+10+from .utils import format_form_param11+12+RequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]13+14+RequestFiles = typing.Dict[15+ str,16+ typing.Union[17+ # file (or str)18+ typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],19+ # (filename, file (or str))20+ typing.Tuple[21+ typing.Optional[str], typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],22+ ],23+ # (filename, file (or str), content_type)24+ typing.Tuple[25+ typing.Optional[str],26+ typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],27+ typing.Optional[str],28+ ],29+ ],30+]31+32+33+class ContentStream:34+ def get_headers(self) -> typing.Dict[str, str]:35+ """36+ Return a dictionary of 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 cases such determining if we can re-issue a request45+ body 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 aclose(self) -> None:53+ pass54+55+56+class ByteStream(ContentStream):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+ if not self.body:66+ return {}67+ content_length = str(len(self.body))68+ return {"Content-Length": content_length}69+70+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:71+ yield self.body72+73+74+class AsyncIteratorStream(ContentStream):75+ """76+ Request content encoded as plain bytes, using an async byte iterator.77+ """78+79+ def __init__(80+ self, aiterator: typing.AsyncIterator[bytes], close_func: typing.Callable = None81+ ) -> None:82+ self.aiterator = aiterator83+ self.close_func = close_func84+85+ def can_replay(self) -> bool:86+ return False87+88+ def get_headers(self) -> typing.Dict[str, str]:89+ return {"Transfer-Encoding": "chunked"}90+91+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:92+ async for part in self.aiterator:93+ yield part94+95+ async def aclose(self) -> None:96+ if self.close_func is not None:97+ await self.close_func()98+99+100+class JSONStream(ContentStream):101+ """102+ Request content encoded as JSON.103+ """104+105+ def __init__(self, json: typing.Any) -> None:106+ self.body = json_dumps(json).encode("utf-8")107+108+ def get_headers(self) -> typing.Dict[str, str]:109+ content_length = str(len(self.body))110+ content_type = "application/json"111+ return {"Content-Length": content_length, "Content-Type": content_type}112+113+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:114+ yield self.body115+116+117+class URLEncodedStream(ContentStream):118+ """119+ Request content as URL encoded form data.120+ """121+122+ def __init__(self, data: dict) -> None:123+ self.body = urlencode(data, doseq=True).encode("utf-8")124+125+ def get_headers(self) -> typing.Dict[str, str]:126+ content_length = str(len(self.body))127+ content_type = "application/x-www-form-urlencoded"128+ return {"Content-Length": content_length, "Content-Type": content_type}129+130+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:131+ yield self.body132+133+134+class MultipartStream(ContentStream):135+ """136+ Request content as multipart encoded form data.137+ """138+139+ class DataField:140+ """141+ A single form field item, within a multipart form field.142+ """143+144+ def __init__(self, name: str, value: typing.Union[str, bytes]) -> None:145+ if not isinstance(name, str):146+ raise TypeError("Invalid type for name. Expected str.")147+ if not isinstance(value, (str, bytes)):148+ raise TypeError("Invalid type for value. Expected str or bytes.")149+ self.name = name150+ self.value = value151+152+ def render_headers(self) -> bytes:153+ name = format_form_param("name", self.name)154+ return b"".join([b"Content-Disposition: form-data; ", name, b"\r\n\r\n"])155+156+ def render_data(self) -> bytes:157+ return (158+ self.value159+ if isinstance(self.value, bytes)160+ else self.value.encode("utf-8")161+ )162+163+ class FileField:164+ """165+ A single file field item, within a multipart form field.166+ """167+168+ def __init__(169+ self, name: str, value: typing.Union[typing.IO[typing.AnyStr], tuple]170+ ) -> None:171+ self.name = name172+ if not isinstance(value, tuple):173+ self.filename = Path(str(getattr(value, "name", "upload"))).name174+ self.file = (175+ value176+ ) # type: typing.Union[typing.IO[str], typing.IO[bytes]]177+ self.content_type = self.guess_content_type()178+ else:179+ self.filename = value[0]180+ self.file = value[1]181+ self.content_type = (182+ value[2] if len(value) > 2 else self.guess_content_type()183+ )184+185+ def guess_content_type(self) -> typing.Optional[str]:186+ if self.filename:187+ return (188+ mimetypes.guess_type(self.filename)[0] or "application/octet-stream"189+ )190+ else:191+ return None192+193+ def render_headers(self) -> bytes:194+ parts = [195+ b"Content-Disposition: form-data; ",196+ format_form_param("name", self.name),197+ ]198+ if self.filename:199+ filename = format_form_param("filename", self.filename)200+ parts.extend([b"; ", filename])201+ if self.content_type is not None:202+ content_type = self.content_type.encode()203+ parts.extend([b"\r\nContent-Type: ", content_type])204+ parts.append(b"\r\n\r\n")205+ return b"".join(parts)206+207+ def render_data(self) -> bytes:208+ if isinstance(self.file, str):209+ content = self.file210+ else:211+ content = self.file.read()212+ return content.encode("utf-8") if isinstance(content, str) else content213+214+ def __init__(self, data: dict, files: dict, boundary: bytes = None) -> None:215+ body = BytesIO()216+ if boundary is None:217+ boundary = binascii.hexlify(os.urandom(16))218+219+ for field in self.iter_fields(data, files):220+ body.write(b"--%s\r\n" % boundary)221+ body.write(field.render_headers())222+ body.write(field.render_data())223+ body.write(b"\r\n")224+225+ body.write(b"--%s--\r\n" % boundary)226+227+ self.content_type = "multipart/form-data; boundary=%s" % boundary.decode(228+ "ascii"229+ )230+ self.body = body.getvalue()231+232+ def iter_fields(233+ self, data: dict, files: dict234+ ) -> typing.Iterator[typing.Union["FileField", "DataField"]]:235+ for name, value in data.items():236+ if isinstance(value, (list, dict)):237+ for item in value:238+ yield self.DataField(name=name, value=item)239+ else:240+ yield self.DataField(name=name, value=value)241+242+ for name, value in files.items():243+ yield self.FileField(name=name, value=value)244+245+ def get_headers(self) -> typing.Dict[str, str]:246+ content_length = str(len(self.body))247+ content_type = self.content_type248+ return {"Content-Length": content_length, "Content-Type": content_type}249+250+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:251+ yield self.body252+253+254+def encode(255+ data: RequestData = None,256+ files: RequestFiles = None,257+ json: typing.Any = None,258+ boundary: bytes = None,259+) -> ContentStream:260+ """261+ Handles encoding the given `data`, `files`, and `json`, returning262+ a `ContentStream` implementation.263+ """264+ if data is None:265+ if json is not None:266+ return JSONStream(json=json)267+ elif files:268+ return MultipartStream(data={}, files=files, boundary=boundary)269+ else:270+ return ByteStream(body=b"")271+ elif isinstance(data, dict):272+ if files is not None:273+ return MultipartStream(data=data, files=files, boundary=boundary)274+ else:275+ return URLEncodedStream(data=data)276+ elif isinstance(data, (str, bytes)):277+ return ByteStream(body=data)278+ else:279+ return AsyncIteratorStream(aiterator=data)deleted:httpx/content.py-171 removed
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+16 added-17 removed
11 unmodified lines12 import chardet13 import rfc398614 15 from .config import USER_AGENT16-from .content import RequestData, RequestFiles, encode16+from .content_streams import ContentStream, RequestData, RequestFiles, encode17 from .decoders import (18 ACCEPT_ENCODING,19 SUPPORTED_DECODERS,20 Decoder,49 unmodified lines70 ProxiesTypes = typing.Union[71 URLTypes, "Dispatcher", typing.Dict[URLTypes, typing.Union[URLTypes, "Dispatcher"]]72 ]73 74-ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]74 76-75 class URL:76 def __init__(77 self,78 url: URLTypes,513 unmodified lines592 cookies: CookieTypes = None,593 data: RequestData = None,594 files: RequestFiles = None,595 json: typing.Any = None,596+ stream: ContentStream = None,597 ):598 self.method = method.upper()599 self.url = URL(url, params=params)600 self.headers = Headers(headers)601 if cookies:602 self._cookies = Cookies(cookies)603 self._cookies.set_cookie_header(self)604+605+ if stream is not None:606+ self.stream = stream607+ else:605- self.content = encode(data, files, json)608+ self.stream = encode(data, files, json)609+610 self.prepare()611 612 def prepare(self) -> None:609- for key, value in self.content.get_headers().items():613+ for key, value in self.stream.get_headers().items():614 self.headers.setdefault(key, value)615 616 auto_headers: typing.List[typing.Tuple[bytes, bytes]] = []617 34 unmodified lines652 async def read(self) -> bytes:653 """654 Read and return the request content.655 """652- return await self.content.aread()656+ return b"".join([part async for part in self.stream])657 654- async def stream(self) -> typing.AsyncIterator[bytes]:655- async for part in self.content:656- yield part658 658-659 class Response:660 def __init__(661 self,662 status_code: int,663 *,664 http_version: str = None,665 headers: HeaderTypes = None,666- content: ResponseContent = None,667- on_close: typing.Callable = None,666+ stream: ContentStream = None,667+ content: bytes = None,668 request: Request = None,669 history: typing.List["Response"] = None,670 elapsed: datetime.timedelta = None,671 ):1 unmodified line673 self.http_version = http_version674 self.headers = Headers(headers)675 676 self.request = request677- self.on_close = on_close677 self.elapsed = datetime.timedelta(0) if elapsed is None else elapsed678 self.call_next: typing.Optional[typing.Callable] = None679 680 self.history = [] if history is None else list(history)681 683- if content is None or isinstance(content, bytes):682+ if stream is None:683 self.is_closed = True684 self.is_stream_consumed = True685 self._raw_content = content or b""686 else:687 self.is_closed = False688 self.is_stream_consumed = False690- self._raw_stream = content689+ self._raw_stream = stream690 691 @property692 def reason_phrase(self) -> str:693 return StatusCode.get_reason_phrase(self.status_code)246 unmodified lines940 Automatically called if the response body is read to completion.941 """942 if not self.is_closed:943 self.is_closed = True945- if self.on_close is not None:946- await self.on_close()944+ if hasattr(self, "_raw_stream"):945+ await self._raw_stream.aclose()946 947 948 class Cookies(MutableMapping):949 """171 unmodified linesdeleted:httpx/multipart.py-126 removed
1-import binascii2-import mimetypes3-import os4-import re5-import typing6-from io import BytesIO7-from pathlib import Path8-9-_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}10-_HTML5_FORM_ENCODING_REPLACEMENTS.update(11- {chr(c): "%{:02X}".format(c) for c in range(0x00, 0x1F + 1) if c != 0x1B}12-)13-_HTML5_FORM_ENCODING_RE = re.compile(14- r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()])15-)16-17-18-class Field:19- def render_headers(self) -> bytes:20- raise NotImplementedError() # pragma: nocover21-22- def render_data(self) -> bytes:23- raise NotImplementedError() # pragma: nocover24-25-26-class DataField(Field):27- def __init__(self, name: str, value: typing.Union[str, bytes]) -> None:28- if not isinstance(name, str):29- raise TypeError("Invalid type for name. Expected str.")30- if not isinstance(value, (str, bytes)):31- raise TypeError("Invalid type for value. Expected str or bytes.")32- self.name = name33- self.value = value34-35- def render_headers(self) -> bytes:36- name = _format_param("name", self.name)37- return b"".join([b"Content-Disposition: form-data; ", name, b"\r\n\r\n"])38-39- def render_data(self) -> bytes:40- return (41- self.value if isinstance(self.value, bytes) else self.value.encode("utf-8")42- )43-44-45-class FileField(Field):46- def __init__(47- self, name: str, value: typing.Union[typing.IO[typing.AnyStr], tuple]48- ) -> None:49- self.name = name50- if not isinstance(value, tuple):51- self.filename = Path(str(getattr(value, "name", "upload"))).name52- self.file = value # type: typing.Union[typing.IO[str], typing.IO[bytes]]53- self.content_type = self.guess_content_type()54- else:55- self.filename = value[0]56- self.file = value[1]57- self.content_type = (58- value[2] if len(value) > 2 else self.guess_content_type()59- )60-61- def guess_content_type(self) -> typing.Optional[str]:62- if self.filename:63- return mimetypes.guess_type(self.filename)[0] or "application/octet-stream"64- else:65- return None66-67- def render_headers(self) -> bytes:68- parts = [b"Content-Disposition: form-data; ", _format_param("name", self.name)]69- if self.filename:70- filename = _format_param("filename", self.filename)71- parts.extend([b"; ", filename])72- if self.content_type is not None:73- content_type = self.content_type.encode()74- parts.extend([b"\r\nContent-Type: ", content_type])75- parts.append(b"\r\n\r\n")76- return b"".join(parts)77-78- def render_data(self) -> bytes:79- if isinstance(self.file, str):80- content = self.file81- else:82- content = self.file.read()83- return content.encode("utf-8") if isinstance(content, str) else content84-85-86-def iter_fields(data: dict, files: dict) -> typing.Iterator[Field]:87- for name, value in data.items():88- if isinstance(value, (list, dict)):89- for item in value:90- yield DataField(name=name, value=item)91- else:92- yield DataField(name=name, value=value)93-94- for name, value in files.items():95- yield FileField(name=name, value=value)96-97-98-def multipart_encode(99- data: dict, files: dict, boundary: bytes = None100-) -> typing.Tuple[bytes, str]:101- body = BytesIO()102- if boundary is None: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())108- body.write(field.render_data())109- body.write(b"\r\n")110-111- body.write(b"--%s--\r\n" % boundary)112-113- content_type = "multipart/form-data; boundary=%s" % boundary.decode("ascii")114-115- return body.getvalue(), content_type116-117-118-def _format_param(name: str, value: typing.Union[str, bytes]) -> bytes:119- if isinstance(value, bytes):120- value = value.decode()121-122- def replacer(match: typing.Match[str]) -> str:123- return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]124-125- value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)126- return f'{name}="{value}"'.encode()modified:httpx/utils.py+23 added
15 unmodified lines16 from .models import PrimitiveData17 from .models import URL18 19 20+_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}21+_HTML5_FORM_ENCODING_REPLACEMENTS.update(22+ {chr(c): "%{:02X}".format(c) for c in range(0x00, 0x1F + 1) if c != 0x1B}23+)24+_HTML5_FORM_ENCODING_RE = re.compile(25+ r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()])26+)27+28+29 def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:30 """31 Coerce str/bytes into a strictly byte-wise HTTP header key.32 """36 unmodified lines69 return False70 return True71 72 73+def format_form_param(name: str, value: typing.Union[str, bytes]) -> bytes:74+ """75+ Encode a name/value pair within a multipart form.76+ """77+ if isinstance(value, bytes):78+ value = value.decode()79+80+ def replacer(match: typing.Match[str]) -> str:81+ return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]82+83+ value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)84+ return f'{name}="{value}"'.encode()85+86+87 # Null bytes; no need to recreate these on each call to guess_json_utf88 _null = "\x00".encode("ascii") # encoding to ASCII for Python 389 _null2 = _null * 290 _null3 = _null * 3274 unmodified linesmodified:tests/client/test_redirects.py+2 added-2 removed
79 unmodified lines80 headers = {"location": "/redirect_body_target"}81 return Response(codes.PERMANENT_REDIRECT, headers=headers, request=request)82 83 elif request.url.path == "/redirect_no_body":84- await request.read()84+ content = b"".join([part async for part in request.stream])85 headers = {"location": "/redirect_body_target"}86 return Response(codes.SEE_OTHER, headers=headers, request=request)87 88 elif request.url.path == "/redirect_body_target":89- content = await request.read()89+ content = b"".join([part async for part in request.stream])90 headers = dict(request.headers.items())91 body = json.dumps({"body": content.decode(), "headers": headers}).encode()92 return Response(codes.OK, content=body, request=request)93 260 unmodified linesmodified:tests/dispatch/test_http2.py+1 added-1 removed
12 unmodified lines13 14 async def app(request):15 method = request.method16 path = request.url.path17- body = await request.read()17+ body = b"".join([part async for part in request.stream])18 content = json.dumps(19 {"method": method, "path": path, "body": body.decode()}20 ).encode()21 headers = {"Content-Length": str(len(content))}128 unmodified linesmodified:tests/models/test_requests.py+6 added-2 removed
19 unmodified lines20 21 @pytest.mark.asyncio22 async def test_url_encoded_data():23 request = httpx.Request("POST", "http://example.org", data={"test": "123"})24+ content = b"".join([part async for part in request.stream])25+26 assert request.headers["Content-Type"] == "application/x-www-form-urlencoded"25- assert await request.content.aread() == b"test=123"27+ assert content == b"test=123"28 29 30 @pytest.mark.asyncio31 async def test_json_encoded_data():32 request = httpx.Request("POST", "http://example.org", json={"test": 123})33+ content = b"".join([part async for part in request.stream])34+35 assert request.headers["Content-Type"] == "application/json"32- assert await request.content.aread() == b'{"test": 123}'36+ assert content == b'{"test": 123}'37 38 39 def test_transfer_encoding_header():40 async def streaming_body(data):54 unmodified linesmodified:tests/models/test_responses.py+7 added-3 removed
3 unmodified lines4 5 import pytest6 7 import httpx8+from httpx.content_streams import AsyncIteratorStream9 10 11 def streaming_body():12 yield b"Hello, "177 unmodified lines190 191 192 @pytest.mark.asyncio193 async def test_streaming_response():193- response = httpx.Response(200, content=async_streaming_body())194+ stream = AsyncIteratorStream(aiterator=async_streaming_body())195+ response = httpx.Response(200, stream=stream)196 197 assert response.status_code == 200198 assert not response.is_closed199 5 unmodified lines205 206 207 @pytest.mark.asyncio208 async def test_cannot_read_after_stream_consumed():207- response = httpx.Response(200, content=async_streaming_body())209+ stream = AsyncIteratorStream(aiterator=async_streaming_body())210+ response = httpx.Response(200, stream=stream)211 212 content = b""213 async for part in response.aiter_bytes():214 content += part3 unmodified lines218 219 220 @pytest.mark.asyncio221 async def test_cannot_read_after_response_closed():219- response = httpx.Response(200, content=async_streaming_body())222+ stream = AsyncIteratorStream(aiterator=async_streaming_body())223+ response = httpx.Response(200, stream=stream)224 225 await response.close()226 227 with pytest.raises(httpx.ResponseClosed):64 unmodified linesadded:tests/test_content_streams.py+116 added
1+import io2+3+import pytest4+5+from httpx.content_streams import encode6+7+8+@pytest.mark.asyncio9+async def test_empty_content():10+ stream = encode()11+ content = b"".join([part async for part in stream])12+13+ assert stream.can_replay()14+ assert stream.get_headers() == {}15+ assert content == b""16+17+18+@pytest.mark.asyncio19+async def test_bytes_content():20+ stream = encode(data=b"Hello, world!")21+ content = b"".join([part async for part in stream])22+23+ assert stream.can_replay()24+ assert stream.get_headers() == {"Content-Length": "13"}25+ assert content == b"Hello, world!"26+27+28+@pytest.mark.asyncio29+async def test_aiterator_content():30+ async def hello_world():31+ yield b"Hello, "32+ yield b"world!"33+34+ stream = encode(data=hello_world())35+ content = b"".join([part async for part in stream])36+37+ assert not stream.can_replay()38+ assert stream.get_headers() == {"Transfer-Encoding": "chunked"}39+ assert content == b"Hello, world!"40+41+42+@pytest.mark.asyncio43+async def test_json_content():44+ stream = encode(json={"Hello": "world!"})45+ content = b"".join([part async for part in stream])46+47+ assert stream.can_replay()48+ assert stream.get_headers() == {49+ "Content-Length": "19",50+ "Content-Type": "application/json",51+ }52+ assert content == b'{"Hello": "world!"}'53+54+55+@pytest.mark.asyncio56+async def test_urlencoded_content():57+ stream = encode(data={"Hello": "world!"})58+ content = b"".join([part async for part in stream])59+60+ assert stream.can_replay()61+ assert stream.get_headers() == {62+ "Content-Length": "14",63+ "Content-Type": "application/x-www-form-urlencoded",64+ }65+ assert content == b"Hello=world%21"66+67+68+@pytest.mark.asyncio69+async def test_multipart_files_content():70+ files = {"file": io.BytesIO(b"<file content>")}71+ stream = encode(files=files, boundary=b"+++")72+ content = b"".join([part async for part in stream])73+74+ assert stream.can_replay()75+ assert stream.get_headers() == {76+ "Content-Length": "138",77+ "Content-Type": "multipart/form-data; boundary=+++",78+ }79+ assert content == b"".join(80+ [81+ b"--+++\r\n",82+ b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',83+ b"Content-Type: application/octet-stream\r\n",84+ b"\r\n",85+ b"<file content>\r\n",86+ b"--+++--\r\n",87+ ]88+ )89+90+91+@pytest.mark.asyncio92+async def test_multipart_data_and_files_content():93+ data = {"message": "Hello, world!"}94+ files = {"file": io.BytesIO(b"<file content>")}95+ stream = encode(data=data, files=files, boundary=b"+++")96+ content = b"".join([part async for part in stream])97+98+ assert stream.can_replay()99+ assert stream.get_headers() == {100+ "Content-Length": "210",101+ "Content-Type": "multipart/form-data; boundary=+++",102+ }103+ assert content == b"".join(104+ [105+ b"--+++\r\n",106+ b'Content-Disposition: form-data; name="message"\r\n',107+ b"\r\n",108+ b"Hello, world!\r\n",109+ b"--+++\r\n",110+ b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',111+ b"Content-Type: application/octet-stream\r\n",112+ b"\r\n",113+ b"<file content>\r\n",114+ b"--+++--\r\n",115+ ]116+ )deleted:tests/test_content.py-109 removed
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- )modified:tests/test_decoders.py+7 added-3 removed
2 unmodified lines3 import brotli4 import pytest5 6 import httpx7+from httpx.content_streams import AsyncIteratorStream8 from httpx.decoders import (9 BrotliDecoder,10 DeflateDecoder,11 GZipDecoder,70 unmodified lines82 yield compressor.compress(body)83 yield compressor.flush()84 85 headers = [(b"Content-Encoding", b"gzip")]85- response = httpx.Response(200, headers=headers, content=compress(body))86+ stream = AsyncIteratorStream(aiterator=compress(body))87+ response = httpx.Response(200, headers=headers, stream=stream)88 assert not hasattr(response, "body")89 assert await response.read() == body90 91 46 unmodified lines138 nonlocal data139 for chunk in data:140 yield chunk141 140- response = httpx.Response(200, content=iterator())142+ stream = AsyncIteratorStream(aiterator=iterator())143+ response = httpx.Response(200, stream=stream)144 await response.read()145 assert response.text == (b"".join(data)).decode(encoding)146 147 3 unmodified lines151 yield b"\x83g"152 yield b"\x83"153 yield b"\x89\x83x\x83\x8b"154 155+ stream = AsyncIteratorStream(aiterator=iterator())156 response = httpx.Response(157 200,158 headers=[(b"Content-Type", b"text/html; charset=shift-jis")],155- content=iterator(),159+ stream=stream,160 )161 162 await response.read()163 assert "".join(response.text) == "トラベル"59 unmodified linesmodified:tests/test_multipart.py+19 added-18 removed
6 unmodified lines7 import pytest8 9 import httpx10 from httpx.config import CertTypes, TimeoutTypes, VerifyTypes11+from httpx.content_streams import encode12 from httpx.dispatch.base import Dispatcher12-from httpx.multipart import _format_param, multipart_encode13+from httpx.utils import format_form_param14 15 16 class MockDispatch(Dispatcher):17 async def send(2 unmodified lines20 verify: VerifyTypes = None,21 cert: CertTypes = None,22 timeout: TimeoutTypes = None,23 ) -> httpx.Response:23- content = await request.read()24+ content = b"".join([part async for part in request.stream])25 return httpx.Response(200, content=content)26 27 28 @pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))76 unmodified lines105 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}106 107 with mock.patch("os.urandom", return_value=os.urandom(16)):108 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")108- body, content_type = multipart_encode(data=data, files=files)109- assert content_type == f"multipart/form-data; boundary={boundary}"110- assert body == (109+ stream = encode(data=data, files=files)110+ assert stream.content_type == f"multipart/form-data; boundary={boundary}"111+ assert stream.body == (112 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'113 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'114 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'115 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'13 unmodified lines129 files = {"file": (None, io.BytesIO(b"<file content>"))}130 with mock.patch("os.urandom", return_value=os.urandom(16)):131 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")132 132- body, content_type = multipart_encode(data={}, files=files)133+ stream = encode(data={}, files=files)134 134- assert content_type == f"multipart/form-data; boundary={boundary}"135- assert body == (135+ assert stream.content_type == f"multipart/form-data; boundary={boundary}"136+ assert stream.body == (137 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'138 "<file content>\r\n--{0}--\r\n"139 "".format(boundary).encode("ascii")140 )13 unmodified lines154 files = {"file": (file_name, io.BytesIO(b"<file content>"))}155 with mock.patch("os.urandom", return_value=os.urandom(16)):156 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")157 157- body, content_type = multipart_encode(data={}, files=files)158+ stream = encode(data={}, files=files)159 159- assert content_type == f"multipart/form-data; boundary={boundary}"160- assert body == (160+ assert stream.content_type == f"multipart/form-data; boundary={boundary}"161+ assert stream.body == (162 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '163 f'filename="{file_name}"\r\nContent-Type: '164 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"165 "".encode("ascii")4 unmodified lines170 files = {"file": ("test.txt", "<string content>", "text/plain")}171 with mock.patch("os.urandom", return_value=os.urandom(16)):172 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")173 173- body, content_type = multipart_encode(data={}, files=files)174+ stream = encode(data={}, files=files)175 175- assert content_type == f"multipart/form-data; boundary={boundary}"176- assert body == (176+ assert stream.content_type == f"multipart/form-data; boundary={boundary}"177+ assert stream.body == (178 '--{0}\r\nContent-Disposition: form-data; name="file"; '179 'filename="test.txt"\r\n'180 "Content-Type: text/plain\r\n\r\n<string content>\r\n"181 "--{0}--\r\n"2 unmodified lines184 185 186 class TestHeaderParamHTML5Formatting:187 def test_unicode(self):187- param = _format_param("filename", "n\u00e4me")188+ param = format_form_param("filename", "n\u00e4me")189 assert param == b'filename="n\xc3\xa4me"'190 191 def test_ascii(self):191- param = _format_param("filename", b"name")192+ param = format_form_param("filename", b"name")193 assert param == b'filename="name"'194 195 def test_unicode_escape(self):195- param = _format_param("filename", "hello\\world\u0022")196+ param = format_form_param("filename", "hello\\world\u0022")197 assert param == b'filename="hello\\\\world%22"'198 199 def test_unicode_with_control_character(self):199- param = _format_param("filename", "hello\x1A\x1B\x1C")200+ param = format_form_param("filename", "hello\x1A\x1B\x1C")201 assert param == b'filename="hello%1A\x1B%1C"'