Skip to content
Myr

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

18 files+511 added−474 removed

modified:httpx/dispatch/asgi.py+7 added-3 removed
1import typing23from ..config import CertTypes, TimeoutTypes, VerifyTypes4from ..content_streams import ByteStream5from ..models import Request, Response6from .base import Dispatcher78
68 unmodified lines
77 }78 status_code = None79 headers = None80 body_parts = []80 request_stream = request.stream()81 response_started = False82 response_complete = False8384 request_body_chunks = request.stream.__aiter__()8586 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 lines
121 assert response_complete122 assert status_code is not None123 assert headers is not None124125 stream = ByteStream(b"".join(body_parts))126127 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 lines
3import h1145from ..concurrency.base import BaseSocketStream6from ..config import Timeout7from ..content_streams import AsyncIteratorStream8from ..exceptions import ConnectionClosed, ProtocolError9from ..models import Request, Response10from ..utils import get_logger11from .base import OpenConnection
38 unmodified lines
5051 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 )5859 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 )6667 async def close(self) -> None:
27 unmodified lines
95 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 lines
modified:httpx/dispatch/http2.py+7 added-4 removed
10 unmodified lines
11 ConcurrencyBackend,12 lookup_backend,13)14from ..config import Timeout15from ..content_streams import AsyncIteratorStream16from ..exceptions import ProtocolError17from ..models import Request, Response18from ..utils import get_logger19from .base import OpenConnection
189 unmodified lines
209 await self.send_body(request, timeout)210211 # 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 )216217 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 )224225 async def send_headers(self, request: Request, timeout: Timeout) -> None:
14 unmodified lines
240 await self.connection.send_headers(self.stream_id, headers, timeout)241242 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 lines
modified:httpx/dispatch/proxy_http.py+3 added-2 removed
165 unmodified lines
166 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 pass173174 return connection175176 def should_forward_origin(self, origin: Origin) -> bool:
37 unmodified lines
modified:httpx/client.py+11 added-9 removed
17 unmodified lines
18 TimeoutTypes,19 UnsetType,20 VerifyTypes,21)22from .content import RequestContent22from .content_streams import ContentStream23from .dispatch.asgi import ASGIDispatch24from .dispatch.base import Dispatcher25from .dispatch.connection_pool import ConnectionPool26from .dispatch.proxy_http import HTTPProxy
467 unmodified lines
494 """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 )503504 def redirect_method(self, request: Request, response: Response) -> str:505 """506 When being redirected we may want to change the method of the request
59 unmodified lines
566 headers.pop("Cookie", None)567568 return headers569570 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.stream581582 async def send_handling_auth(583 self,584 request: Request,
401 unmodified lines
added:httpx/content_streams.py+279 added
1import binascii2import mimetypes3import os4import typing5from io import BytesIO6from json import dumps as json_dumps7from pathlib import Path8from urllib.parse import urlencode910from .utils import format_form_param1112RequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]1314RequestFiles = 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]313233class 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 {}3940 def can_replay(self) -> bool:41 """42 Return `True` if `__aiter__` can be called multiple times.4344 We need this in cases such determining if we can re-issue a request45 body when we receive a redirect response.46 """47 return True4849 async def __aiter__(self) -> typing.AsyncIterator[bytes]:50 yield b""5152 async def aclose(self) -> None:53 pass545556class ByteStream(ContentStream):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 if not self.body:66 return {}67 content_length = str(len(self.body))68 return {"Content-Length": content_length}6970 async def __aiter__(self) -> typing.AsyncIterator[bytes]:71 yield self.body727374class AsyncIteratorStream(ContentStream):75 """76 Request content encoded as plain bytes, using an async byte iterator.77 """7879 def __init__(80 self, aiterator: typing.AsyncIterator[bytes], close_func: typing.Callable = None81 ) -> None:82 self.aiterator = aiterator83 self.close_func = close_func8485 def can_replay(self) -> bool:86 return False8788 def get_headers(self) -> typing.Dict[str, str]:89 return {"Transfer-Encoding": "chunked"}9091 async def __aiter__(self) -> typing.AsyncIterator[bytes]:92 async for part in self.aiterator:93 yield part9495 async def aclose(self) -> None:96 if self.close_func is not None:97 await self.close_func()9899100class JSONStream(ContentStream):101 """102 Request content encoded as JSON.103 """104105 def __init__(self, json: typing.Any) -> None:106 self.body = json_dumps(json).encode("utf-8")107108 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}112113 async def __aiter__(self) -> typing.AsyncIterator[bytes]:114 yield self.body115116117class URLEncodedStream(ContentStream):118 """119 Request content as URL encoded form data.120 """121122 def __init__(self, data: dict) -> None:123 self.body = urlencode(data, doseq=True).encode("utf-8")124125 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}129130 async def __aiter__(self) -> typing.AsyncIterator[bytes]:131 yield self.body132133134class MultipartStream(ContentStream):135 """136 Request content as multipart encoded form data.137 """138139 class DataField:140 """141 A single form field item, within a multipart form field.142 """143144 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 = value151152 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"])155156 def render_data(self) -> bytes:157 return (158 self.value159 if isinstance(self.value, bytes)160 else self.value.encode("utf-8")161 )162163 class FileField:164 """165 A single file field item, within a multipart form field.166 """167168 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 )184185 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 None192193 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)206207 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 content213214 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))218219 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")224225 body.write(b"--%s--\r\n" % boundary)226227 self.content_type = "multipart/form-data; boundary=%s" % boundary.decode(228 "ascii"229 )230 self.body = body.getvalue()231232 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)241242 for name, value in files.items():243 yield self.FileField(name=name, value=value)244245 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}249250 async def __aiter__(self) -> typing.AsyncIterator[bytes]:251 yield self.body252253254def 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
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+16 added-17 removed
11 unmodified lines
12import chardet13import rfc39861415from .config import USER_AGENT16from .content import RequestData, RequestFiles, encode16from .content_streams import ContentStream, RequestData, RequestFiles, encode17from .decoders import (18 ACCEPT_ENCODING,19 SUPPORTED_DECODERS,20 Decoder,
49 unmodified lines
70ProxiesTypes = typing.Union[71 URLTypes, "Dispatcher", typing.Dict[URLTypes, typing.Union[URLTypes, "Dispatcher"]]72]7374ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]747675class URL:76 def __init__(77 self,78 url: URLTypes,
513 unmodified lines
592 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)604605 if stream is not None:606 self.stream = stream607 else:605 self.content = encode(data, files, json)608 self.stream = encode(data, files, json)609610 self.prepare()611612 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)615616 auto_headers: typing.List[typing.Tuple[bytes, bytes]] = []617
34 unmodified lines
652 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])657654 async def stream(self) -> typing.AsyncIterator[bytes]:655 async for part in self.content:656 yield part658658659class 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 line
673 self.http_version = http_version674 self.headers = Headers(headers)675676 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] = None679680 self.history = [] if history is None else list(history)681683 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 = stream690691 @property692 def reason_phrase(self) -> str:693 return StatusCode.get_reason_phrase(self.status_code)
246 unmodified lines
940 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()946947948class Cookies(MutableMapping):949 """
171 unmodified lines
deleted:httpx/multipart.py-126 removed
1import binascii2import mimetypes3import os4import re5import typing6from io import BytesIO7from pathlib import Path89_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)161718class Field:19 def render_headers(self) -> bytes:20 raise NotImplementedError() # pragma: nocover2122 def render_data(self) -> bytes:23 raise NotImplementedError() # pragma: nocover242526class 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 = value3435 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"])3839 def render_data(self) -> bytes:40 return (41 self.value if isinstance(self.value, bytes) else self.value.encode("utf-8")42 )434445class 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 )6061 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 None6667 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)7778 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 content848586def 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)9394 for name, value in files.items():95 yield FileField(name=name, value=value)969798def 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))104105 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")110111 body.write(b"--%s--\r\n" % boundary)112113 content_type = "multipart/form-data; boundary=%s" % boundary.decode("ascii")114115 return body.getvalue(), content_type116117118def _format_param(name: str, value: typing.Union[str, bytes]) -> bytes:119 if isinstance(value, bytes):120 value = value.decode()121122 def replacer(match: typing.Match[str]) -> str:123 return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]124125 value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)126 return f'{name}="{value}"'.encode()
modified:httpx/utils.py+23 added
15 unmodified lines
16 from .models import PrimitiveData17 from .models import URL181920_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)272829def 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 lines
69 return False70 return True717273def 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()7980 def replacer(match: typing.Match[str]) -> str:81 return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]8283 value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)84 return f'{name}="{value}"'.encode()858687# 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 * 3
274 unmodified lines
modified:tests/client/test_redirects.py+2 added-2 removed
79 unmodified lines
80 headers = {"location": "/redirect_body_target"}81 return Response(codes.PERMANENT_REDIRECT, headers=headers, request=request)8283 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)8788 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 lines
modified:tests/dispatch/test_http2.py+1 added-1 removed
12 unmodified lines
1314async 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 lines
modified:tests/models/test_requests.py+6 added-2 removed
19 unmodified lines
2021@pytest.mark.asyncio22async 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])2526 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"282930@pytest.mark.asyncio31async 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])3435 assert request.headers["Content-Type"] == "application/json"32 assert await request.content.aread() == b'{"test": 123}'36 assert content == b'{"test": 123}'373839def test_transfer_encoding_header():40 async def streaming_body(data):
54 unmodified lines
modified:tests/models/test_responses.py+7 added-3 removed
3 unmodified lines
45import pytest67import httpx8from httpx.content_streams import AsyncIteratorStream91011def streaming_body():12 yield b"Hello, "
177 unmodified lines
190191192@pytest.mark.asyncio193async 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)196197 assert response.status_code == 200198 assert not response.is_closed199
5 unmodified lines
205206207@pytest.mark.asyncio208async 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)211212 content = b""213 async for part in response.aiter_bytes():214 content += part
3 unmodified lines
218219220@pytest.mark.asyncio221async 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)224225 await response.close()226227 with pytest.raises(httpx.ResponseClosed):
64 unmodified lines
added:tests/test_content_streams.py+116 added
1import io23import pytest45from httpx.content_streams import encode678@pytest.mark.asyncio9async def test_empty_content():10 stream = encode()11 content = b"".join([part async for part in stream])1213 assert stream.can_replay()14 assert stream.get_headers() == {}15 assert content == b""161718@pytest.mark.asyncio19async def test_bytes_content():20 stream = encode(data=b"Hello, world!")21 content = b"".join([part async for part in stream])2223 assert stream.can_replay()24 assert stream.get_headers() == {"Content-Length": "13"}25 assert content == b"Hello, world!"262728@pytest.mark.asyncio29async def test_aiterator_content():30 async def hello_world():31 yield b"Hello, "32 yield b"world!"3334 stream = encode(data=hello_world())35 content = b"".join([part async for part in stream])3637 assert not stream.can_replay()38 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}39 assert content == b"Hello, world!"404142@pytest.mark.asyncio43async def test_json_content():44 stream = encode(json={"Hello": "world!"})45 content = b"".join([part async for part in stream])4647 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!"}'535455@pytest.mark.asyncio56async def test_urlencoded_content():57 stream = encode(data={"Hello": "world!"})58 content = b"".join([part async for part in stream])5960 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"666768@pytest.mark.asyncio69async 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])7374 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 )899091@pytest.mark.asyncio92async 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])9798 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
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 )
modified:tests/test_decoders.py+7 added-3 removed
2 unmodified lines
3import brotli4import pytest56import httpx7from httpx.content_streams import AsyncIteratorStream8from httpx.decoders import (9 BrotliDecoder,10 DeflateDecoder,11 GZipDecoder,
70 unmodified lines
82 yield compressor.compress(body)83 yield compressor.flush()8485 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() == body9091
46 unmodified lines
138 nonlocal data139 for chunk in data:140 yield chunk141140 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)146147
3 unmodified lines
151 yield b"\x83g"152 yield b"\x83"153 yield b"\x89\x83x\x83\x8b"154155 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 )161162 await response.read()163 assert "".join(response.text) == "トラベル"
59 unmodified lines
modified:tests/test_multipart.py+19 added-18 removed
6 unmodified lines
7import pytest89import httpx10from httpx.config import CertTypes, TimeoutTypes, VerifyTypes11from httpx.content_streams import encode12from httpx.dispatch.base import Dispatcher12from httpx.multipart import _format_param, multipart_encode13from httpx.utils import format_form_param141516class MockDispatch(Dispatcher):17 async def send(
2 unmodified lines
20 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)262728@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))
76 unmodified lines
105 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}106107 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 lines
129 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")132132 body, content_type = multipart_encode(data={}, files=files)133 stream = encode(data={}, files=files)134134 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 lines
154 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")157157 body, content_type = multipart_encode(data={}, files=files)158 stream = encode(data={}, files=files)159159 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 lines
170 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")173173 body, content_type = multipart_encode(data={}, files=files)174 stream = encode(data={}, files=files)175175 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 lines
184185186class 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"'190191 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"'194195 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"'198199 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"'