Skip to content
Myr

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

authored by Tom Christie · committed by GitHub · parent ba033c5 · Browse files · 22 files+1078 added−602 removed
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

22 files+1078 added−602 removed

modified:httpcore/dispatch/connection_pool.py+6 added-7 removed
10 unmodified lines
11 VerifyTypes,12)13from ..decoders import ACCEPT_ENCODING14from ..exceptions import PoolTimeout15from ..interfaces import ConcurrencyBackend, Dispatcher16from ..models import Origin, Request, Response15from ..interfaces import AsyncDispatcher, ConcurrencyBackend16from ..models import AsyncRequest, AsyncResponse, Origin17from .connection import HTTPConnection1819CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]20
55 unmodified lines
76 def __len__(self) -> int:77 return len(self.all)787980class ConnectionPool(Dispatcher):80class ConnectionPool(AsyncDispatcher):81 def __init__(82 self,83 *,84 verify: VerifyTypes = True,
19 unmodified lines
104 return len(self.keepalive_connections) + len(self.active_connections)105106 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 lines
modified:httpcore/dispatch/connection.py+7 added-12 removed
13 unmodified lines
14 TimeoutTypes,15 VerifyTypes,16)17from ..exceptions import ConnectTimeout18from ..interfaces import ConcurrencyBackend, Dispatcher, Protocol19from ..models import Origin, Request, Response18from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Protocol19from ..models import AsyncRequest, AsyncResponse, Origin20from .http2 import HTTP2Connection21from .http11 import HTTP11Connection2223# Callback signature: async def callback(conn: HTTPConnection) -> None24ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]252627class HTTPConnection(Dispatcher):27class HTTPConnection(AsyncDispatcher):28 def __init__(29 self,30 origin: typing.Union[str, Origin],31 verify: VerifyTypes = True,
11 unmodified lines
43 self.h2_connection = None # type: typing.Optional[HTTP2Connection]4445 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)5455 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)6061 return response6263 async def connect(
44 unmodified lines
modified:httpcore/dispatch/http11.py+6 added-14 removed
2 unmodified lines
3import h1145from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes6from ..exceptions import ConnectTimeout, ReadTimeout7from ..interfaces import BaseReader, BaseWriter, Dispatcher8from ..models import Request, Response7from ..interfaces import BaseReader, BaseWriter8from ..models import AsyncRequest, AsyncResponse910H11Event = typing.Union[11 h11.Request,12 h11.Response,
24 unmodified lines
37 self.on_release = on_release38 self.h11_state = h11.Connection(our_role=h11.CLIENT)3940 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)4445 #  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 lines
71 status_code = event.status_code72 headers = event.headers73 content = self._body_iter(timeout)7475 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 line
81 on_close=self.response_closed,82 request=request,83 )8485 if not stream:86 try:87 await response.read()88 finally:89 await response.close()9091 return response9285 async def close(self) -> None:86 event = h11.ConnectionClosed()87 self.h11_state.send(event)88 await self.writer.close()
39 unmodified lines
modified:httpcore/dispatch/http2.py+6 added-14 removed
4 unmodified lines
5import h2.events67from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes8from ..exceptions import ConnectTimeout, ReadTimeout9from ..interfaces import BaseReader, BaseWriter, Dispatcher10from ..models import Request, Response9from ..interfaces import BaseReader, BaseWriter10from ..models import AsyncRequest, AsyncResponse111213class HTTP2Connection:14 READ_NUM_BYTES = 4096
8 unmodified lines
23 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]24 self.initialized = False2526 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)3031 #  Start sending the request.32 if not self.initialized:
25 unmodified lines
5859 content = self.body_iter(stream_id, timeout)60 on_close = functools.partial(self.response_closed, stream_id=stream_id)6162 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 )7071 if not stream:72 try:73 await response.read()74 finally:75 await response.close()7677 return response7871 async def close(self) -> None:72 await self.writer.close()7374 def initiate_connection(self) -> None:
2 unmodified lines
77 self.writer.write_no_block(data_to_send)78 self.initialized = True7980 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 lines
added:httpcore/dispatch/threaded.py+97 added
1from ..config import CertTypes, TimeoutTypes, VerifyTypes2from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher3from ..models import (4 AsyncRequest,5 AsyncRequestData,6 AsyncResponse,7 AsyncResponseContent,8 Request,9 RequestData,10 Response,11 ResponseContent,12)131415class 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 """2122 def __init__(self, dispatch: Dispatcher, backend: ConcurrencyBackend) -> None:23 self.sync_dispatcher = dispatch24 self.backend = backend2526 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.backend3435 data = getattr(request, "content", getattr(request, "content_aiter", None))36 sync_data = self._sync_request_data(data)3738 sync_request = Request(39 method=request.method,40 url=request.url,41 headers=request.headers,42 data=sync_data,43 )4445 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)5455 content = getattr(56 sync_response, "_raw_content", getattr(sync_response, "_raw_stream", None)57 )5859 async_content = self._async_response_content(content)6061 async def async_on_close() -> None:62 nonlocal concurrency_backend, sync_response63 await concurrency_backend.run_in_threadpool(sync_response.close)6465 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 )7576 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)8384 def _async_response_content(self, content: ResponseContent) -> AsyncResponseContent:85 if isinstance(content, bytes):86 return content8788 # 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)9293 def _sync_request_data(self, data: AsyncRequestData) -> RequestData:94 if isinstance(data, bytes):95 return data9697 return self.backend.iterate(data)
modified:httpcore/__init__.py+19 added-2 removed
26 unmodified lines
27 Timeout,28 TooManyRedirects,29 WriteTimeout,30)31from .interfaces import BaseReader, BaseWriter, ConcurrencyBackend, Dispatcher, Protocol32from .models import URL, Cookies, Headers, Origin, QueryParams, Request, Response31from .interfaces import (32 AsyncDispatcher,33 BaseReader,34 BaseWriter,35 ConcurrencyBackend,36 Dispatcher,37 Protocol,38)39from .models import (40 URL,41 AsyncRequest,42 AsyncResponse,43 Cookies,44 Headers,45 Origin,46 QueryParams,47 Request,48 Response,49)50from .status_codes import StatusCode, codes5152__version__ = "0.4.0"
modified:httpcore/api.py+9 added-9 removed
6 unmodified lines
7 CookieTypes,8 HeaderTypes,9 QueryParamTypes,10 RequestData,11 SyncResponse,11 Response,12 URLTypes,13)1415
13 unmodified lines
29 # 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 lines
60 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 lines
87 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 lines
114 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 lines
143 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 lines
174 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 lines
205 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 lines
236 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 lines
modified:httpcore/auth.py+3 added-3 removed
1import typing2from base64 import b64encode34from .models import Request4from .models import AsyncRequest567class AuthBase:8 """9 Base class that all auth implementations derive from.10 """1112 def __call__(self, request: Request) -> Request:12 def __call__(self, request: AsyncRequest) -> AsyncRequest:13 raise NotImplementedError("Auth hooks must be callable.") # pragma: nocover141516class HTTPBasicAuth(AuthBase):
2 unmodified lines
19 ) -> None:20 self.username = username21 self.password = password2223 def __call__(self, request: Request) -> Request:23 def __call__(self, request: AsyncRequest) -> AsyncRequest:24 request.headers["Authorization"] = self.build_auth_header()25 return request2627 def build_auth_header(self) -> str:
11 unmodified lines
modified:httpcore/client.py+279 added-255 removed
1import asyncio1import typing2from types import TracebackType34from .auth import HTTPBasicAuth5from .concurrency import AsyncioBackend6from .config import (7 DEFAULT_MAX_REDIRECTS,8 DEFAULT_POOL_LIMITS,9 DEFAULT_TIMEOUT_CONFIG,
2 unmodified lines
12 TimeoutTypes,13 VerifyTypes,14)15from .dispatch.connection_pool import ConnectionPool16from .dispatch.threaded import ThreadedDispatcher17from .exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects17from .interfaces import ConcurrencyBackend, Dispatcher18from .interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher19from .models import (20 URL,21 AsyncRequest,22 AsyncRequestData,23 AsyncResponse,24 AsyncResponseContent,25 AuthTypes,26 Cookies,27 CookieTypes,28 Headers,
1 unmodified line
30 QueryParamTypes,31 Request,32 RequestData,33 Response,29 SyncResponse,34 ResponseContent,35 URLTypes,36)37from .status_codes import codes383935class AsyncClient:40class BaseClient:41 def __init__(42 self,43 auth: AuthTypes = None,44 cookies: CookieTypes = None,
1 unmodified line
46 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()5556 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 = dispatch6869 self.auth = auth70 self.cookies = Cookies(cookies)71 self.max_redirects = max_redirects60 self.dispatch = dispatch72 self.dispatch = async_dispatch73 self.concurrency_backend = backend7475 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 cookies8384 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.auth9798 url = request.url99 if auth is None and (url.username or url.password):100 auth = HTTPBasicAuth(username=url.username, password=url.password)101102 if auth is not None:103 if isinstance(auth, tuple):104 auth = HTTPBasicAuth(username=auth[0], password=auth[1])105 request = auth(request)106107 response = await self.send_handling_redirects(108 request,109 verify=verify,110 cert=cert,111 timeout=timeout,112 allow_redirects=allow_redirects,113 )114115 if not stream:116 try:117 await response.read()118 finally:119 await response.close()120121 return response122123 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 = []135136 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()143144 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 break153154 if allow_redirects:155 request = self.build_redirect_request(request, response)156 else:157158 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 response170171 response.next = send_next # type: ignore172 break173174 return response175176 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 )187188 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.method194195 # https://tools.ietf.org/html/rfc7231#section-6.4.4196 if response.status_code == codes.SEE_OTHER and method != "HEAD":197 method = "GET"198199 # 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"203204 # 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"208209 return method210211 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"]216217 url = URL(location, allow_relative=True)218219 # 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)223224 # 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)227228 return url229230 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 headers239240 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.content249250251class AsyncClient(BaseClient):252 async def get(253 self,254 url: URLTypes,255 *,
5 unmodified lines
261 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 lines
289 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 lines
317 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 lines
336 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 lines
347 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 lines
368 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 lines
379 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 lines
400 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 lines
411 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 lines
432 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 lines
443 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 lines
465 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 lines
476 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 lines
497 timeout=timeout,498 )499 return response500311 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 cookies319320 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.auth333334 url = request.url335 if auth is None and (url.username or url.password):336 auth = HTTPBasicAuth(username=url.username, password=url.password)337338 if auth is not None:339 if isinstance(auth, tuple):340 auth = HTTPBasicAuth(username=auth[0], password=auth[1])341 request = auth(request)342343 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 response352353 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 = []366367 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()374375 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 break383384 if allow_redirects:385 request = self.build_redirect_request(request, response)386 else:387388 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 response401402 response.next = send_next # type: ignore403 break404405 return response406407 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 )416417 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.method423424 # https://tools.ietf.org/html/rfc7231#section-6.4.4425 if response.status_code == codes.SEE_OTHER and method != "HEAD":426 method = "GET"427428 # 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"432433 # 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"437438 return method439440 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"]445446 url = URL(location, allow_relative=True)447448 # 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)452453 # 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)456457 return url458459 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 headers468469 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.content478501 async def close(self) -> None:502 await self.dispatch.close()503504 async def __aenter__(self) -> "AsyncClient":
7 unmodified lines
512 ) -> None:513 await self.close()514515494class 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()516class 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 data524518 @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)529530 def _sync_data(self, data: AsyncResponseContent) -> ResponseContent:531 if isinstance(data, bytes):532 return data533534 # 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)538539 def request(540 self,541 method: str,542 url: URLTypes,
8 unmodified lines
551 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_backend566567 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)578579 content = getattr(580 async_response, "_raw_content", getattr(async_response, "_raw_stream", None)581 )582583 sync_content = self._sync_data(content)584585 def sync_on_close() -> None:586 nonlocal concurrency_backend, async_response587 concurrency_backend.run(async_response.on_close)588589 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 response605606 def get(607 self,
7 unmodified lines
615 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 lines
642 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 lines
669 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 lines
698 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 lines
729 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 lines
760 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 lines
791 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 lines
807 cert=cert,808 timeout=timeout,809 )810764 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)787811 def close(self) -> None:789 self._loop.run_until_complete(self._client.close())812 coroutine = self.dispatch.close813 self.concurrency_backend.run(coroutine)814815 def __enter__(self) -> "Client":816 return self817
7 unmodified lines
modified:httpcore/concurrency.py+29 added
7 unmodified lines
8protocols, and help keep the rest of the package more `async`/`await`9based, and less strictly `asyncio`-specific.10"""11import asyncio12import functools13import ssl14import typing1516from .config import DEFAULT_TIMEOUT_CONFIG, PoolLimits, TimeoutConfig
116 unmodified lines
133 if not SSL_MONKEY_PATCH_APPLIED:134 ssl_monkey_patch()135 SSL_MONKEY_PATCH_APPLIED = True136137 @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._loop145146 async def connect(147 self,148 hostname: str,149 port: int,
21 unmodified lines
171 protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11172173 return (reader, writer, protocol)174175 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)182183 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 = loop193194 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:195 return PoolSemaphore(limits)
modified:httpcore/interfaces.py+92 added-13 removed
4 unmodified lines
56from .config import CertTypes, PoolLimits, TimeoutConfig, TimeoutTypes, VerifyTypes7from .models import (8 URL,9 AsyncRequest,10 AsyncRequestData,11 AsyncResponse,12 Headers,13 HeaderTypes,14 QueryParamTypes,15 Request,
7 unmodified lines
23 HTTP_11 = "HTTP/1.1"24 HTTP_2 = "HTTP/2"252624class Dispatcher:27class 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.3031 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 lines
37 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)5051 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: nocover5960 async def close(self) -> None:61 pass # pragma: nocover6263 async def __aenter__(self) -> "AsyncDispatcher":64 return self6566 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()737475class Dispatcher:76 """77 Base class for syncronous dispatcher classes, that handle sending the request.7879 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 """8384 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)9852 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: nocover10762 async def close(self) -> None:108 def close(self) -> None:109 pass # pragma: nocover11065 async def __aenter__(self) -> "Dispatcher":111 def __enter__(self) -> "Dispatcher":112 return self11368 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()121122123class BaseReader:124 """
48 unmodified lines
173 raise NotImplementedError() # pragma: no cover174175 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:176 raise NotImplementedError() # pragma: no cover177178 async def run_in_threadpool(179 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any180 ) -> typing.Any:181 raise NotImplementedError() # pragma: no cover182183 async def iterate_in_threadpool(self, iterator): # type: ignore184 class IterationComplete(Exception):185 pass186187 def next_wrapper(iterator): # type: ignore188 try:189 return next(iterator)190 except StopIteration:191 raise IterationComplete()192193 while True:194 try:195 yield await self.run_in_threadpool(next_wrapper, iterator)196 except IterationComplete:197 break198199 def run(200 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any201 ) -> typing.Any:202 raise NotImplementedError() # pragma: no cover203204 def iterate(self, async_iterator): # type: ignore205 while True:206 try:207 yield self.run(async_iterator.__anext__)208 except StopAsyncIteration:209 break
modified:httpcore/models.py+264 added-165 removed
1import asyncio1import cgi2import email.message3import json as jsonlib4import typing
41 unmodified lines
46CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]4748AuthTypes = typing.Union[49 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],51 typing.Callable[["Request"], "Request"],50 typing.Callable[["AsyncRequest"], "AsyncRequest"],51]5254RequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]53AsyncRequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]5456ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]55RequestData = typing.Union[dict, bytes, typing.Iterator[bytes]]5657AsyncResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]5859ResponseContent = typing.Union[bytes, typing.Iterator[bytes]]606162class URL:63 def __init__(64 self,65 url: URLTypes,
405 unmodified lines
471 as_list = self.items()472 return f"{class_name}({as_list!r}{encoding_str})"473474472class Request:475class 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 lines
488 if cookies:489 self._cookies = Cookies(cookies)490 self._cookies.set_cookie_header(self)491492 def encode_json(self, json: typing.Any) -> bytes:493 return jsonlib.dumps(json).encode("utf-8")494495 def urlencode_data(self, data: dict) -> bytes:496 return urlencode(data, doseq=True).encode("utf-8")497498 def prepare(self) -> None:499 content = getattr(self, "content", None) # type: bytes500 is_streaming = getattr(self, "is_streaming", False)501502 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]503504 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.headers510511 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()))523524 for item in reversed(auto_headers):525 self.headers.raw.insert(0, item)526527 @property528 def cookies(self) -> "Cookies":529 if not hasattr(self, "_cookies"):530 self._cookies = Cookies()531 return self._cookies532533 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})>"537538539class 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 )554555 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"494495 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 = data570571 self.prepare()
12 unmodified lines
584 yield part585 elif self.content:586 yield self.content587523 def prepare(self) -> None:524 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]588526 has_content_length = (527 "content-length" in self.headers or "transfer-encoding" in self.headers589class 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.headers604531 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 = data620540 for item in reversed(auto_headers):541 self.headers.raw.insert(0, item)621 self.prepare()622543 @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.content627549 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.content634635555class Response:636class 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)651573 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 = content581582 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]655656 @property657 def url(self) -> typing.Optional[URL]:
7 unmodified lines
665 @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 lines
751 self._decoder = IdentityDecoder()752753 return self._decoder754755 @property756 def is_redirect(self) -> bool:757 return StatusCode.is_redirect(self.status_code) and "location" in self.headers758759 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 )767768 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 = ""774775 if message:776 raise HttpError(message)777778 def json(self) -> typing.Any:779 return jsonlib.loads(self.content.decode("utf-8"))780781 @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._cookies788789 def __repr__(self) -> str:790 return f"<Response({self.status_code}, {self.reason_phrase!r})>"791792793class 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 )814815 self.history = [] if history is None else list(history)816817 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 = content825826 async def read(self) -> bytes:827 """828 Read and return the response content.829 """
39 unmodified lines
869 self.is_closed = True870 if self.on_close is not None:871 await self.on_close()872732 @property733 def is_redirect(self) -> bool:734 return StatusCode.is_redirect(self.status_code) and "location" in self.headers873736 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}"874class 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 )895745 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)897898 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 = content906752 if message:753 raise HttpError(message)754755 def json(self) -> typing.Any:756 return jsonlib.loads(self.content.decode("utf-8"))757758 @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._cookies765766 def __repr__(self) -> str:767 return f"<Response({self.status_code}, {self.reason_phrase!r})>"768769770class SyncResponse:771 """772 A thread-synchronous response. This class proxies onto a `Response`773 instance, providing standard synchronous interfaces where required.774 """775776 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):777 self._response = response778 self._loop = loop779780 @property781 def status_code(self) -> int:782 return self._response.status_code783784 @property785 def reason_phrase(self) -> str:786 return self._response.reason_phrase787788 @property789 def protocol(self) -> typing.Optional[str]:790 return self._response.protocol791792 @property793 def url(self) -> typing.Optional[URL]:794 return self._response.url795796 @property797 def request(self) -> typing.Optional[Request]:798 return self._response.request799800 @property801 def headers(self) -> Headers:802 return self._response.headers803804 @property805 def content(self) -> bytes:806 return self._response.content807808 @property809 def text(self) -> str:810 return self._response.text811812 @property813 def encoding(self) -> str:814 return self._response.encoding815816 @property817 def is_redirect(self) -> bool:818 return self._response.is_redirect819820 def raise_for_status(self) -> None:821 return self._response.raise_for_status()822823 def json(self) -> typing.Any:824 return self._response.json()825907 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._content914915 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()926927 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()938939 self.is_stream_consumed = True940 for part in self._raw_stream:941 yield part942 self.close()943944 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()953848 @property849 def cookies(self) -> "Cookies":850 return self._response.cookies954852 def __repr__(self) -> str:853 return f"<Response({self.status_code}, {self.reason_phrase!r})>"854855955class Cookies(MutableMapping):956 """957 HTTP Cookies, as a mutable mapping.958 """
10 unmodified lines
969 self.jar.set_cookie(cookie)970 else:971 self.jar = cookies972874 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 None
1 unmodified line
979 urllib_request = self._CookieCompatRequest(response.request)980981 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore982884 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 lines
1098 Wraps a `Request` instance up in a compatability interface suitable1099 for use with `CookieJar` operations.1100 """11011003 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 lines
1116 Wraps a `Request` instance up in a compatability interface suitable1117 for use with `CookieJar` operations.1118 """11191021 def __init__(self, response: Response):1120 def __init__(self, response: BaseResponse):1121 self.response = response11221123 def info(self) -> email.message.Message:1124 info = email.message.Message()
3 unmodified lines
modified:tests/client/test_auth.py+7 added-8 removed
2 unmodified lines
3import pytest45from 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)151617class MockDispatch(Dispatcher):17class 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)272829def test_basic_auth():30 url = "https://example.org/"
42 unmodified lines
modified:tests/client/test_cookies.py+8 added-9 removed
3 unmodified lines
4import pytest56from 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)171819class MockDispatch(Dispatcher):19class 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)333435def test_set_cookie():36 """
91 unmodified lines
modified:tests/client/test_redirects.py+20 added-17 removed
4 unmodified lines
56from 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 lines
20 codes,21)222322class MockDispatch(Dispatcher):24class 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)3637 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)4142 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)4647 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)5051 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)5455 elif request.url.path == "/multiple_redirects":56 params = parse_qs(request.url.query)57 count = int(params.get("count", "0")[0])
2 unmodified lines
60 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)6566 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)6970 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)7374 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)7879 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 )8586 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)9088 return Response(codes.OK, content=b"Hello, world!", request=request)91 return AsyncResponse(codes.OK, content=b"Hello, world!", request=request)929394@pytest.mark.asyncio95async def test_redirect_301():
151 unmodified lines
modified:tests/dispatch/test_connection_pools.py+12 added-5 removed
8 unmodified lines
9 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) == 11617 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) == 12122
3 unmodified lines
26 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) == 13334 response = await http.request("GET", "http://localhost:8000/")35 await response.read()36 assert len(http.active_connections) == 037 assert len(http.keepalive_connections) == 23839
5 unmodified lines
45 pool_limits = httpcore.PoolLimits(soft_limit=1)4647 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) == 15253 response = await http.request("GET", "http://localhost:8000/")54 await response.read()55 assert len(http.active_connections) == 056 assert len(http.keepalive_connections) == 15758
2 unmodified lines
61 """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) == 06869 await response.read()
7 unmodified lines
77 """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) == 08479 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) == 08889 await response_b.read()
12 unmodified lines
102 """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) == 0109110
2 unmodified lines
113 """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) == 1
4 unmodified lines
126 """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) == 0
modified:tests/dispatch/test_connections.py+3 added
5 unmodified lines
6@pytest.mark.asyncio7async 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!"1314
12 unmodified lines
27 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!"3435
3 unmodified lines
39 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
1import json23import pytest45from httpcore import (6 CertTypes,7 Client,8 Dispatcher,9 Request,10 Response,11 TimeoutTypes,12 VerifyTypes,13)141516def streaming_body():17 for part in [b"Hello", b", ", b"world!"]:18 yield part192021class 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)404142def 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)5051 assert response.status_code == 20052 assert response.json() == {"hello": "world"}535455def test_threaded_streaming_response():56 url = "https://example.org/streaming_response"57 with Client(dispatch=MockDispatch()) as client:58 response = client.get(url)5960 assert response.status_code == 20061 assert response.text == "Hello, world!"626364def 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())6869 assert response.status_code == 20070 assert response.text == "Hello, world!"717273def 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!")7778 assert response.status_code == 20079 assert response.text == "Hello, world!"808182def 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!")8687 assert response.status_code == 20088 assert response.text == "Hello, world!"899091def 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)9899 assert response.status_code == 200100 assert response.json() == {"hello": "world"}
modified:tests/models/test_requests.py+23 added-48 removed
8 unmodified lines
91011def 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.headers141516def 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"192021def 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"262728def 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}'333435def test_transfer_encoding_header():44 async def streaming_body(data):36 def streaming_body(data):37 yield data # pragma: nocover3839 data = streaming_body(b"test 123")4041 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"444546def test_override_host_header():60 headers = [(b"host", b"1.2.3.4:80")]47 headers = {"host": "1.2.3.4:80"}4849 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"515253def test_override_accept_encoding_header():70 headers = [(b"accept-encoding", b"identity")]54 headers = {"Accept-Encoding": "identity"}5556 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"585960def test_override_content_length_header():80 async def streaming_body(data):61 def streaming_body(data):62 yield data # pragma: nocover6364 data = streaming_body(b"test 123")84 headers = [(b"content-length", b"8")]65 headers = {"Content-Length": "8"}6667 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"697071def test_url():72 url = "http://example.org"
21 unmodified lines
modified:tests/models/test_responses.py+73 added-17 removed
1 unmodified line
23import httpcore456async def streaming_body():6def streaming_body():7 yield b"Hello, "8 yield b"world!"91011async def async_streaming_body():12 yield b"Hello, "13 yield b"world!"141516def test_response():17 response = httpcore.Response(200, content=b"Hello, world!")18 assert response.status_code == 20019 assert response.reason_phrase == "OK"
89 unmodified lines
109 assert response.text == "Snowman: â\x98\x83"110 assert response.encoding == "iso-8859-1"111112108@pytest.mark.asyncio109async def test_read_response():113def test_read_response():114 response = httpcore.Response(200, content=b"Hello, world!")115116 assert response.status_code == 200117 assert response.text == "Hello, world!"118 assert response.encoding == "ascii"119 assert response.is_closed120117 content = await response.read()121 content = response.read()122123 assert content == b"Hello, world!"124 assert response.content == b"Hello, world!"125 assert response.is_closed126127124@pytest.mark.asyncio125async def test_raw_interface():128def test_raw_interface():129 response = httpcore.Response(200, content=b"Hello, world!")130131 raw = b""129 async for part in response.raw():132 for part in response.raw():133 raw += part134 assert raw == b"Hello, world!"135136134@pytest.mark.asyncio135async def test_stream_interface():137def test_stream_interface():138 response = httpcore.Response(200, content=b"Hello, world!")139140 content = b""139 async for part in response.stream():141 for part in response.stream():142 content += part143 assert content == b"Hello, world!"144145146@pytest.mark.asyncio147async def test_async_stream_interface():148 response = httpcore.AsyncResponse(200, content=b"Hello, world!")149150 content = b""151 async for part in response.stream():152 content += part153 assert content == b"Hello, world!"154155145async def test_stream_interface_after_read():156def test_stream_interface_after_read():157 response = httpcore.Response(200, content=b"Hello, world!")158159 response.read()160161 content = b""162 for part in response.stream():163 content += part164 assert content == b"Hello, world!"165166167@pytest.mark.asyncio168async def test_async_stream_interface_after_read():169 response = httpcore.AsyncResponse(200, content=b"Hello, world!")170171 await response.read()172173 content = b""174 async for part in response.stream():175 content += part176 assert content == b"Hello, world!"177178156@pytest.mark.asyncio157async def test_streaming_response():179def test_streaming_response():180 response = httpcore.Response(200, content=streaming_body())181182 assert response.status_code == 200183 assert not response.is_closed184163 content = await response.read()185 content = response.read()186187 assert content == b"Hello, world!"188 assert response.content == b"Hello, world!"189 assert response.is_closed190191192@pytest.mark.asyncio193async def test_async_streaming_response():194 response = httpcore.AsyncResponse(200, content=async_streaming_body())195196 assert response.status_code == 200197 assert not response.is_closed198199 content = await response.read()200201 assert content == b"Hello, world!"202 assert response.content == b"Hello, world!"203 assert response.is_closed204205171async def test_cannot_read_after_stream_consumed():206def test_cannot_read_after_stream_consumed():207 response = httpcore.Response(200, content=streaming_body())208209 content = b""210 for part in response.stream():211 content += part212213 with pytest.raises(httpcore.StreamConsumed):214 response.read()215216217@pytest.mark.asyncio218async def test_async_cannot_read_after_stream_consumed():219 response = httpcore.AsyncResponse(200, content=async_streaming_body())220221 content = b""222 async for part in response.stream():223 content += part224225 with pytest.raises(httpcore.StreamConsumed):226 await response.read()227228182@pytest.mark.asyncio183async def test_cannot_read_after_response_closed():229def test_cannot_read_after_response_closed():230 response = httpcore.Response(200, content=streaming_body())231232 response.close()233234 with pytest.raises(httpcore.ResponseClosed):235 response.read()236237238@pytest.mark.asyncio239async def test_async_cannot_read_after_response_closed():240 response = httpcore.AsyncResponse(200, content=async_streaming_body())241242 await response.close()243244 with pytest.raises(httpcore.ResponseClosed):245 await response.read()
7 unmodified lines
modified:tests/test_api.py+12 added
37 unmodified lines
38 assert response.reason_phrase == "OK"394041@threadpool42def test_post_byte_iterator(server):43 def data():44 yield b"Hello"45 yield b", "46 yield b"world!"4748 response = httpcore.post("http://127.0.0.1:8000/", data=data())49 assert response.status_code == 20050 assert response.reason_phrase == "OK"515253@threadpool54def 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 lines
modified:tests/test_decoders.py+3 added-4 removed
62 unmodified lines
63 response = httpcore.Response(200, headers=headers, content=compressed_body)64 assert response.content == body656667@pytest.mark.asyncio68async def test_streaming():67def test_streaming():68 body = b"test 123"69 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)7072 async def compress(body):71 def compress(body):72 yield compressor.compress(body)73 yield compressor.flush()7475 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() == body798081@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))82def test_decoding_errors(header_value):
6 unmodified lines