Sync or Async dispatch (#83)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Support thread-pooled dispatch * Add ConcurrencyBackend.run * Initial work towards support byte-iterators on sync request data * Test case for byte iterator content * byte iterator support for RequestData * Add BaseResponse * Bridge sync/async data in SyncResponse * Add BaseClient * SyncResponse -> Response * Tweaking type annotation * Distinct classes for Request, AsyncRequest * Tweak is_streaming, content in BaseRequest * Stream handling moves to client * Handle mediating to AsyncResponse from a standard sync Dispatcher class * Working on thread-pooled dispatcher * Support threaded dispatch, inc. streaming requests/responses * Increase test coverage * Coverage and tweaks * Include Accept and User-Agent headers by default
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
22 files+1078 added−602 removed
- tests:+261 added−108 removed
- other:+817 added−494 removed
Provenance
- Commit
0cbf3c7- Tree
4f69022- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
ba033c5
22 files changed+1078 added−602 removed
modified:httpcore/dispatch/connection_pool.py+6 added-7 removed
10 unmodified lines11 VerifyTypes,12 )13 from ..decoders import ACCEPT_ENCODING14 from ..exceptions import PoolTimeout15-from ..interfaces import ConcurrencyBackend, Dispatcher16-from ..models import Origin, Request, Response15+from ..interfaces import AsyncDispatcher, ConcurrencyBackend16+from ..models import AsyncRequest, AsyncResponse, Origin17 from .connection import HTTPConnection18 19 CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]20 55 unmodified lines76 def __len__(self) -> int:77 return len(self.all)78 79 80-class ConnectionPool(Dispatcher):80+class ConnectionPool(AsyncDispatcher):81 def __init__(82 self,83 *,84 verify: VerifyTypes = True,19 unmodified lines104 return len(self.keepalive_connections) + len(self.active_connections)105 106 async def send(107 self,108- request: Request,109- stream: bool = False,108+ request: AsyncRequest,109 verify: VerifyTypes = None,110 cert: CertTypes = None,111 timeout: TimeoutTypes = None,113- ) -> Response:112+ ) -> AsyncResponse:113 connection = await self.acquire_connection(request.url.origin)114 try:115 response = await connection.send(117- request, stream=stream, verify=verify, cert=cert, timeout=timeout116+ request, verify=verify, cert=cert, timeout=timeout117 )118 except BaseException as exc:119 self.active_connections.remove(connection)120 self.max_connections.release()44 unmodified linesmodified:httpcore/dispatch/connection.py+7 added-12 removed
13 unmodified lines14 TimeoutTypes,15 VerifyTypes,16 )17 from ..exceptions import ConnectTimeout18-from ..interfaces import ConcurrencyBackend, Dispatcher, Protocol19-from ..models import Origin, Request, Response18+from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Protocol19+from ..models import AsyncRequest, AsyncResponse, Origin20 from .http2 import HTTP2Connection21 from .http11 import HTTP11Connection22 23 # Callback signature: async def callback(conn: HTTPConnection) -> None24 ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]25 26 27-class HTTPConnection(Dispatcher):27+class HTTPConnection(AsyncDispatcher):28 def __init__(29 self,30 origin: typing.Union[str, Origin],31 verify: VerifyTypes = True,11 unmodified lines43 self.h2_connection = None # type: typing.Optional[HTTP2Connection]44 45 async def send(46 self,47- request: Request,48- stream: bool = False,47+ request: AsyncRequest,48 verify: VerifyTypes = None,49 cert: CertTypes = None,50 timeout: TimeoutTypes = None,52- ) -> Response:51+ ) -> AsyncResponse:52 if self.h11_connection is None and self.h2_connection is None:53 await self.connect(verify=verify, cert=cert, timeout=timeout)54 55 if self.h2_connection is not None:57- response = await self.h2_connection.send(58- request, stream=stream, timeout=timeout59- )56+ response = await self.h2_connection.send(request, timeout=timeout)57 else:58 assert self.h11_connection is not None62- response = await self.h11_connection.send(63- request, stream=stream, timeout=timeout64- )59+ response = await self.h11_connection.send(request, timeout=timeout)60 61 return response62 63 async def connect(44 unmodified linesmodified:httpcore/dispatch/http11.py+6 added-14 removed
2 unmodified lines3 import h114 5 from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes6 from ..exceptions import ConnectTimeout, ReadTimeout7-from ..interfaces import BaseReader, BaseWriter, Dispatcher8-from ..models import Request, Response7+from ..interfaces import BaseReader, BaseWriter8+from ..models import AsyncRequest, AsyncResponse9 10 H11Event = typing.Union[11 h11.Request,12 h11.Response,24 unmodified lines37 self.on_release = on_release38 self.h11_state = h11.Connection(our_role=h11.CLIENT)39 40 async def send(41- self, request: Request, stream: bool = False, timeout: TimeoutTypes = None42- ) -> Response:41+ self, request: AsyncRequest, timeout: TimeoutTypes = None42+ ) -> AsyncResponse:43 timeout = None if timeout is None else TimeoutConfig(timeout)44 45 # Start sending the request.46 method = request.method.encode("ascii")47 target = request.url.full_path.encode("ascii")48 headers = request.headers.raw49- if 'Host' not in request.headers:49+ if "Host" not in request.headers:50 host = request.url.authority.encode("ascii")51 headers = [(b"host", host)] + headers52 event = h11.Request(method=method, target=target, headers=headers)53 await self._send_event(event, timeout)17 unmodified lines71 status_code = event.status_code72 headers = event.headers73 content = self._body_iter(timeout)74 75- response = Response(75+ return AsyncResponse(76 status_code=status_code,77 reason_phrase=reason_phrase,78 protocol="HTTP/1.1",79 headers=headers,1 unmodified line81 on_close=self.response_closed,82 request=request,83 )84 85- if not stream:86- try:87- await response.read()88- finally:89- await response.close()90-91- return response92-85 async def close(self) -> None:86 event = h11.ConnectionClosed()87 self.h11_state.send(event)88 await self.writer.close()39 unmodified linesmodified:httpcore/dispatch/http2.py+6 added-14 removed
4 unmodified lines5 import h2.events6 7 from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes8 from ..exceptions import ConnectTimeout, ReadTimeout9-from ..interfaces import BaseReader, BaseWriter, Dispatcher10-from ..models import Request, Response9+from ..interfaces import BaseReader, BaseWriter10+from ..models import AsyncRequest, AsyncResponse11 12 13 class HTTP2Connection:14 READ_NUM_BYTES = 40968 unmodified lines23 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]24 self.initialized = False25 26 async def send(27- self, request: Request, stream: bool = False, timeout: TimeoutTypes = None28- ) -> Response:27+ self, request: AsyncRequest, timeout: TimeoutTypes = None28+ ) -> AsyncResponse:29 timeout = None if timeout is None else TimeoutConfig(timeout)30 31 # Start sending the request.32 if not self.initialized:25 unmodified lines58 59 content = self.body_iter(stream_id, timeout)60 on_close = functools.partial(self.response_closed, stream_id=stream_id)61 62- response = Response(62+ return AsyncResponse(63 status_code=status_code,64 protocol="HTTP/2",65 headers=headers,66 content=content,67 on_close=on_close,68 request=request,69 )70 71- if not stream:72- try:73- await response.read()74- finally:75- await response.close()76-77- return response78-71 async def close(self) -> None:72 await self.writer.close()73 74 def initiate_connection(self) -> None:2 unmodified lines77 self.writer.write_no_block(data_to_send)78 self.initialized = True79 80 async def send_headers(89- self, request: Request, timeout: TimeoutConfig = None81+ self, request: AsyncRequest, timeout: TimeoutConfig = None82 ) -> int:83 stream_id = self.h2_state.get_next_available_stream_id()84 headers = [85 (b":method", request.method.encode("ascii")),56 unmodified linesadded:httpcore/dispatch/threaded.py+97 added
1+from ..config import CertTypes, TimeoutTypes, VerifyTypes2+from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher3+from ..models import (4+ AsyncRequest,5+ AsyncRequestData,6+ AsyncResponse,7+ AsyncResponseContent,8+ Request,9+ RequestData,10+ Response,11+ ResponseContent,12+)13+14+15+class ThreadedDispatcher(AsyncDispatcher):16+ """17+ The ThreadedDispatcher class is used to mediate between the Client18+ (which always uses async under the hood), and a synchronous `Dispatch`19+ class.20+ """21+22+ def __init__(self, dispatch: Dispatcher, backend: ConcurrencyBackend) -> None:23+ self.sync_dispatcher = dispatch24+ self.backend = backend25+26+ async def send(27+ self,28+ request: AsyncRequest,29+ verify: VerifyTypes = None,30+ cert: CertTypes = None,31+ timeout: TimeoutTypes = None,32+ ) -> AsyncResponse:33+ concurrency_backend = self.backend34+35+ data = getattr(request, "content", getattr(request, "content_aiter", None))36+ sync_data = self._sync_request_data(data)37+38+ sync_request = Request(39+ method=request.method,40+ url=request.url,41+ headers=request.headers,42+ data=sync_data,43+ )44+45+ func = self.sync_dispatcher.send46+ kwargs = {47+ "request": sync_request,48+ "verify": verify,49+ "cert": cert,50+ "timeout": timeout,51+ }52+ sync_response = await self.backend.run_in_threadpool(func, **kwargs)53+ assert isinstance(sync_response, Response)54+55+ content = getattr(56+ sync_response, "_raw_content", getattr(sync_response, "_raw_stream", None)57+ )58+59+ async_content = self._async_response_content(content)60+61+ async def async_on_close() -> None:62+ nonlocal concurrency_backend, sync_response63+ await concurrency_backend.run_in_threadpool(sync_response.close)64+65+ return AsyncResponse(66+ status_code=sync_response.status_code,67+ reason_phrase=sync_response.reason_phrase,68+ protocol=sync_response.protocol,69+ headers=sync_response.headers,70+ content=async_content,71+ on_close=async_on_close,72+ request=request,73+ history=sync_response.history,74+ )75+76+ async def close(self) -> None:77+ """78+ The `.close()` method runs the `Dispatcher.close()` within a threadpool,79+ so as not to block the async event loop.80+ """81+ func = self.sync_dispatcher.close82+ await self.backend.run_in_threadpool(func)83+84+ def _async_response_content(self, content: ResponseContent) -> AsyncResponseContent:85+ if isinstance(content, bytes):86+ return content87+88+ # Coerce an async iterator into an iterator, with each item in the89+ # iteration run within the event loop.90+ assert hasattr(content, "__iter__")91+ return self.backend.iterate_in_threadpool(content)92+93+ def _sync_request_data(self, data: AsyncRequestData) -> RequestData:94+ if isinstance(data, bytes):95+ return data96+97+ return self.backend.iterate(data)modified:httpcore/__init__.py+19 added-2 removed
26 unmodified lines27 Timeout,28 TooManyRedirects,29 WriteTimeout,30 )31-from .interfaces import BaseReader, BaseWriter, ConcurrencyBackend, Dispatcher, Protocol32-from .models import URL, Cookies, Headers, Origin, QueryParams, Request, Response31+from .interfaces import (32+ AsyncDispatcher,33+ BaseReader,34+ BaseWriter,35+ ConcurrencyBackend,36+ Dispatcher,37+ Protocol,38+)39+from .models import (40+ URL,41+ AsyncRequest,42+ AsyncResponse,43+ Cookies,44+ Headers,45+ Origin,46+ QueryParams,47+ Request,48+ Response,49+)50 from .status_codes import StatusCode, codes51 52 __version__ = "0.4.0"modified:httpcore/api.py+9 added-9 removed
6 unmodified lines7 CookieTypes,8 HeaderTypes,9 QueryParamTypes,10 RequestData,11- SyncResponse,11+ Response,12 URLTypes,13 )14 15 13 unmodified lines29 # proxies30 cert: CertTypes = None,31 verify: VerifyTypes = True,32 stream: bool = False,33-) -> SyncResponse:33+) -> Response:34 with Client() as client:35 return client.request(36 method=method,37 url=url,22 unmodified lines60 allow_redirects: bool = True,61 cert: CertTypes = None,62 verify: VerifyTypes = True,63 timeout: TimeoutTypes = None,64-) -> SyncResponse:64+) -> Response:65 return request(66 "GET",67 url,68 headers=headers,18 unmodified lines87 allow_redirects: bool = True,88 cert: CertTypes = None,89 verify: VerifyTypes = True,90 timeout: TimeoutTypes = None,91-) -> SyncResponse:91+) -> Response:92 return request(93 "OPTIONS",94 url,95 headers=headers,18 unmodified lines114 allow_redirects: bool = False, # Note: Differs to usual default.115 cert: CertTypes = None,116 verify: VerifyTypes = True,117 timeout: TimeoutTypes = None,118-) -> SyncResponse:118+) -> Response:119 return request(120 "HEAD",121 url,122 headers=headers,20 unmodified lines143 allow_redirects: bool = True,144 cert: CertTypes = None,145 verify: VerifyTypes = True,146 timeout: TimeoutTypes = None,147-) -> SyncResponse:147+) -> Response:148 return request(149 "POST",150 url,151 data=data,22 unmodified lines174 allow_redirects: bool = True,175 cert: CertTypes = None,176 verify: VerifyTypes = True,177 timeout: TimeoutTypes = None,178-) -> SyncResponse:178+) -> Response:179 return request(180 "PUT",181 url,182 data=data,22 unmodified lines205 allow_redirects: bool = True,206 cert: CertTypes = None,207 verify: VerifyTypes = True,208 timeout: TimeoutTypes = None,209-) -> SyncResponse:209+) -> Response:210 return request(211 "PATCH",212 url,213 data=data,22 unmodified lines236 allow_redirects: bool = True,237 cert: CertTypes = None,238 verify: VerifyTypes = True,239 timeout: TimeoutTypes = None,240-) -> SyncResponse:240+) -> Response:241 return request(242 "DELETE",243 url,244 data=data,10 unmodified linesmodified:httpcore/auth.py+3 added-3 removed
1 import typing2 from base64 import b64encode3 4-from .models import Request4+from .models import AsyncRequest5 6 7 class AuthBase:8 """9 Base class that all auth implementations derive from.10 """11 12- def __call__(self, request: Request) -> Request:12+ def __call__(self, request: AsyncRequest) -> AsyncRequest:13 raise NotImplementedError("Auth hooks must be callable.") # pragma: nocover14 15 16 class HTTPBasicAuth(AuthBase):2 unmodified lines19 ) -> None:20 self.username = username21 self.password = password22 23- def __call__(self, request: Request) -> Request:23+ def __call__(self, request: AsyncRequest) -> AsyncRequest:24 request.headers["Authorization"] = self.build_auth_header()25 return request26 27 def build_auth_header(self) -> str:11 unmodified linesmodified:httpcore/client.py+279 added-255 removed
1-import asyncio1 import typing2 from types import TracebackType3 4 from .auth import HTTPBasicAuth5+from .concurrency import AsyncioBackend6 from .config import (7 DEFAULT_MAX_REDIRECTS,8 DEFAULT_POOL_LIMITS,9 DEFAULT_TIMEOUT_CONFIG,2 unmodified lines12 TimeoutTypes,13 VerifyTypes,14 )15 from .dispatch.connection_pool import ConnectionPool16+from .dispatch.threaded import ThreadedDispatcher17 from .exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects17-from .interfaces import ConcurrencyBackend, Dispatcher18+from .interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher19 from .models import (20 URL,21+ AsyncRequest,22+ AsyncRequestData,23+ AsyncResponse,24+ AsyncResponseContent,25 AuthTypes,26 Cookies,27 CookieTypes,28 Headers,1 unmodified line30 QueryParamTypes,31 Request,32 RequestData,33 Response,29- SyncResponse,34+ ResponseContent,35 URLTypes,36 )37 from .status_codes import codes38 39 35-class AsyncClient:40+class BaseClient:41 def __init__(42 self,43 auth: AuthTypes = None,44 cookies: CookieTypes = None,1 unmodified line46 cert: CertTypes = None,47 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,48 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,49 max_redirects: int = DEFAULT_MAX_REDIRECTS,45- dispatch: Dispatcher = None,50+ dispatch: typing.Union[AsyncDispatcher, Dispatcher] = None,51 backend: ConcurrencyBackend = None,52 ):53+ if backend is None:54+ backend = AsyncioBackend()55+56 if dispatch is None:49- dispatch = ConnectionPool(57+ async_dispatch = ConnectionPool(58 verify=verify,59 cert=cert,60 timeout=timeout,61 pool_limits=pool_limits,62 backend=backend,55- )63+ ) # type: AsyncDispatcher64+ elif isinstance(dispatch, Dispatcher):65+ async_dispatch = ThreadedDispatcher(dispatch, backend)66+ else:67+ async_dispatch = dispatch68 69 self.auth = auth70 self.cookies = Cookies(cookies)71 self.max_redirects = max_redirects60- self.dispatch = dispatch72+ self.dispatch = async_dispatch73+ self.concurrency_backend = backend74 75+ def merge_cookies(76+ self, cookies: CookieTypes = None77+ ) -> typing.Optional[CookieTypes]:78+ if cookies or self.cookies:79+ merged_cookies = Cookies(self.cookies)80+ merged_cookies.update(cookies)81+ return merged_cookies82+ return cookies83+84+ async def send(85+ self,86+ request: AsyncRequest,87+ *,88+ stream: bool = False,89+ auth: AuthTypes = None,90+ allow_redirects: bool = True,91+ verify: VerifyTypes = None,92+ cert: CertTypes = None,93+ timeout: TimeoutTypes = None,94+ ) -> AsyncResponse:95+ if auth is None:96+ auth = self.auth97+98+ url = request.url99+ if auth is None and (url.username or url.password):100+ auth = HTTPBasicAuth(username=url.username, password=url.password)101+102+ if auth is not None:103+ if isinstance(auth, tuple):104+ auth = HTTPBasicAuth(username=auth[0], password=auth[1])105+ request = auth(request)106+107+ response = await self.send_handling_redirects(108+ request,109+ verify=verify,110+ cert=cert,111+ timeout=timeout,112+ allow_redirects=allow_redirects,113+ )114+115+ if not stream:116+ try:117+ await response.read()118+ finally:119+ await response.close()120+121+ return response122+123+ async def send_handling_redirects(124+ self,125+ request: AsyncRequest,126+ *,127+ cert: CertTypes = None,128+ verify: VerifyTypes = None,129+ timeout: TimeoutTypes = None,130+ allow_redirects: bool = True,131+ history: typing.List[AsyncResponse] = None,132+ ) -> AsyncResponse:133+ if history is None:134+ history = []135+136+ while True:137+ # We perform these checks here, so that calls to `response.next()`138+ # will raise redirect errors if appropriate.139+ if len(history) > self.max_redirects:140+ raise TooManyRedirects()141+ if request.url in [response.url for response in history]:142+ raise RedirectLoop()143+144+ response = await self.dispatch.send(145+ request, verify=verify, cert=cert, timeout=timeout146+ )147+ assert isinstance(response, AsyncResponse)148+ response.history = list(history)149+ self.cookies.extract_cookies(response)150+ history = [response] + history151+ if not response.is_redirect:152+ break153+154+ if allow_redirects:155+ request = self.build_redirect_request(request, response)156+ else:157+158+ async def send_next() -> AsyncResponse:159+ nonlocal request, response, verify, cert, allow_redirects, timeout, history160+ request = self.build_redirect_request(request, response)161+ response = await self.send_handling_redirects(162+ request,163+ allow_redirects=allow_redirects,164+ verify=verify,165+ cert=cert,166+ timeout=timeout,167+ history=history,168+ )169+ return response170+171+ response.next = send_next # type: ignore172+ break173+174+ return response175+176+ def build_redirect_request(177+ self, request: AsyncRequest, response: AsyncResponse178+ ) -> AsyncRequest:179+ method = self.redirect_method(request, response)180+ url = self.redirect_url(request, response)181+ headers = self.redirect_headers(request, url)182+ content = self.redirect_content(request, method)183+ cookies = self.merge_cookies(request.cookies)184+ return AsyncRequest(185+ method=method, url=url, headers=headers, data=content, cookies=cookies186+ )187+188+ def redirect_method(self, request: AsyncRequest, response: AsyncResponse) -> str:189+ """190+ When being redirected we may want to change the method of the request191+ based on certain specs or browser behavior.192+ """193+ method = request.method194+195+ # https://tools.ietf.org/html/rfc7231#section-6.4.4196+ if response.status_code == codes.SEE_OTHER and method != "HEAD":197+ method = "GET"198+199+ # Do what the browsers do, despite standards...200+ # Turn 302s into GETs.201+ if response.status_code == codes.FOUND and method != "HEAD":202+ method = "GET"203+204+ # If a POST is responded to with a 301, turn it into a GET.205+ # This bizarre behaviour is explained in 'requests' issue 1704.206+ if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":207+ method = "GET"208+209+ return method210+211+ def redirect_url(self, request: AsyncRequest, response: AsyncResponse) -> URL:212+ """213+ Return the URL for the redirect to follow.214+ """215+ location = response.headers["Location"]216+217+ url = URL(location, allow_relative=True)218+219+ # Facilitate relative 'Location' headers, as allowed by RFC 7231.220+ # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')221+ if url.is_relative_url:222+ url = url.resolve_with(request.url)223+224+ # Attach previous fragment if needed (RFC 7231 7.1.2)225+ if request.url.fragment and not url.fragment:226+ url = url.copy_with(fragment=request.url.fragment)227+228+ return url229+230+ def redirect_headers(self, request: AsyncRequest, url: URL) -> Headers:231+ """232+ Strip Authorization headers when responses are redirected away from233+ the origin.234+ """235+ headers = Headers(request.headers)236+ if url.origin != request.url.origin:237+ del headers["Authorization"]238+ return headers239+240+ def redirect_content(self, request: AsyncRequest, method: str) -> bytes:241+ """242+ Return the body that should be used for the redirect request.243+ """244+ if method != request.method and method == "GET":245+ return b""246+ if request.is_streaming:247+ raise RedirectBodyUnavailable()248+ return request.content249+250+251+class AsyncClient(BaseClient):252 async def get(253 self,254 url: URLTypes,255 *,5 unmodified lines261 allow_redirects: bool = True,262 cert: CertTypes = None,263 verify: VerifyTypes = None,264 timeout: TimeoutTypes = None,75- ) -> Response:265+ ) -> AsyncResponse:266 return await self.request(267 "GET",268 url,269 params=params,19 unmodified lines289 allow_redirects: bool = True,290 cert: CertTypes = None,291 verify: VerifyTypes = None,292 timeout: TimeoutTypes = None,103- ) -> Response:293+ ) -> AsyncResponse:294 return await self.request(295 "OPTIONS",296 url,297 params=params,19 unmodified lines317 allow_redirects: bool = False, # Note: Differs to usual default.318 cert: CertTypes = None,319 verify: VerifyTypes = None,320 timeout: TimeoutTypes = None,131- ) -> Response:321+ ) -> AsyncResponse:322 return await self.request(323 "HEAD",324 url,325 params=params,10 unmodified lines336 async def post(337 self,338 url: URLTypes,339 *,150- data: RequestData = b"",340+ data: AsyncRequestData = b"",341 json: typing.Any = None,342 params: QueryParamTypes = None,343 headers: HeaderTypes = None,344 cookies: CookieTypes = None,2 unmodified lines347 allow_redirects: bool = True,348 cert: CertTypes = None,349 verify: VerifyTypes = None,350 timeout: TimeoutTypes = None,161- ) -> Response:351+ ) -> AsyncResponse:352 return await self.request(353 "POST",354 url,355 data=data,12 unmodified lines368 async def put(369 self,370 url: URLTypes,371 *,182- data: RequestData = b"",372+ data: AsyncRequestData = b"",373 json: typing.Any = None,374 params: QueryParamTypes = None,375 headers: HeaderTypes = None,376 cookies: CookieTypes = None,2 unmodified lines379 allow_redirects: bool = True,380 cert: CertTypes = None,381 verify: VerifyTypes = None,382 timeout: TimeoutTypes = None,193- ) -> Response:383+ ) -> AsyncResponse:384 return await self.request(385 "PUT",386 url,387 data=data,12 unmodified lines400 async def patch(401 self,402 url: URLTypes,403 *,214- data: RequestData = b"",404+ data: AsyncRequestData = b"",405 json: typing.Any = None,406 params: QueryParamTypes = None,407 headers: HeaderTypes = None,408 cookies: CookieTypes = None,2 unmodified lines411 allow_redirects: bool = True,412 cert: CertTypes = None,413 verify: VerifyTypes = None,414 timeout: TimeoutTypes = None,225- ) -> Response:415+ ) -> AsyncResponse:416 return await self.request(417 "PATCH",418 url,419 data=data,12 unmodified lines432 async def delete(433 self,434 url: URLTypes,435 *,246- data: RequestData = b"",436+ data: AsyncRequestData = b"",437 json: typing.Any = None,438 params: QueryParamTypes = None,439 headers: HeaderTypes = None,440 cookies: CookieTypes = None,2 unmodified lines443 allow_redirects: bool = True,444 cert: CertTypes = None,445 verify: VerifyTypes = None,446 timeout: TimeoutTypes = None,257- ) -> Response:447+ ) -> AsyncResponse:448 return await self.request(449 "DELETE",450 url,451 data=data,13 unmodified lines465 self,466 method: str,467 url: URLTypes,468 *,279- data: RequestData = b"",469+ data: AsyncRequestData = b"",470 json: typing.Any = None,471 params: QueryParamTypes = None,472 headers: HeaderTypes = None,473 cookies: CookieTypes = None,2 unmodified lines476 allow_redirects: bool = True,477 cert: CertTypes = None,478 verify: VerifyTypes = None,479 timeout: TimeoutTypes = None,290- ) -> Response:291- request = Request(480+ ) -> AsyncResponse:481+ request = AsyncRequest(482 method,483 url,484 data=data,485 json=json,11 unmodified lines497 timeout=timeout,498 )499 return response500 311- def merge_cookies(312- self, cookies: CookieTypes = None313- ) -> typing.Optional[CookieTypes]:314- if cookies or self.cookies:315- merged_cookies = Cookies(self.cookies)316- merged_cookies.update(cookies)317- return merged_cookies318- return cookies319-320- async def send(321- self,322- request: Request,323- *,324- stream: bool = False,325- auth: AuthTypes = None,326- allow_redirects: bool = True,327- verify: VerifyTypes = None,328- cert: CertTypes = None,329- timeout: TimeoutTypes = None,330- ) -> Response:331- if auth is None:332- auth = self.auth333-334- url = request.url335- if auth is None and (url.username or url.password):336- auth = HTTPBasicAuth(username=url.username, password=url.password)337-338- if auth is not None:339- if isinstance(auth, tuple):340- auth = HTTPBasicAuth(username=auth[0], password=auth[1])341- request = auth(request)342-343- response = await self.send_handling_redirects(344- request,345- stream=stream,346- verify=verify,347- cert=cert,348- timeout=timeout,349- allow_redirects=allow_redirects,350- )351- return response352-353- async def send_handling_redirects(354- self,355- request: Request,356- *,357- stream: bool = False,358- cert: CertTypes = None,359- verify: VerifyTypes = None,360- timeout: TimeoutTypes = None,361- allow_redirects: bool = True,362- history: typing.List[Response] = None,363- ) -> Response:364- if history is None:365- history = []366-367- while True:368- # We perform these checks here, so that calls to `response.next()`369- # will raise redirect errors if appropriate.370- if len(history) > self.max_redirects:371- raise TooManyRedirects()372- if request.url in [response.url for response in history]:373- raise RedirectLoop()374-375- response = await self.dispatch.send(376- request, stream=stream, verify=verify, cert=cert, timeout=timeout377- )378- response.history = list(history)379- self.cookies.extract_cookies(response)380- history = [response] + history381- if not response.is_redirect:382- break383-384- if allow_redirects:385- request = self.build_redirect_request(request, response)386- else:387-388- async def send_next() -> Response:389- nonlocal request, response, verify, cert, allow_redirects, timeout, history390- request = self.build_redirect_request(request, response)391- response = await self.send_handling_redirects(392- request,393- stream=stream,394- allow_redirects=allow_redirects,395- verify=verify,396- cert=cert,397- timeout=timeout,398- history=history,399- )400- return response401-402- response.next = send_next # type: ignore403- break404-405- return response406-407- def build_redirect_request(self, request: Request, response: Response) -> Request:408- method = self.redirect_method(request, response)409- url = self.redirect_url(request, response)410- headers = self.redirect_headers(request, url)411- content = self.redirect_content(request, method)412- cookies = self.merge_cookies(request.cookies)413- return Request(414- method=method, url=url, headers=headers, data=content, cookies=cookies415- )416-417- def redirect_method(self, request: Request, response: Response) -> str:418- """419- When being redirected we may want to change the method of the request420- based on certain specs or browser behavior.421- """422- method = request.method423-424- # https://tools.ietf.org/html/rfc7231#section-6.4.4425- if response.status_code == codes.SEE_OTHER and method != "HEAD":426- method = "GET"427-428- # Do what the browsers do, despite standards...429- # Turn 302s into GETs.430- if response.status_code == codes.FOUND and method != "HEAD":431- method = "GET"432-433- # If a POST is responded to with a 301, turn it into a GET.434- # This bizarre behaviour is explained in 'requests' issue 1704.435- if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":436- method = "GET"437-438- return method439-440- def redirect_url(self, request: Request, response: Response) -> URL:441- """442- Return the URL for the redirect to follow.443- """444- location = response.headers["Location"]445-446- url = URL(location, allow_relative=True)447-448- # Facilitate relative 'Location' headers, as allowed by RFC 7231.449- # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')450- if url.is_relative_url:451- url = url.resolve_with(request.url)452-453- # Attach previous fragment if needed (RFC 7231 7.1.2)454- if request.url.fragment and not url.fragment:455- url = url.copy_with(fragment=request.url.fragment)456-457- return url458-459- def redirect_headers(self, request: Request, url: URL) -> Headers:460- """461- Strip Authorization headers when responses are redirected away from462- the origin.463- """464- headers = Headers(request.headers)465- if url.origin != request.url.origin:466- del headers["Authorization"]467- return headers468-469- def redirect_content(self, request: Request, method: str) -> bytes:470- """471- Return the body that should be used for the redirect request.472- """473- if method != request.method and method == "GET":474- return b""475- if request.is_streaming:476- raise RedirectBodyUnavailable()477- return request.content478-501 async def close(self) -> None:502 await self.dispatch.close()503 504 async def __aenter__(self) -> "AsyncClient":7 unmodified lines512 ) -> None:513 await self.close()514 515 494-class Client:495- def __init__(496- self,497- auth: AuthTypes = None,498- cert: CertTypes = None,499- verify: VerifyTypes = True,500- timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,501- pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,502- max_redirects: int = DEFAULT_MAX_REDIRECTS,503- dispatch: Dispatcher = None,504- backend: ConcurrencyBackend = None,505- ) -> None:506- self._client = AsyncClient(507- auth=auth,508- verify=verify,509- cert=cert,510- timeout=timeout,511- pool_limits=pool_limits,512- max_redirects=max_redirects,513- dispatch=dispatch,514- backend=backend,515- )516- self._loop = asyncio.new_event_loop()516+class Client(BaseClient):517+ def _async_request_data(self, data: RequestData) -> AsyncRequestData:518+ """519+ If the request data is an bytes iterator then return an async bytes520+ iterator onto the request data.521+ """522+ if isinstance(data, (bytes, dict)):523+ return data524 518- @property519- def cookies(self) -> Cookies:520- return self._client.cookies525+ # Coerce an iterator into an async iterator, with each item in the526+ # iteration running as a thread-pooled operation.527+ assert hasattr(data, "__iter__")528+ return self.concurrency_backend.iterate_in_threadpool(data)529 530+ def _sync_data(self, data: AsyncResponseContent) -> ResponseContent:531+ if isinstance(data, bytes):532+ return data533+534+ # Coerce an async iterator into an iterator, with each item in the535+ # iteration run within the event loop.536+ assert hasattr(data, "__aiter__")537+ return self.concurrency_backend.iterate(data)538+539 def request(540 self,541 method: str,542 url: URLTypes,8 unmodified lines551 allow_redirects: bool = True,552 cert: CertTypes = None,553 verify: VerifyTypes = None,554 timeout: TimeoutTypes = None,538- ) -> SyncResponse:539- request = Request(555+ ) -> Response:556+ request = AsyncRequest(557 method,558 url,542- data=data,559+ data=self._async_request_data(data),560 json=json,561 params=params,562 headers=headers,546- cookies=self._client.merge_cookies(cookies),563+ cookies=self.merge_cookies(cookies),564 )548- response = self.send(549- request,550- stream=stream,565+ concurrency_backend = self.concurrency_backend566+567+ coroutine = self.send568+ args = [request]569+ kwargs = dict(570+ stream=True,571 auth=auth,572 allow_redirects=allow_redirects,573 verify=verify,574 cert=cert,575 timeout=timeout,576 )577+ async_response = concurrency_backend.run(coroutine, *args, **kwargs)578+579+ content = getattr(580+ async_response, "_raw_content", getattr(async_response, "_raw_stream", None)581+ )582+583+ sync_content = self._sync_data(content)584+585+ def sync_on_close() -> None:586+ nonlocal concurrency_backend, async_response587+ concurrency_backend.run(async_response.on_close)588+589+ response = Response(590+ status_code=async_response.status_code,591+ reason_phrase=async_response.reason_phrase,592+ protocol=async_response.protocol,593+ headers=async_response.headers,594+ content=sync_content,595+ on_close=sync_on_close,596+ request=async_response.request,597+ history=async_response.history,598+ )599+ if not stream:600+ try:601+ response.read()602+ finally:603+ response.close()604 return response605 606 def get(607 self,7 unmodified lines615 allow_redirects: bool = True,616 cert: CertTypes = None,617 verify: VerifyTypes = None,618 timeout: TimeoutTypes = None,572- ) -> SyncResponse:619+ ) -> Response:620 return self.request(621 "GET",622 url,623 headers=headers,18 unmodified lines642 allow_redirects: bool = True,643 cert: CertTypes = None,644 verify: VerifyTypes = None,645 timeout: TimeoutTypes = None,599- ) -> SyncResponse:646+ ) -> Response:647 return self.request(648 "OPTIONS",649 url,650 headers=headers,18 unmodified lines669 allow_redirects: bool = False, # Note: Differs to usual default.670 cert: CertTypes = None,671 verify: VerifyTypes = None,672 timeout: TimeoutTypes = None,626- ) -> SyncResponse:673+ ) -> Response:674 return self.request(675 "HEAD",676 url,677 headers=headers,20 unmodified lines698 allow_redirects: bool = True,699 cert: CertTypes = None,700 verify: VerifyTypes = None,701 timeout: TimeoutTypes = None,655- ) -> SyncResponse:702+ ) -> Response:703 return self.request(704 "POST",705 url,706 data=data,22 unmodified lines729 allow_redirects: bool = True,730 cert: CertTypes = None,731 verify: VerifyTypes = None,732 timeout: TimeoutTypes = None,686- ) -> SyncResponse:733+ ) -> Response:734 return self.request(735 "PUT",736 url,737 data=data,22 unmodified lines760 allow_redirects: bool = True,761 cert: CertTypes = None,762 verify: VerifyTypes = None,763 timeout: TimeoutTypes = None,717- ) -> SyncResponse:764+ ) -> Response:765 return self.request(766 "PATCH",767 url,768 data=data,22 unmodified lines791 allow_redirects: bool = True,792 cert: CertTypes = None,793 verify: VerifyTypes = None,794 timeout: TimeoutTypes = None,748- ) -> SyncResponse:795+ ) -> Response:796 return self.request(797 "DELETE",798 url,799 data=data,7 unmodified lines807 cert=cert,808 timeout=timeout,809 )810 764- def send(765- self,766- request: Request,767- *,768- stream: bool = False,769- auth: AuthTypes = None,770- allow_redirects: bool = True,771- verify: VerifyTypes = None,772- cert: CertTypes = None,773- timeout: TimeoutTypes = None,774- ) -> SyncResponse:775- response = self._loop.run_until_complete(776- self._client.send(777- request,778- stream=stream,779- auth=auth,780- allow_redirects=allow_redirects,781- verify=verify,782- cert=cert,783- timeout=timeout,784- )785- )786- return SyncResponse(response, self._loop)787-811 def close(self) -> None:789- self._loop.run_until_complete(self._client.close())812+ coroutine = self.dispatch.close813+ self.concurrency_backend.run(coroutine)814 815 def __enter__(self) -> "Client":816 return self817 7 unmodified linesmodified:httpcore/concurrency.py+29 added
7 unmodified lines8 protocols, and help keep the rest of the package more `async`/`await`9 based, and less strictly `asyncio`-specific.10 """11 import asyncio12+import functools13 import ssl14 import typing15 16 from .config import DEFAULT_TIMEOUT_CONFIG, PoolLimits, TimeoutConfig116 unmodified lines133 if not SSL_MONKEY_PATCH_APPLIED:134 ssl_monkey_patch()135 SSL_MONKEY_PATCH_APPLIED = True136 137+ @property138+ def loop(self) -> asyncio.AbstractEventLoop:139+ if not hasattr(self, "_loop"):140+ try:141+ self._loop = asyncio.get_event_loop()142+ except RuntimeError:143+ self._loop = asyncio.new_event_loop()144+ return self._loop145+146 async def connect(147 self,148 hostname: str,149 port: int,21 unmodified lines171 protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11172 173 return (reader, writer, protocol)174 175+ async def run_in_threadpool(176+ self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any177+ ) -> typing.Any:178+ if kwargs:179+ # loop.run_in_executor doesn't accept 'kwargs', so bind them in here180+ func = functools.partial(func, **kwargs)181+ return await self.loop.run_in_executor(None, func, *args)182+183+ def run(184+ self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any185+ ) -> typing.Any:186+ loop = self.loop187+ if loop.is_running():188+ self._loop = asyncio.new_event_loop()189+ try:190+ return self.loop.run_until_complete(coroutine(*args, **kwargs))191+ finally:192+ self._loop = loop193+194 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:195 return PoolSemaphore(limits)modified:httpcore/interfaces.py+92 added-13 removed
4 unmodified lines5 6 from .config import CertTypes, PoolLimits, TimeoutConfig, TimeoutTypes, VerifyTypes7 from .models import (8 URL,9+ AsyncRequest,10+ AsyncRequestData,11+ AsyncResponse,12 Headers,13 HeaderTypes,14 QueryParamTypes,15 Request,7 unmodified lines23 HTTP_11 = "HTTP/1.1"24 HTTP_2 = "HTTP/2"25 26 24-class Dispatcher:27+class AsyncDispatcher:28 """26- Base class for dispatcher classes, that handle sending the request.29+ Base class for async dispatcher classes, that handle sending the request.30 31 Stubs out the interface, as well as providing a `.request()` convienence32 implementation, to make it easy to use or test stand-alone dispatchers,33 without requiring a complete `Client` instance.3 unmodified lines37 self,38 method: str,39 url: URLTypes,40 *,41+ data: AsyncRequestData = b"",42+ params: QueryParamTypes = None,43+ headers: HeaderTypes = None,44+ verify: VerifyTypes = None,45+ cert: CertTypes = None,46+ timeout: TimeoutTypes = None47+ ) -> AsyncResponse:48+ request = AsyncRequest(method, url, data=data, params=params, headers=headers)49+ return await self.send(request, verify=verify, cert=cert, timeout=timeout)50+51+ async def send(52+ self,53+ request: AsyncRequest,54+ verify: VerifyTypes = None,55+ cert: CertTypes = None,56+ timeout: TimeoutTypes = None,57+ ) -> AsyncResponse:58+ raise NotImplementedError() # pragma: nocover59+60+ async def close(self) -> None:61+ pass # pragma: nocover62+63+ async def __aenter__(self) -> "AsyncDispatcher":64+ return self65+66+ async def __aexit__(67+ self,68+ exc_type: typing.Type[BaseException] = None,69+ exc_value: BaseException = None,70+ traceback: TracebackType = None,71+ ) -> None:72+ await self.close()73+74+75+class Dispatcher:76+ """77+ Base class for syncronous dispatcher classes, that handle sending the request.78+79+ Stubs out the interface, as well as providing a `.request()` convienence80+ implementation, to make it easy to use or test stand-alone dispatchers,81+ without requiring a complete `Client` instance.82+ """83+84+ def request(85+ self,86+ method: str,87+ url: URLTypes,88+ *,89 data: RequestData = b"",90 params: QueryParamTypes = None,91 headers: HeaderTypes = None,41- stream: bool = False,92 verify: VerifyTypes = None,93 cert: CertTypes = None,94 timeout: TimeoutTypes = None95 ) -> Response:96 request = Request(method, url, data=data, params=params, headers=headers)47- response = await self.send(48- request, stream=stream, verify=verify, cert=cert, timeout=timeout49- )50- return response97+ return self.send(request, verify=verify, cert=cert, timeout=timeout)98 52- async def send(99+ def send(100 self,101 request: Request,55- stream: bool = False,102 verify: VerifyTypes = None,103 cert: CertTypes = None,104 timeout: TimeoutTypes = None,105 ) -> Response:106 raise NotImplementedError() # pragma: nocover107 62- async def close(self) -> None:108+ def close(self) -> None:109 pass # pragma: nocover110 65- async def __aenter__(self) -> "Dispatcher":111+ def __enter__(self) -> "Dispatcher":112 return self113 68- async def __aexit__(114+ def __exit__(115 self,116 exc_type: typing.Type[BaseException] = None,117 exc_value: BaseException = None,118 traceback: TracebackType = None,119 ) -> None:74- await self.close()120+ self.close()121 122 123 class BaseReader:124 """48 unmodified lines173 raise NotImplementedError() # pragma: no cover174 175 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:176 raise NotImplementedError() # pragma: no cover177+178+ async def run_in_threadpool(179+ self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any180+ ) -> typing.Any:181+ raise NotImplementedError() # pragma: no cover182+183+ async def iterate_in_threadpool(self, iterator): # type: ignore184+ class IterationComplete(Exception):185+ pass186+187+ def next_wrapper(iterator): # type: ignore188+ try:189+ return next(iterator)190+ except StopIteration:191+ raise IterationComplete()192+193+ while True:194+ try:195+ yield await self.run_in_threadpool(next_wrapper, iterator)196+ except IterationComplete:197+ break198+199+ def run(200+ self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any201+ ) -> typing.Any:202+ raise NotImplementedError() # pragma: no cover203+204+ def iterate(self, async_iterator): # type: ignore205+ while True:206+ try:207+ yield self.run(async_iterator.__anext__)208+ except StopAsyncIteration:209+ breakmodified:httpcore/models.py+264 added-165 removed
1-import asyncio1 import cgi2 import email.message3 import json as jsonlib4 import typing41 unmodified lines46 CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]47 48 AuthTypes = typing.Union[49 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],51- typing.Callable[["Request"], "Request"],50+ typing.Callable[["AsyncRequest"], "AsyncRequest"],51 ]52 54-RequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]53+AsyncRequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]54 56-ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]55+RequestData = typing.Union[dict, bytes, typing.Iterator[bytes]]56 57+AsyncResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]58 59+ResponseContent = typing.Union[bytes, typing.Iterator[bytes]]60+61+62 class URL:63 def __init__(64 self,65 url: URLTypes,405 unmodified lines471 as_list = self.items()472 return f"{class_name}({as_list!r}{encoding_str})"473 474 472-class Request:475+class BaseRequest:476 def __init__(477 self,478 method: str,479 url: typing.Union[str, URL],480 *,478- data: RequestData = b"",479- json: typing.Any = None,481 params: QueryParamTypes = None,482 headers: HeaderTypes = None,483 cookies: CookieTypes = None,484 ):3 unmodified lines488 if cookies:489 self._cookies = Cookies(cookies)490 self._cookies.set_cookie_header(self)491 492+ def encode_json(self, json: typing.Any) -> bytes:493+ return jsonlib.dumps(json).encode("utf-8")494+495+ def urlencode_data(self, data: dict) -> bytes:496+ return urlencode(data, doseq=True).encode("utf-8")497+498+ def prepare(self) -> None:499+ content = getattr(self, "content", None) # type: bytes500+ is_streaming = getattr(self, "is_streaming", False)501+502+ auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]503+504+ has_user_agent = "user-agent" in self.headers505+ has_accept = "accept" in self.headers506+ has_content_length = (507+ "content-length" in self.headers or "transfer-encoding" in self.headers508+ )509+ has_accept_encoding = "accept-encoding" in self.headers510+511+ if not has_user_agent:512+ auto_headers.append((b"user-agent", b"httpcore"))513+ if not has_accept:514+ auto_headers.append((b"accept", b"*/*"))515+ if not has_content_length:516+ if is_streaming:517+ auto_headers.append((b"transfer-encoding", b"chunked"))518+ elif content:519+ content_length = str(len(content)).encode()520+ auto_headers.append((b"content-length", content_length))521+ if not has_accept_encoding:522+ auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))523+524+ for item in reversed(auto_headers):525+ self.headers.raw.insert(0, item)526+527+ @property528+ def cookies(self) -> "Cookies":529+ if not hasattr(self, "_cookies"):530+ self._cookies = Cookies()531+ return self._cookies532+533+ def __repr__(self) -> str:534+ class_name = self.__class__.__name__535+ url = str(self.url)536+ return f"<{class_name}({self.method!r}, {url!r})>"537+538+539+class AsyncRequest(BaseRequest):540+ def __init__(541+ self,542+ method: str,543+ url: typing.Union[str, URL],544+ *,545+ params: QueryParamTypes = None,546+ headers: HeaderTypes = None,547+ cookies: CookieTypes = None,548+ data: AsyncRequestData = b"",549+ json: typing.Any = None,550+ ):551+ super().__init__(552+ method=method, url=url, params=params, headers=headers, cookies=cookies553+ )554+555 if json is not None:492- data = jsonlib.dumps(json).encode("utf-8")556+ self.is_streaming = False557+ self.content = self.encode_json(json)558 self.headers["Content-Type"] = "application/json"494-495- if isinstance(data, bytes):559+ elif isinstance(data, bytes):560 self.is_streaming = False561 self.content = data562 elif isinstance(data, dict):563 self.is_streaming = False500- self.content = urlencode(data, doseq=True).encode("utf-8")564+ self.content = self.urlencode_data(data)565 self.headers["Content-Type"] = "application/x-www-form-urlencoded"566 else:567+ assert hasattr(data, "__aiter__")568 self.is_streaming = True569 self.content_aiter = data570 571 self.prepare()12 unmodified lines584 yield part585 elif self.content:586 yield self.content587 523- def prepare(self) -> None:524- auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]588 526- has_content_length = (527- "content-length" in self.headers or "transfer-encoding" in self.headers589+class Request(BaseRequest):590+ def __init__(591+ self,592+ method: str,593+ url: typing.Union[str, URL],594+ *,595+ params: QueryParamTypes = None,596+ headers: HeaderTypes = None,597+ cookies: CookieTypes = None,598+ data: RequestData = b"",599+ json: typing.Any = None,600+ ):601+ super().__init__(602+ method=method, url=url, params=params, headers=headers, cookies=cookies603 )529- has_accept_encoding = "accept-encoding" in self.headers604 531- if not has_content_length:532- if self.is_streaming:533- auto_headers.append((b"transfer-encoding", b"chunked"))534- elif self.content:535- content_length = str(len(self.content)).encode()536- auto_headers.append((b"content-length", content_length))537- if not has_accept_encoding:538- auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))605+ if json is not None:606+ self.is_streaming = False607+ self.content = self.encode_json(json)608+ self.headers["Content-Type"] = "application/json"609+ elif isinstance(data, bytes):610+ self.is_streaming = False611+ self.content = data612+ elif isinstance(data, dict):613+ self.is_streaming = False614+ self.content = self.urlencode_data(data)615+ self.headers["Content-Type"] = "application/x-www-form-urlencoded"616+ else:617+ assert hasattr(data, "__iter__")618+ self.is_streaming = True619+ self.content_iter = data620 540- for item in reversed(auto_headers):541- self.headers.raw.insert(0, item)621+ self.prepare()622 543- @property544- def cookies(self) -> "Cookies":545- if not hasattr(self, "_cookies"):546- self._cookies = Cookies()547- return self._cookies623+ def read(self) -> bytes:624+ if not hasattr(self, "content"):625+ self.content = b"".join([part for part in self.stream()])626+ return self.content627 549- def __repr__(self) -> str:550- class_name = self.__class__.__name__551- url = str(self.url)552- return f"<{class_name}({self.method!r}, {url!r})>"628+ def stream(self) -> typing.Iterator[bytes]:629+ if self.is_streaming:630+ for part in self.content_iter:631+ yield part632+ elif self.content:633+ yield self.content634 635 555-class Response:636+class BaseResponse:637 def __init__(638 self,639 status_code: int,640 *,641 reason_phrase: str = None,642 protocol: str = None,643 headers: HeaderTypes = None,563- content: ResponseContent = b"",644+ request: BaseRequest = None,645 on_close: typing.Callable = None,565- request: Request = None,566- history: typing.List["Response"] = None,646 ):647 self.status_code = StatusCode.enum_or_int(status_code)648 self.reason_phrase = StatusCode.get_reason_phrase(status_code)649 self.protocol = protocol650 self.headers = Headers(headers)651 573- if isinstance(content, bytes):574- self.is_closed = True575- self.is_stream_consumed = True576- self._raw_content = content577- else:578- self.is_closed = False579- self.is_stream_consumed = False580- self._raw_stream = content581-582- self.on_close = on_close652 self.request = request584- self.history = [] if history is None else list(history)653+ self.on_close = on_close654 self.next = None # typing.Optional[typing.Callable]655 656 @property657 def url(self) -> typing.Optional[URL]:7 unmodified lines665 @property666 def content(self) -> bytes:667 if not hasattr(self, "_content"):668 if hasattr(self, "_raw_content"):669+ raw_content = getattr(self, "_raw_content") # type: bytes600- content = self.decoder.decode(self._raw_content)670+ content = self.decoder.decode(raw_content)671 content += self.decoder.flush()672 self._content = content673 else:674 raise ResponseNotRead()76 unmodified lines751 self._decoder = IdentityDecoder()752 753 return self._decoder754 755+ @property756+ def is_redirect(self) -> bool:757+ return StatusCode.is_redirect(self.status_code) and "location" in self.headers758+759+ def raise_for_status(self) -> None:760+ """761+ Raise the `HttpError` if one occurred.762+ """763+ message = (764+ "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"765+ "For more information check: https://httpstatuses.com/{0.status_code}"766+ )767+768+ if StatusCode.is_client_error(self.status_code):769+ message = message.format(self, error_type="Client Error")770+ elif StatusCode.is_server_error(self.status_code):771+ message = message.format(self, error_type="Server Error")772+ else:773+ message = ""774+775+ if message:776+ raise HttpError(message)777+778+ def json(self) -> typing.Any:779+ return jsonlib.loads(self.content.decode("utf-8"))780+781+ @property782+ def cookies(self) -> "Cookies":783+ if not hasattr(self, "_cookies"):784+ assert self.request is not None785+ self._cookies = Cookies()786+ self._cookies.extract_cookies(self)787+ return self._cookies788+789+ def __repr__(self) -> str:790+ return f"<Response({self.status_code}, {self.reason_phrase!r})>"791+792+793+class AsyncResponse(BaseResponse):794+ def __init__(795+ self,796+ status_code: int,797+ *,798+ reason_phrase: str = None,799+ protocol: str = None,800+ headers: HeaderTypes = None,801+ content: AsyncResponseContent = b"",802+ on_close: typing.Callable = None,803+ request: AsyncRequest = None,804+ history: typing.List["BaseResponse"] = None,805+ ):806+ super().__init__(807+ status_code=status_code,808+ reason_phrase=reason_phrase,809+ protocol=protocol,810+ headers=headers,811+ request=request,812+ on_close=on_close,813+ )814+815+ self.history = [] if history is None else list(history)816+817+ if isinstance(content, bytes):818+ self.is_closed = True819+ self.is_stream_consumed = True820+ self._raw_content = content821+ else:822+ self.is_closed = False823+ self.is_stream_consumed = False824+ self._raw_stream = content825+826 async def read(self) -> bytes:827 """828 Read and return the response content.829 """39 unmodified lines869 self.is_closed = True870 if self.on_close is not None:871 await self.on_close()872 732- @property733- def is_redirect(self) -> bool:734- return StatusCode.is_redirect(self.status_code) and "location" in self.headers873 736- def raise_for_status(self) -> None:737- """738- Raise the `HttpError` if one occurred.739- """740- message = (741- "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"742- "For more information check: https://httpstatuses.com/{0.status_code}"874+class Response(BaseResponse):875+ def __init__(876+ self,877+ status_code: int,878+ *,879+ reason_phrase: str = None,880+ protocol: str = None,881+ headers: HeaderTypes = None,882+ content: ResponseContent = b"",883+ on_close: typing.Callable = None,884+ request: Request = None,885+ history: typing.List["BaseResponse"] = None,886+ ):887+ super().__init__(888+ status_code=status_code,889+ reason_phrase=reason_phrase,890+ protocol=protocol,891+ headers=headers,892+ request=request,893+ on_close=on_close,894 )895 745- if StatusCode.is_client_error(self.status_code):746- message = message.format(self, error_type="Client Error")747- elif StatusCode.is_server_error(self.status_code):748- message = message.format(self, error_type="Server Error")896+ self.history = [] if history is None else list(history)897+898+ if isinstance(content, bytes):899+ self.is_closed = True900+ self.is_stream_consumed = True901+ self._raw_content = content902 else:750- message = ""903+ self.is_closed = False904+ self.is_stream_consumed = False905+ self._raw_stream = content906 752- if message:753- raise HttpError(message)754-755- def json(self) -> typing.Any:756- return jsonlib.loads(self.content.decode("utf-8"))757-758- @property759- def cookies(self) -> "Cookies":760- if not hasattr(self, "_cookies"):761- assert self.request is not None762- self._cookies = Cookies()763- self._cookies.extract_cookies(self)764- return self._cookies765-766- def __repr__(self) -> str:767- return f"<Response({self.status_code}, {self.reason_phrase!r})>"768-769-770-class SyncResponse:771- """772- A thread-synchronous response. This class proxies onto a `Response`773- instance, providing standard synchronous interfaces where required.774- """775-776- def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):777- self._response = response778- self._loop = loop779-780- @property781- def status_code(self) -> int:782- return self._response.status_code783-784- @property785- def reason_phrase(self) -> str:786- return self._response.reason_phrase787-788- @property789- def protocol(self) -> typing.Optional[str]:790- return self._response.protocol791-792- @property793- def url(self) -> typing.Optional[URL]:794- return self._response.url795-796- @property797- def request(self) -> typing.Optional[Request]:798- return self._response.request799-800- @property801- def headers(self) -> Headers:802- return self._response.headers803-804- @property805- def content(self) -> bytes:806- return self._response.content807-808- @property809- def text(self) -> str:810- return self._response.text811-812- @property813- def encoding(self) -> str:814- return self._response.encoding815-816- @property817- def is_redirect(self) -> bool:818- return self._response.is_redirect819-820- def raise_for_status(self) -> None:821- return self._response.raise_for_status()822-823- def json(self) -> typing.Any:824- return self._response.json()825-907 def read(self) -> bytes:827- return self._loop.run_until_complete(self._response.read())908+ """909+ Read and return the response content.910+ """911+ if not hasattr(self, "_content"):912+ self._content = b"".join([part for part in self.stream()])913+ return self._content914 915 def stream(self) -> typing.Iterator[bytes]:830- inner = self._response.stream()831- while True:832- try:833- yield self._loop.run_until_complete(inner.__anext__())834- except StopAsyncIteration:835- break916+ """917+ A byte-iterator over the decoded response content.918+ This allows us to handle gzip, deflate, and brotli encoded responses.919+ """920+ if hasattr(self, "_content"):921+ yield self._content922+ else:923+ for chunk in self.raw():924+ yield self.decoder.decode(chunk)925+ yield self.decoder.flush()926 927 def raw(self) -> typing.Iterator[bytes]:838- inner = self._response.raw()839- while True:840- try:841- yield self._loop.run_until_complete(inner.__anext__())842- except StopAsyncIteration:843- break928+ """929+ A byte-iterator over the raw response content.930+ """931+ if hasattr(self, "_raw_content"):932+ yield self._raw_content933+ else:934+ if self.is_stream_consumed:935+ raise StreamConsumed()936+ if self.is_closed:937+ raise ResponseClosed()938 939+ self.is_stream_consumed = True940+ for part in self._raw_stream:941+ yield part942+ self.close()943+944 def close(self) -> None:846- return self._loop.run_until_complete(self._response.close())945+ """946+ Close the response and release the connection.947+ Automatically called if the response body is read to completion.948+ """949+ if not self.is_closed:950+ self.is_closed = True951+ if self.on_close is not None:952+ self.on_close()953 848- @property849- def cookies(self) -> "Cookies":850- return self._response.cookies954 852- def __repr__(self) -> str:853- return f"<Response({self.status_code}, {self.reason_phrase!r})>"854-855-955 class Cookies(MutableMapping):956 """957 HTTP Cookies, as a mutable mapping.958 """10 unmodified lines969 self.jar.set_cookie(cookie)970 else:971 self.jar = cookies972 874- def extract_cookies(self, response: Response) -> None:973+ def extract_cookies(self, response: BaseResponse) -> None:974 """975 Loads any cookies based on the response `Set-Cookie` headers.976 """977 assert response.request is not None1 unmodified line979 urllib_request = self._CookieCompatRequest(response.request)980 981 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore982 884- def set_cookie_header(self, request: Request) -> None:983+ def set_cookie_header(self, request: BaseRequest) -> None:984 """985 Sets an appropriate 'Cookie:' HTTP header on the `Request`.986 """987 urllib_request = self._CookieCompatRequest(request)110 unmodified lines1098 Wraps a `Request` instance up in a compatability interface suitable1099 for use with `CookieJar` operations.1100 """1101 1003- def __init__(self, request: Request) -> None:1102+ def __init__(self, request: BaseRequest) -> None:1103 super().__init__(1104 url=str(request.url),1105 headers=dict(request.headers),1106 method=request.method,9 unmodified lines1116 Wraps a `Request` instance up in a compatability interface suitable1117 for use with `CookieJar` operations.1118 """1119 1021- def __init__(self, response: Response):1120+ def __init__(self, response: BaseResponse):1121 self.response = response1122 1123 def info(self) -> email.message.Message:1124 info = email.message.Message()3 unmodified linesmodified:tests/client/test_auth.py+7 added-8 removed
2 unmodified lines3 import pytest4 5 from httpcore import (6 URL,7+ AsyncDispatcher,8+ AsyncRequest,9+ AsyncResponse,10 CertTypes,11 Client,9- Dispatcher,10- Request,11- Response,12 TimeoutTypes,13 VerifyTypes,14 )15 16 17-class MockDispatch(Dispatcher):17+class MockDispatch(AsyncDispatcher):18 async def send(19 self,20- request: Request,21- stream: bool = False,20+ request: AsyncRequest,21 verify: VerifyTypes = None,22 cert: CertTypes = None,23 timeout: TimeoutTypes = None,25- ) -> Response:24+ ) -> AsyncResponse:25 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()27- return Response(200, content=body, request=request)26+ return AsyncResponse(200, content=body, request=request)27 28 29 def test_basic_auth():30 url = "https://example.org/"42 unmodified linesmodified:tests/client/test_cookies.py+8 added-9 removed
3 unmodified lines4 import pytest5 6 from httpcore import (7 URL,8+ AsyncDispatcher,9+ AsyncRequest,10+ AsyncResponse,11 CertTypes,12 Client,13 Cookies,11- Dispatcher,12- Request,13- Response,14 TimeoutTypes,15 VerifyTypes,16 )17 18 19-class MockDispatch(Dispatcher):19+class MockDispatch(AsyncDispatcher):20 async def send(21 self,22- request: Request,23- stream: bool = False,22+ request: AsyncRequest,23 verify: VerifyTypes = None,24 cert: CertTypes = None,25 timeout: TimeoutTypes = None,27- ) -> Response:26+ ) -> AsyncResponse:27 if request.url.path.startswith("/echo_cookies"):28 body = json.dumps({"cookies": request.headers.get("Cookie")}).encode()30- return Response(200, content=body, request=request)29+ return AsyncResponse(200, content=body, request=request)30 elif request.url.path.startswith("/set_cookie"):31 headers = {"set-cookie": "example-name=example-value"}33- return Response(200, headers=headers, request=request)32+ return AsyncResponse(200, headers=headers, request=request)33 34 35 def test_set_cookie():36 """91 unmodified linesmodified:tests/client/test_redirects.py+20 added-17 removed
4 unmodified lines5 6 from httpcore import (7 URL,8 AsyncClient,9+ AsyncDispatcher,10+ AsyncRequest,11+ AsyncResponse,12 CertTypes,10- Dispatcher,13 RedirectBodyUnavailable,14 RedirectLoop,15 Request,16 Response,3 unmodified lines20 codes,21 )22 23 22-class MockDispatch(Dispatcher):24+class MockDispatch(AsyncDispatcher):25 async def send(26 self,25- request: Request,26- stream: bool = False,27+ request: AsyncRequest,28 verify: VerifyTypes = None,29 cert: CertTypes = None,30 timeout: TimeoutTypes = None,30- ) -> Response:31+ ) -> AsyncResponse:32 if request.url.path == "/redirect_301":33 status_code = codes.MOVED_PERMANENTLY34 headers = {"location": "https://example.org/"}34- return Response(status_code, headers=headers, request=request)35+ return AsyncResponse(status_code, headers=headers, request=request)36 37 elif request.url.path == "/redirect_302":38 status_code = codes.FOUND39 headers = {"location": "https://example.org/"}39- return Response(status_code, headers=headers, request=request)40+ return AsyncResponse(status_code, headers=headers, request=request)41 42 elif request.url.path == "/redirect_303":43 status_code = codes.SEE_OTHER44 headers = {"location": "https://example.org/"}44- return Response(status_code, headers=headers, request=request)45+ return AsyncResponse(status_code, headers=headers, request=request)46 47 elif request.url.path == "/relative_redirect":48 headers = {"location": "/"}48- return Response(codes.SEE_OTHER, headers=headers, request=request)49+ return AsyncResponse(codes.SEE_OTHER, headers=headers, request=request)50 51 elif request.url.path == "/no_scheme_redirect":52 headers = {"location": "//example.org/"}52- return Response(codes.SEE_OTHER, headers=headers, request=request)53+ return AsyncResponse(codes.SEE_OTHER, headers=headers, request=request)54 55 elif request.url.path == "/multiple_redirects":56 params = parse_qs(request.url.query)57 count = int(params.get("count", "0")[0])2 unmodified lines60 location = "/multiple_redirects"61 if redirect_count:62 location += "?count=" + str(redirect_count)63 headers = {"location": location} if count else {}63- return Response(code, headers=headers, request=request)64+ return AsyncResponse(code, headers=headers, request=request)65 66 if request.url.path == "/redirect_loop":67 headers = {"location": "/redirect_loop"}67- return Response(codes.SEE_OTHER, headers=headers, request=request)68+ return AsyncResponse(codes.SEE_OTHER, headers=headers, request=request)69 70 elif request.url.path == "/cross_domain":71 headers = {"location": "https://example.org/cross_domain_target"}71- return Response(codes.SEE_OTHER, headers=headers, request=request)72+ return AsyncResponse(codes.SEE_OTHER, headers=headers, request=request)73 74 elif request.url.path == "/cross_domain_target":75 headers = dict(request.headers.items())76 content = json.dumps({"headers": headers}).encode()76- return Response(codes.OK, content=content, request=request)77+ return AsyncResponse(codes.OK, content=content, request=request)78 79 elif request.url.path == "/redirect_body":80 await request.read()81 headers = {"location": "/redirect_body_target"}81- return Response(codes.PERMANENT_REDIRECT, headers=headers, request=request)82+ return AsyncResponse(83+ codes.PERMANENT_REDIRECT, headers=headers, request=request84+ )85 86 elif request.url.path == "/redirect_body_target":87 content = await request.read()88 body = json.dumps({"body": content.decode()}).encode()86- return Response(codes.OK, content=body, request=request)89+ return AsyncResponse(codes.OK, content=body, request=request)90 88- return Response(codes.OK, content=b"Hello, world!", request=request)91+ return AsyncResponse(codes.OK, content=b"Hello, world!", request=request)92 93 94 @pytest.mark.asyncio95 async def test_redirect_301():151 unmodified linesmodified:tests/dispatch/test_connection_pools.py+12 added-5 removed
8 unmodified lines9 Connections should default to staying in a keep-alive state.10 """11 async with httpcore.ConnectionPool() as http:12 response = await http.request("GET", "http://127.0.0.1:8000/")13+ await response.read()14 assert len(http.active_connections) == 015 assert len(http.keepalive_connections) == 116 17 response = await http.request("GET", "http://127.0.0.1:8000/")18+ await response.read()19 assert len(http.active_connections) == 020 assert len(http.keepalive_connections) == 121 22 3 unmodified lines26 Connnections to differing connection keys should result in multiple connections.27 """28 async with httpcore.ConnectionPool() as http:29 response = await http.request("GET", "http://127.0.0.1:8000/")30+ await response.read()31 assert len(http.active_connections) == 032 assert len(http.keepalive_connections) == 133 34 response = await http.request("GET", "http://localhost:8000/")35+ await response.read()36 assert len(http.active_connections) == 037 assert len(http.keepalive_connections) == 238 39 5 unmodified lines45 pool_limits = httpcore.PoolLimits(soft_limit=1)46 47 async with httpcore.ConnectionPool(pool_limits=pool_limits) as http:48 response = await http.request("GET", "http://127.0.0.1:8000/")49+ await response.read()50 assert len(http.active_connections) == 051 assert len(http.keepalive_connections) == 152 53 response = await http.request("GET", "http://localhost:8000/")54+ await response.read()55 assert len(http.active_connections) == 056 assert len(http.keepalive_connections) == 157 58 2 unmodified lines61 """62 A streaming request should hold the connection open until the response is read.63 """64 async with httpcore.ConnectionPool() as http:59- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)65+ response = await http.request("GET", "http://127.0.0.1:8000/")66 assert len(http.active_connections) == 167 assert len(http.keepalive_connections) == 068 69 await response.read()7 unmodified lines77 """78 Multiple conncurrent requests should open multiple conncurrent connections.79 """80 async with httpcore.ConnectionPool() as http:75- response_a = await http.request("GET", "http://127.0.0.1:8000/", stream=True)81+ response_a = await http.request("GET", "http://127.0.0.1:8000/")82 assert len(http.active_connections) == 183 assert len(http.keepalive_connections) == 084 79- response_b = await http.request("GET", "http://127.0.0.1:8000/", stream=True)85+ response_b = await http.request("GET", "http://127.0.0.1:8000/")86 assert len(http.active_connections) == 287 assert len(http.keepalive_connections) == 088 89 await response_b.read()12 unmodified lines102 """103 headers = [(b"connection", b"close")]104 async with httpcore.ConnectionPool() as http:105 response = await http.request("GET", "http://127.0.0.1:8000/", headers=headers)106+ await response.read()107 assert len(http.active_connections) == 0108 assert len(http.keepalive_connections) == 0109 110 2 unmodified lines113 """114 A standard close should keep the connection open.115 """116 async with httpcore.ConnectionPool() as http:110- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)117+ response = await http.request("GET", "http://127.0.0.1:8000/")118 await response.read()119 await response.close()120 assert len(http.active_connections) == 0121 assert len(http.keepalive_connections) == 14 unmodified lines126 """127 A premature close should close the connection.128 """129 async with httpcore.ConnectionPool() as http:123- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)130+ response = await http.request("GET", "http://127.0.0.1:8000/")131 await response.close()132 assert len(http.active_connections) == 0133 assert len(http.keepalive_connections) == 0modified:tests/dispatch/test_connections.py+3 added
5 unmodified lines6 @pytest.mark.asyncio7 async def test_get(server):8 conn = HTTPConnection(origin="http://127.0.0.1:8000/")9 response = await conn.request("GET", "http://127.0.0.1:8000/")10+ await response.read()11 assert response.status_code == 20012 assert response.content == b"Hello, world!"13 14 12 unmodified lines27 An HTTPS request, with default SSL configuration set on the client.28 """29 conn = HTTPConnection(origin="https://127.0.0.1:8001/", verify=False)30 response = await conn.request("GET", "https://127.0.0.1:8001/")31+ await response.read()32 assert response.status_code == 20033 assert response.content == b"Hello, world!"34 35 3 unmodified lines39 An HTTPS request, with SSL configuration set on the request.40 """41 conn = HTTPConnection(origin="https://127.0.0.1:8001/")42 response = await conn.request("GET", "https://127.0.0.1:8001/", verify=False)43+ await response.read()44 assert response.status_code == 20045 assert response.content == b"Hello, world!"added:tests/dispatch/test_threaded.py+100 added
1+import json2+3+import pytest4+5+from httpcore import (6+ CertTypes,7+ Client,8+ Dispatcher,9+ Request,10+ Response,11+ TimeoutTypes,12+ VerifyTypes,13+)14+15+16+def streaming_body():17+ for part in [b"Hello", b", ", b"world!"]:18+ yield part19+20+21+class MockDispatch(Dispatcher):22+ def send(23+ self,24+ request: Request,25+ verify: VerifyTypes = None,26+ cert: CertTypes = None,27+ timeout: TimeoutTypes = None,28+ ) -> Response:29+ if request.url.path == "/streaming_response":30+ return Response(200, content=streaming_body(), request=request)31+ elif request.url.path == "/echo_request_body":32+ content = request.read()33+ return Response(200, content=content, request=request)34+ elif request.url.path == "/echo_request_body_streaming":35+ content = b"".join([part for part in request.stream()])36+ return Response(200, content=content, request=request)37+ else:38+ body = json.dumps({"hello": "world"}).encode()39+ return Response(200, content=body, request=request)40+41+42+def test_threaded_dispatch():43+ """44+ Use a syncronous 'Dispatcher' class with the client.45+ Calls to the dispatcher will end up running within a thread pool.46+ """47+ url = "https://example.org/"48+ with Client(dispatch=MockDispatch()) as client:49+ response = client.get(url)50+51+ assert response.status_code == 20052+ assert response.json() == {"hello": "world"}53+54+55+def test_threaded_streaming_response():56+ url = "https://example.org/streaming_response"57+ with Client(dispatch=MockDispatch()) as client:58+ response = client.get(url)59+60+ assert response.status_code == 20061+ assert response.text == "Hello, world!"62+63+64+def test_threaded_streaming_request():65+ url = "https://example.org/echo_request_body"66+ with Client(dispatch=MockDispatch()) as client:67+ response = client.post(url, data=streaming_body())68+69+ assert response.status_code == 20070+ assert response.text == "Hello, world!"71+72+73+def test_threaded_request_body():74+ url = "https://example.org/echo_request_body"75+ with Client(dispatch=MockDispatch()) as client:76+ response = client.post(url, data=b"Hello, world!")77+78+ assert response.status_code == 20079+ assert response.text == "Hello, world!"80+81+82+def test_threaded_request_body_streaming():83+ url = "https://example.org/echo_request_body_streaming"84+ with Client(dispatch=MockDispatch()) as client:85+ response = client.post(url, data=b"Hello, world!")86+87+ assert response.status_code == 20088+ assert response.text == "Hello, world!"89+90+91+def test_dispatch_class():92+ """93+ Use a syncronous 'Dispatcher' class directly.94+ """95+ url = "https://example.org/"96+ with MockDispatch() as dispatcher:97+ response = dispatcher.request("GET", url)98+99+ assert response.status_code == 200100+ assert response.json() == {"hello": "world"}modified:tests/models/test_requests.py+23 added-48 removed
8 unmodified lines9 10 11 def test_no_content():12 request = httpcore.Request("GET", "http://example.org")13- request.prepare()14- assert request.headers == httpcore.Headers(15- [(b"accept-encoding", b"deflate, gzip, br")]16- )13+ assert "Content-Length" not in request.headers14 15 16 def test_content_length_header():17 request = httpcore.Request("POST", "http://example.org", data=b"test 123")21- request.prepare()22- assert request.headers == httpcore.Headers(23- [24- (b"content-length", b"8"),25- (b"accept-encoding", b"deflate, gzip, br"),26- ]27- )18+ assert request.headers["Content-Length"] == "8"19 20 21 def test_url_encoded_data():31- request = httpcore.Request("POST", "http://example.org", data={"test": "123"})32- request.prepare()33- assert request.headers == httpcore.Headers(34- [35- (b"content-length", b"8"),36- (b"accept-encoding", b"deflate, gzip, br"),37- (b"content-type", b"application/x-www-form-urlencoded"),38- ]39- )40- assert request.content == b"test=123"22+ for RequestClass in (httpcore.Request, httpcore.AsyncRequest):23+ request = RequestClass("POST", "http://example.org", data={"test": "123"})24+ assert request.headers["Content-Type"] == "application/x-www-form-urlencoded"25+ assert request.content == b"test=123"26 27 28+def test_json_encoded_data():29+ for RequestClass in (httpcore.Request, httpcore.AsyncRequest):30+ request = RequestClass("POST", "http://example.org", json={"test": 123})31+ assert request.headers["Content-Type"] == "application/json"32+ assert request.content == b'{"test": 123}'33+34+35 def test_transfer_encoding_header():44- async def streaming_body(data):36+ def streaming_body(data):37 yield data # pragma: nocover38 39 data = streaming_body(b"test 123")40 41 request = httpcore.Request("POST", "http://example.org", data=data)50- request.prepare()51- assert request.headers == httpcore.Headers(52- [53- (b"transfer-encoding", b"chunked"),54- (b"accept-encoding", b"deflate, gzip, br"),55- ]56- )42+ assert "Content-Length" not in request.headers43+ assert request.headers["Transfer-Encoding"] == "chunked"44 45 46 def test_override_host_header():60- headers = [(b"host", b"1.2.3.4:80")]47+ headers = {"host": "1.2.3.4:80"}48 49 request = httpcore.Request("GET", "http://example.org", headers=headers)63- request.prepare()64- assert request.headers == httpcore.Headers(65- [(b"accept-encoding", b"deflate, gzip, br"), (b"host", b"1.2.3.4:80")]66- )50+ assert request.headers["Host"] == "1.2.3.4:80"51 52 53 def test_override_accept_encoding_header():70- headers = [(b"accept-encoding", b"identity")]54+ headers = {"Accept-Encoding": "identity"}55 56 request = httpcore.Request("GET", "http://example.org", headers=headers)73- request.prepare()74- assert request.headers == httpcore.Headers(75- [(b"accept-encoding", b"identity")]76- )57+ assert request.headers["Accept-Encoding"] == "identity"58 59 60 def test_override_content_length_header():80- async def streaming_body(data):61+ def streaming_body(data):62 yield data # pragma: nocover63 64 data = streaming_body(b"test 123")84- headers = [(b"content-length", b"8")]65+ headers = {"Content-Length": "8"}66 67 request = httpcore.Request("POST", "http://example.org", data=data, headers=headers)87- request.prepare()88- assert request.headers == httpcore.Headers(89- [90- (b"accept-encoding", b"deflate, gzip, br"),91- (b"content-length", b"8"),92- ]93- )68+ assert request.headers["Content-Length"] == "8"69 70 71 def test_url():72 url = "http://example.org"21 unmodified linesmodified:tests/models/test_responses.py+73 added-17 removed
1 unmodified line2 3 import httpcore4 5 6-async def streaming_body():6+def streaming_body():7 yield b"Hello, "8 yield b"world!"9 10 11+async def async_streaming_body():12+ yield b"Hello, "13+ yield b"world!"14+15+16 def test_response():17 response = httpcore.Response(200, content=b"Hello, world!")18 assert response.status_code == 20019 assert response.reason_phrase == "OK"89 unmodified lines109 assert response.text == "Snowman: â\x98\x83"110 assert response.encoding == "iso-8859-1"111 112 108-@pytest.mark.asyncio109-async def test_read_response():113+def test_read_response():114 response = httpcore.Response(200, content=b"Hello, world!")115 116 assert response.status_code == 200117 assert response.text == "Hello, world!"118 assert response.encoding == "ascii"119 assert response.is_closed120 117- content = await response.read()121+ content = response.read()122 123 assert content == b"Hello, world!"124 assert response.content == b"Hello, world!"125 assert response.is_closed126 127 124-@pytest.mark.asyncio125-async def test_raw_interface():128+def test_raw_interface():129 response = httpcore.Response(200, content=b"Hello, world!")130 131 raw = b""129- async for part in response.raw():132+ for part in response.raw():133 raw += part134 assert raw == b"Hello, world!"135 136 134-@pytest.mark.asyncio135-async def test_stream_interface():137+def test_stream_interface():138 response = httpcore.Response(200, content=b"Hello, world!")139 140 content = b""139- async for part in response.stream():141+ for part in response.stream():142 content += part143 assert content == b"Hello, world!"144 145 146 @pytest.mark.asyncio147+async def test_async_stream_interface():148+ response = httpcore.AsyncResponse(200, content=b"Hello, world!")149+150+ content = b""151+ async for part in response.stream():152+ content += part153+ assert content == b"Hello, world!"154+155+145-async def test_stream_interface_after_read():156+def test_stream_interface_after_read():157 response = httpcore.Response(200, content=b"Hello, world!")158 159+ response.read()160+161+ content = b""162+ for part in response.stream():163+ content += part164+ assert content == b"Hello, world!"165+166+167+@pytest.mark.asyncio168+async def test_async_stream_interface_after_read():169+ response = httpcore.AsyncResponse(200, content=b"Hello, world!")170+171 await response.read()172 173 content = b""174 async for part in response.stream():175 content += part176 assert content == b"Hello, world!"177 178 156-@pytest.mark.asyncio157-async def test_streaming_response():179+def test_streaming_response():180 response = httpcore.Response(200, content=streaming_body())181 182 assert response.status_code == 200183 assert not response.is_closed184 163- content = await response.read()185+ content = response.read()186 187 assert content == b"Hello, world!"188 assert response.content == b"Hello, world!"189 assert response.is_closed190 191 192 @pytest.mark.asyncio193+async def test_async_streaming_response():194+ response = httpcore.AsyncResponse(200, content=async_streaming_body())195+196+ assert response.status_code == 200197+ assert not response.is_closed198+199+ content = await response.read()200+201+ assert content == b"Hello, world!"202+ assert response.content == b"Hello, world!"203+ assert response.is_closed204+205+171-async def test_cannot_read_after_stream_consumed():206+def test_cannot_read_after_stream_consumed():207 response = httpcore.Response(200, content=streaming_body())208 209 content = b""210+ for part in response.stream():211+ content += part212+213+ with pytest.raises(httpcore.StreamConsumed):214+ response.read()215+216+217+@pytest.mark.asyncio218+async def test_async_cannot_read_after_stream_consumed():219+ response = httpcore.AsyncResponse(200, content=async_streaming_body())220+221+ content = b""222 async for part in response.stream():223 content += part224 225 with pytest.raises(httpcore.StreamConsumed):226 await response.read()227 228 182-@pytest.mark.asyncio183-async def test_cannot_read_after_response_closed():229+def test_cannot_read_after_response_closed():230 response = httpcore.Response(200, content=streaming_body())231 232+ response.close()233+234+ with pytest.raises(httpcore.ResponseClosed):235+ response.read()236+237+238+@pytest.mark.asyncio239+async def test_async_cannot_read_after_response_closed():240+ response = httpcore.AsyncResponse(200, content=async_streaming_body())241+242 await response.close()243 244 with pytest.raises(httpcore.ResponseClosed):245 await response.read()7 unmodified linesmodified:tests/test_api.py+12 added
37 unmodified lines38 assert response.reason_phrase == "OK"39 40 41 @threadpool42+def test_post_byte_iterator(server):43+ def data():44+ yield b"Hello"45+ yield b", "46+ yield b"world!"47+48+ response = httpcore.post("http://127.0.0.1:8000/", data=data())49+ assert response.status_code == 20050+ assert response.reason_phrase == "OK"51+52+53+@threadpool54 def test_options(server):55 response = httpcore.options("http://127.0.0.1:8000/")56 assert response.status_code == 20057 assert response.reason_phrase == "OK"28 unmodified linesmodified:tests/test_decoders.py+3 added-4 removed
62 unmodified lines63 response = httpcore.Response(200, headers=headers, content=compressed_body)64 assert response.content == body65 66 67-@pytest.mark.asyncio68-async def test_streaming():67+def test_streaming():68 body = b"test 123"69 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)70 72- async def compress(body):71+ def compress(body):72 yield compressor.compress(body)73 yield compressor.flush()74 75 headers = [(b"Content-Encoding", b"gzip")]76 response = httpcore.Response(200, headers=headers, content=compress(body))77 assert not hasattr(response, "body")79- assert await response.read() == body78+ assert response.read() == body79 80 81 @pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))82 def test_decoding_errors(header_value):6 unmodified lines