client.py
This file
Path
httpcore/client.py
611 lines · 17.1 KiB · Python
Last changed by
Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
History of this fileTake it
1import asyncio2import typing3from types import TracebackType45from .config import (6 DEFAULT_MAX_REDIRECTS,7 DEFAULT_POOL_LIMITS,8 DEFAULT_SSL_CONFIG,9 DEFAULT_TIMEOUT_CONFIG,10 PoolLimits,11 SSLConfig,12 TimeoutConfig,13)14from .dispatch.connection_pool import ConnectionPool15from .exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects16from .interfaces import ConcurrencyBackend, Dispatcher17from .models import (18 URL,19 Headers,20 HeaderTypes,21 QueryParamTypes,22 Request,23 RequestData,24 Response,25 SyncResponse,26 URLTypes,27)28from .status_codes import codes293031class AsyncClient:32 def __init__(33 self,34 ssl: SSLConfig = DEFAULT_SSL_CONFIG,35 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,36 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,37 max_redirects: int = DEFAULT_MAX_REDIRECTS,38 dispatch: Dispatcher = None,39 backend: ConcurrencyBackend = None,40 ):41 if dispatch is None:42 dispatch = ConnectionPool(43 ssl=ssl, timeout=timeout, pool_limits=pool_limits, backend=backend44 )4546 self.max_redirects = max_redirects47 self.dispatch = dispatch4849 async def get(50 self,51 url: URLTypes,52 *,53 query_params: QueryParamTypes = None,54 headers: HeaderTypes = None,55 stream: bool = False,56 allow_redirects: bool = True,57 ssl: SSLConfig = None,58 timeout: TimeoutConfig = None,59 ) -> Response:60 return await self.request(61 "GET",62 url,63 query_params=query_params,64 headers=headers,65 stream=stream,66 allow_redirects=allow_redirects,67 ssl=ssl,68 timeout=timeout,69 )7071 async def options(72 self,73 url: URLTypes,74 *,75 query_params: QueryParamTypes = None,76 headers: HeaderTypes = None,77 stream: bool = False,78 allow_redirects: bool = True,79 ssl: SSLConfig = None,80 timeout: TimeoutConfig = None,81 ) -> Response:82 return await self.request(83 "OPTIONS",84 url,85 query_params=query_params,86 headers=headers,87 stream=stream,88 allow_redirects=allow_redirects,89 ssl=ssl,90 timeout=timeout,91 )9293 async def head(94 self,95 url: URLTypes,96 *,97 query_params: QueryParamTypes = None,98 headers: HeaderTypes = None,99 stream: bool = False,100 allow_redirects: bool = False, # Note: Differs to usual default.101 ssl: SSLConfig = None,102 timeout: TimeoutConfig = None,103 ) -> Response:104 return await self.request(105 "HEAD",106 url,107 query_params=query_params,108 headers=headers,109 stream=stream,110 allow_redirects=allow_redirects,111 ssl=ssl,112 timeout=timeout,113 )114115 async def post(116 self,117 url: URLTypes,118 *,119 data: RequestData = b"",120 query_params: QueryParamTypes = None,121 headers: HeaderTypes = None,122 stream: bool = False,123 allow_redirects: bool = True,124 ssl: SSLConfig = None,125 timeout: TimeoutConfig = None,126 ) -> Response:127 return await self.request(128 "POST",129 url,130 data=data,131 query_params=query_params,132 headers=headers,133 stream=stream,134 allow_redirects=allow_redirects,135 ssl=ssl,136 timeout=timeout,137 )138139 async def put(140 self,141 url: URLTypes,142 *,143 data: RequestData = b"",144 query_params: QueryParamTypes = None,145 headers: HeaderTypes = None,146 stream: bool = False,147 allow_redirects: bool = True,148 ssl: SSLConfig = None,149 timeout: TimeoutConfig = None,150 ) -> Response:151 return await self.request(152 "PUT",153 url,154 data=data,155 query_params=query_params,156 headers=headers,157 stream=stream,158 allow_redirects=allow_redirects,159 ssl=ssl,160 timeout=timeout,161 )162163 async def patch(164 self,165 url: URLTypes,166 *,167 data: RequestData = b"",168 query_params: QueryParamTypes = None,169 headers: HeaderTypes = None,170 stream: bool = False,171 allow_redirects: bool = True,172 ssl: SSLConfig = None,173 timeout: TimeoutConfig = None,174 ) -> Response:175 return await self.request(176 "PATCH",177 url,178 data=data,179 query_params=query_params,180 headers=headers,181 stream=stream,182 allow_redirects=allow_redirects,183 ssl=ssl,184 timeout=timeout,185 )186187 async def delete(188 self,189 url: URLTypes,190 *,191 data: RequestData = b"",192 query_params: QueryParamTypes = None,193 headers: HeaderTypes = None,194 stream: bool = False,195 allow_redirects: bool = True,196 ssl: SSLConfig = None,197 timeout: TimeoutConfig = None,198 ) -> Response:199 return await self.request(200 "DELETE",201 url,202 data=data,203 query_params=query_params,204 headers=headers,205 stream=stream,206 allow_redirects=allow_redirects,207 ssl=ssl,208 timeout=timeout,209 )210211 async def request(212 self,213 method: str,214 url: URLTypes,215 *,216 data: RequestData = b"",217 query_params: QueryParamTypes = None,218 headers: HeaderTypes = None,219 stream: bool = False,220 allow_redirects: bool = True,221 ssl: SSLConfig = None,222 timeout: TimeoutConfig = None,223 ) -> Response:224 request = Request(225 method, url, data=data, query_params=query_params, headers=headers226 )227 self.prepare_request(request)228 response = await self.send(229 request,230 stream=stream,231 allow_redirects=allow_redirects,232 ssl=ssl,233 timeout=timeout,234 )235 return response236237 def prepare_request(self, request: Request) -> None:238 request.prepare()239240 async def send(241 self,242 request: Request,243 *,244 stream: bool = False,245 ssl: SSLConfig = None,246 timeout: TimeoutConfig = None,247 allow_redirects: bool = True,248 history: typing.List[Response] = None,249 ) -> Response:250 if history is None:251 history = []252253 while True:254 # We perform these checks here, so that calls to `response.next()`255 # will raise redirect errors if appropriate.256 if len(history) > self.max_redirects:257 raise TooManyRedirects()258 if request.url in [response.url for response in history]:259 raise RedirectLoop()260261 response = await self.dispatch.send(262 request, stream=stream, ssl=ssl, timeout=timeout263 )264 response.history = list(history)265 history = [response] + history266 if not response.is_redirect:267 break268269 if allow_redirects:270 request = self.build_redirect_request(request, response)271 else:272273 async def send_next() -> Response:274 nonlocal request, response, ssl, allow_redirects, timeout, history275 request = self.build_redirect_request(request, response)276 response = await self.send(277 request,278 stream=stream,279 allow_redirects=allow_redirects,280 ssl=ssl,281 timeout=timeout,282 history=history,283 )284 return response285286 response.next = send_next # type: ignore287 break288289 return response290291 def build_redirect_request(self, request: Request, response: Response) -> Request:292 method = self.redirect_method(request, response)293 url = self.redirect_url(request, response)294 headers = self.redirect_headers(request, url)295 content = self.redirect_content(request, method)296 return Request(method=method, url=url, headers=headers, data=content)297298 def redirect_method(self, request: Request, response: Response) -> str:299 """300 When being redirected we may want to change the method of the request301 based on certain specs or browser behavior.302 """303 method = request.method304305 # https://tools.ietf.org/html/rfc7231#section-6.4.4306 if response.status_code == codes.SEE_OTHER and method != "HEAD":307 method = "GET"308309 # Do what the browsers do, despite standards...310 # Turn 302s into GETs.311 if response.status_code == codes.FOUND and method != "HEAD":312 method = "GET"313314 # If a POST is responded to with a 301, turn it into a GET.315 # This bizarre behaviour is explained in 'requests' issue 1704.316 if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":317 method = "GET"318319 return method320321 def redirect_url(self, request: Request, response: Response) -> URL:322 """323 Return the URL for the redirect to follow.324 """325 location = response.headers["Location"]326327 url = URL(location, allow_relative=True)328329 # Facilitate relative 'Location' headers, as allowed by RFC 7231.330 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')331 if url.is_relative_url:332 url = url.resolve_with(request.url)333334 # Attach previous fragment if needed (RFC 7231 7.1.2)335 if request.url.fragment and not url.fragment:336 url = url.copy_with(fragment=request.url.fragment)337338 return url339340 def redirect_headers(self, request: Request, url: URL) -> Headers:341 """342 Strip Authorization headers when responses are redirected away from343 the origin.344 """345 headers = Headers(request.headers)346 if url.origin != request.url.origin:347 del headers["Authorization"]348 return headers349350 def redirect_content(self, request: Request, method: str) -> bytes:351 """352 Return the body that should be used for the redirect request.353 """354 if method != request.method and method == "GET":355 return b""356 if request.is_streaming:357 raise RedirectBodyUnavailable()358 return request.content359360 async def close(self) -> None:361 await self.dispatch.close()362363 async def __aenter__(self) -> "AsyncClient":364 return self365366 async def __aexit__(367 self,368 exc_type: typing.Type[BaseException] = None,369 exc_value: BaseException = None,370 traceback: TracebackType = None,371 ) -> None:372 await self.close()373374375class Client:376 def __init__(377 self,378 ssl: SSLConfig = DEFAULT_SSL_CONFIG,379 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,380 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,381 max_redirects: int = DEFAULT_MAX_REDIRECTS,382 dispatch: Dispatcher = None,383 backend: ConcurrencyBackend = None,384 ) -> None:385 self._client = AsyncClient(386 ssl=ssl,387 timeout=timeout,388 pool_limits=pool_limits,389 max_redirects=max_redirects,390 dispatch=dispatch,391 backend=backend,392 )393 self._loop = asyncio.new_event_loop()394395 def request(396 self,397 method: str,398 url: URLTypes,399 *,400 data: RequestData = b"",401 query_params: QueryParamTypes = None,402 headers: HeaderTypes = None,403 stream: bool = False,404 allow_redirects: bool = True,405 ssl: SSLConfig = None,406 timeout: TimeoutConfig = None,407 ) -> SyncResponse:408 request = Request(409 method, url, data=data, query_params=query_params, headers=headers410 )411 self.prepare_request(request)412 response = self.send(413 request,414 stream=stream,415 allow_redirects=allow_redirects,416 ssl=ssl,417 timeout=timeout,418 )419 return response420421 def get(422 self,423 url: URLTypes,424 *,425 query_params: QueryParamTypes = None,426 headers: HeaderTypes = None,427 stream: bool = False,428 allow_redirects: bool = True,429 ssl: SSLConfig = None,430 timeout: TimeoutConfig = None,431 ) -> SyncResponse:432 return self.request(433 "GET",434 url,435 headers=headers,436 stream=stream,437 allow_redirects=allow_redirects,438 ssl=ssl,439 timeout=timeout,440 )441442 def options(443 self,444 url: URLTypes,445 *,446 query_params: QueryParamTypes = None,447 headers: HeaderTypes = None,448 stream: bool = False,449 allow_redirects: bool = True,450 ssl: SSLConfig = None,451 timeout: TimeoutConfig = None,452 ) -> SyncResponse:453 return self.request(454 "OPTIONS",455 url,456 headers=headers,457 stream=stream,458 allow_redirects=allow_redirects,459 ssl=ssl,460 timeout=timeout,461 )462463 def head(464 self,465 url: URLTypes,466 *,467 query_params: QueryParamTypes = None,468 headers: HeaderTypes = None,469 stream: bool = False,470 allow_redirects: bool = False, # Note: Differs to usual default.471 ssl: SSLConfig = None,472 timeout: TimeoutConfig = None,473 ) -> SyncResponse:474 return self.request(475 "HEAD",476 url,477 headers=headers,478 stream=stream,479 allow_redirects=allow_redirects,480 ssl=ssl,481 timeout=timeout,482 )483484 def post(485 self,486 url: URLTypes,487 *,488 data: RequestData = b"",489 query_params: QueryParamTypes = None,490 headers: HeaderTypes = None,491 stream: bool = False,492 allow_redirects: bool = True,493 ssl: SSLConfig = None,494 timeout: TimeoutConfig = None,495 ) -> SyncResponse:496 return self.request(497 "POST",498 url,499 data=data,500 headers=headers,501 stream=stream,502 allow_redirects=allow_redirects,503 ssl=ssl,504 timeout=timeout,505 )506507 def put(508 self,509 url: URLTypes,510 *,511 data: RequestData = b"",512 query_params: QueryParamTypes = None,513 headers: HeaderTypes = None,514 stream: bool = False,515 allow_redirects: bool = True,516 ssl: SSLConfig = None,517 timeout: TimeoutConfig = None,518 ) -> SyncResponse:519 return self.request(520 "PUT",521 url,522 data=data,523 headers=headers,524 stream=stream,525 allow_redirects=allow_redirects,526 ssl=ssl,527 timeout=timeout,528 )529530 def patch(531 self,532 url: URLTypes,533 *,534 data: RequestData = b"",535 query_params: QueryParamTypes = None,536 headers: HeaderTypes = None,537 stream: bool = False,538 allow_redirects: bool = True,539 ssl: SSLConfig = None,540 timeout: TimeoutConfig = None,541 ) -> SyncResponse:542 return self.request(543 "PATCH",544 url,545 data=data,546 headers=headers,547 stream=stream,548 allow_redirects=allow_redirects,549 ssl=ssl,550 timeout=timeout,551 )552553 def delete(554 self,555 url: URLTypes,556 *,557 data: RequestData = b"",558 query_params: QueryParamTypes = None,559 headers: HeaderTypes = None,560 stream: bool = False,561 allow_redirects: bool = True,562 ssl: SSLConfig = None,563 timeout: TimeoutConfig = None,564 ) -> SyncResponse:565 return self.request(566 "DELETE",567 url,568 data=data,569 headers=headers,570 stream=stream,571 allow_redirects=allow_redirects,572 ssl=ssl,573 timeout=timeout,574 )575576 def prepare_request(self, request: Request) -> None:577 self._client.prepare_request(request)578579 def send(580 self,581 request: Request,582 *,583 stream: bool = False,584 allow_redirects: bool = True,585 ssl: SSLConfig = None,586 timeout: TimeoutConfig = None,587 ) -> SyncResponse:588 response = self._loop.run_until_complete(589 self._client.send(590 request,591 stream=stream,592 allow_redirects=allow_redirects,593 ssl=ssl,594 timeout=timeout,595 )596 )597 return SyncResponse(response, self._loop)598599 def close(self) -> None:600 self._loop.run_until_complete(self._client.close())601602 def __enter__(self) -> "Client":603 return self604605 def __exit__(606 self,607 exc_type: typing.Type[BaseException] = None,608 exc_value: BaseException = None,609 traceback: TracebackType = None,610 ) -> None:611 self.close()