Skip to content
Myr

client.py

This file

Path

httpcore/client.py

606 lines · 16.9 KiB · Python

Last changed by

Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369

History of this file

Take 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 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    ):40        if dispatch is None:41            dispatch = ConnectionPool(ssl=ssl, timeout=timeout, pool_limits=pool_limits)4243        self.max_redirects = max_redirects44        self.dispatch = dispatch4546    async def get(47        self,48        url: URLTypes,49        *,50        query_params: QueryParamTypes = None,51        headers: HeaderTypes = None,52        stream: bool = False,53        allow_redirects: bool = True,54        ssl: SSLConfig = None,55        timeout: TimeoutConfig = None,56    ) -> Response:57        return await self.request(58            "GET",59            url,60            query_params=query_params,61            headers=headers,62            stream=stream,63            allow_redirects=allow_redirects,64            ssl=ssl,65            timeout=timeout,66        )6768    async def options(69        self,70        url: URLTypes,71        *,72        query_params: QueryParamTypes = None,73        headers: HeaderTypes = None,74        stream: bool = False,75        allow_redirects: bool = True,76        ssl: SSLConfig = None,77        timeout: TimeoutConfig = None,78    ) -> Response:79        return await self.request(80            "OPTIONS",81            url,82            query_params=query_params,83            headers=headers,84            stream=stream,85            allow_redirects=allow_redirects,86            ssl=ssl,87            timeout=timeout,88        )8990    async def head(91        self,92        url: URLTypes,93        *,94        query_params: QueryParamTypes = None,95        headers: HeaderTypes = None,96        stream: bool = False,97        allow_redirects: bool = False,  #  Note: Differs to usual default.98        ssl: SSLConfig = None,99        timeout: TimeoutConfig = None,100    ) -> Response:101        return await self.request(102            "HEAD",103            url,104            query_params=query_params,105            headers=headers,106            stream=stream,107            allow_redirects=allow_redirects,108            ssl=ssl,109            timeout=timeout,110        )111112    async def post(113        self,114        url: URLTypes,115        *,116        data: RequestData = b"",117        query_params: QueryParamTypes = None,118        headers: HeaderTypes = None,119        stream: bool = False,120        allow_redirects: bool = True,121        ssl: SSLConfig = None,122        timeout: TimeoutConfig = None,123    ) -> Response:124        return await self.request(125            "POST",126            url,127            data=data,128            query_params=query_params,129            headers=headers,130            stream=stream,131            allow_redirects=allow_redirects,132            ssl=ssl,133            timeout=timeout,134        )135136    async def put(137        self,138        url: URLTypes,139        *,140        data: RequestData = b"",141        query_params: QueryParamTypes = None,142        headers: HeaderTypes = None,143        stream: bool = False,144        allow_redirects: bool = True,145        ssl: SSLConfig = None,146        timeout: TimeoutConfig = None,147    ) -> Response:148        return await self.request(149            "PUT",150            url,151            data=data,152            query_params=query_params,153            headers=headers,154            stream=stream,155            allow_redirects=allow_redirects,156            ssl=ssl,157            timeout=timeout,158        )159160    async def patch(161        self,162        url: URLTypes,163        *,164        data: RequestData = b"",165        query_params: QueryParamTypes = None,166        headers: HeaderTypes = None,167        stream: bool = False,168        allow_redirects: bool = True,169        ssl: SSLConfig = None,170        timeout: TimeoutConfig = None,171    ) -> Response:172        return await self.request(173            "PATCH",174            url,175            data=data,176            query_params=query_params,177            headers=headers,178            stream=stream,179            allow_redirects=allow_redirects,180            ssl=ssl,181            timeout=timeout,182        )183184    async def delete(185        self,186        url: URLTypes,187        *,188        data: RequestData = b"",189        query_params: QueryParamTypes = None,190        headers: HeaderTypes = None,191        stream: bool = False,192        allow_redirects: bool = True,193        ssl: SSLConfig = None,194        timeout: TimeoutConfig = None,195    ) -> Response:196        return await self.request(197            "DELETE",198            url,199            data=data,200            query_params=query_params,201            headers=headers,202            stream=stream,203            allow_redirects=allow_redirects,204            ssl=ssl,205            timeout=timeout,206        )207208    async def request(209        self,210        method: str,211        url: URLTypes,212        *,213        data: RequestData = b"",214        query_params: QueryParamTypes = None,215        headers: HeaderTypes = None,216        stream: bool = False,217        allow_redirects: bool = True,218        ssl: SSLConfig = None,219        timeout: TimeoutConfig = None,220    ) -> Response:221        request = Request(222            method, url, data=data, query_params=query_params, headers=headers223        )224        self.prepare_request(request)225        response = await self.send(226            request,227            stream=stream,228            allow_redirects=allow_redirects,229            ssl=ssl,230            timeout=timeout,231        )232        return response233234    def prepare_request(self, request: Request) -> None:235        request.prepare()236237    async def send(238        self,239        request: Request,240        *,241        stream: bool = False,242        ssl: SSLConfig = None,243        timeout: TimeoutConfig = None,244        allow_redirects: bool = True,245        history: typing.List[Response] = None,246    ) -> Response:247        if history is None:248            history = []249250        while True:251            # We perform these checks here, so that calls to `response.next()`252            # will raise redirect errors if appropriate.253            if len(history) > self.max_redirects:254                raise TooManyRedirects()255            if request.url in [response.url for response in history]:256                raise RedirectLoop()257258            response = await self.dispatch.send(259                request, stream=stream, ssl=ssl, timeout=timeout260            )261            response.history = list(history)262            history = [response] + history263            if not response.is_redirect:264                break265266            if allow_redirects:267                request = self.build_redirect_request(request, response)268            else:269270                async def send_next() -> Response:271                    nonlocal request, response, ssl, allow_redirects, timeout, history272                    request = self.build_redirect_request(request, response)273                    response = await self.send(274                        request,275                        stream=stream,276                        allow_redirects=allow_redirects,277                        ssl=ssl,278                        timeout=timeout,279                        history=history,280                    )281                    return response282283                response.next = send_next  # type: ignore284                break285286        return response287288    def build_redirect_request(self, request: Request, response: Response) -> Request:289        method = self.redirect_method(request, response)290        url = self.redirect_url(request, response)291        headers = self.redirect_headers(request, url)292        content = self.redirect_content(request, method)293        return Request(method=method, url=url, headers=headers, data=content)294295    def redirect_method(self, request: Request, response: Response) -> str:296        """297        When being redirected we may want to change the method of the request298        based on certain specs or browser behavior.299        """300        method = request.method301302        # https://tools.ietf.org/html/rfc7231#section-6.4.4303        if response.status_code == codes.SEE_OTHER and method != "HEAD":304            method = "GET"305306        # Do what the browsers do, despite standards...307        # Turn 302s into GETs.308        if response.status_code == codes.FOUND and method != "HEAD":309            method = "GET"310311        # If a POST is responded to with a 301, turn it into a GET.312        # This bizarre behaviour is explained in 'requests' issue 1704.313        if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":314            method = "GET"315316        return method317318    def redirect_url(self, request: Request, response: Response) -> URL:319        """320        Return the URL for the redirect to follow.321        """322        location = response.headers["Location"]323324        url = URL(location, allow_relative=True)325326        # Facilitate relative 'Location' headers, as allowed by RFC 7231.327        # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')328        if url.is_relative_url:329            url = url.resolve_with(request.url)330331        # Attach previous fragment if needed (RFC 7231 7.1.2)332        if request.url.fragment and not url.fragment:333            url = url.copy_with(fragment=request.url.fragment)334335        return url336337    def redirect_headers(self, request: Request, url: URL) -> Headers:338        """339        Strip Authorization headers when responses are redirected away from340        the origin.341        """342        headers = Headers(request.headers)343        if url.origin != request.url.origin:344            del headers["Authorization"]345        return headers346347    def redirect_content(self, request: Request, method: str) -> bytes:348        """349        Return the body that should be used for the redirect request.350        """351        if method != request.method and method == "GET":352            return b""353        if request.is_streaming:354            raise RedirectBodyUnavailable()355        return request.content356357    async def close(self) -> None:358        await self.dispatch.close()359360    async def __aenter__(self) -> "AsyncClient":361        return self362363    async def __aexit__(364        self,365        exc_type: typing.Type[BaseException] = None,366        exc_value: BaseException = None,367        traceback: TracebackType = None,368    ) -> None:369        await self.close()370371372class Client:373    def __init__(374        self,375        ssl: SSLConfig = DEFAULT_SSL_CONFIG,376        timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,377        pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,378        max_redirects: int = DEFAULT_MAX_REDIRECTS,379        dispatch: Dispatcher = None,380    ) -> None:381        self._client = AsyncClient(382            ssl=ssl,383            timeout=timeout,384            pool_limits=pool_limits,385            max_redirects=max_redirects,386            dispatch=dispatch,387        )388        self._loop = asyncio.new_event_loop()389390    def request(391        self,392        method: str,393        url: URLTypes,394        *,395        data: RequestData = b"",396        query_params: QueryParamTypes = None,397        headers: HeaderTypes = None,398        stream: bool = False,399        allow_redirects: bool = True,400        ssl: SSLConfig = None,401        timeout: TimeoutConfig = None,402    ) -> SyncResponse:403        request = Request(404            method, url, data=data, query_params=query_params, headers=headers405        )406        self.prepare_request(request)407        response = self.send(408            request,409            stream=stream,410            allow_redirects=allow_redirects,411            ssl=ssl,412            timeout=timeout,413        )414        return response415416    def get(417        self,418        url: URLTypes,419        *,420        query_params: QueryParamTypes = None,421        headers: HeaderTypes = None,422        stream: bool = False,423        allow_redirects: bool = True,424        ssl: SSLConfig = None,425        timeout: TimeoutConfig = None,426    ) -> SyncResponse:427        return self.request(428            "GET",429            url,430            headers=headers,431            stream=stream,432            allow_redirects=allow_redirects,433            ssl=ssl,434            timeout=timeout,435        )436437    def options(438        self,439        url: URLTypes,440        *,441        query_params: QueryParamTypes = None,442        headers: HeaderTypes = None,443        stream: bool = False,444        allow_redirects: bool = True,445        ssl: SSLConfig = None,446        timeout: TimeoutConfig = None,447    ) -> SyncResponse:448        return self.request(449            "OPTIONS",450            url,451            headers=headers,452            stream=stream,453            allow_redirects=allow_redirects,454            ssl=ssl,455            timeout=timeout,456        )457458    def head(459        self,460        url: URLTypes,461        *,462        query_params: QueryParamTypes = None,463        headers: HeaderTypes = None,464        stream: bool = False,465        allow_redirects: bool = False,  #  Note: Differs to usual default.466        ssl: SSLConfig = None,467        timeout: TimeoutConfig = None,468    ) -> SyncResponse:469        return self.request(470            "HEAD",471            url,472            headers=headers,473            stream=stream,474            allow_redirects=allow_redirects,475            ssl=ssl,476            timeout=timeout,477        )478479    def post(480        self,481        url: URLTypes,482        *,483        data: RequestData = b"",484        query_params: QueryParamTypes = None,485        headers: HeaderTypes = None,486        stream: bool = False,487        allow_redirects: bool = True,488        ssl: SSLConfig = None,489        timeout: TimeoutConfig = None,490    ) -> SyncResponse:491        return self.request(492            "POST",493            url,494            data=data,495            headers=headers,496            stream=stream,497            allow_redirects=allow_redirects,498            ssl=ssl,499            timeout=timeout,500        )501502    def put(503        self,504        url: URLTypes,505        *,506        data: RequestData = b"",507        query_params: QueryParamTypes = None,508        headers: HeaderTypes = None,509        stream: bool = False,510        allow_redirects: bool = True,511        ssl: SSLConfig = None,512        timeout: TimeoutConfig = None,513    ) -> SyncResponse:514        return self.request(515            "PUT",516            url,517            data=data,518            headers=headers,519            stream=stream,520            allow_redirects=allow_redirects,521            ssl=ssl,522            timeout=timeout,523        )524525    def patch(526        self,527        url: URLTypes,528        *,529        data: RequestData = b"",530        query_params: QueryParamTypes = None,531        headers: HeaderTypes = None,532        stream: bool = False,533        allow_redirects: bool = True,534        ssl: SSLConfig = None,535        timeout: TimeoutConfig = None,536    ) -> SyncResponse:537        return self.request(538            "PATCH",539            url,540            data=data,541            headers=headers,542            stream=stream,543            allow_redirects=allow_redirects,544            ssl=ssl,545            timeout=timeout,546        )547548    def delete(549        self,550        url: URLTypes,551        *,552        data: RequestData = b"",553        query_params: QueryParamTypes = None,554        headers: HeaderTypes = None,555        stream: bool = False,556        allow_redirects: bool = True,557        ssl: SSLConfig = None,558        timeout: TimeoutConfig = None,559    ) -> SyncResponse:560        return self.request(561            "DELETE",562            url,563            data=data,564            headers=headers,565            stream=stream,566            allow_redirects=allow_redirects,567            ssl=ssl,568            timeout=timeout,569        )570571    def prepare_request(self, request: Request) -> None:572        self._client.prepare_request(request)573574    def send(575        self,576        request: Request,577        *,578        stream: bool = False,579        allow_redirects: bool = True,580        ssl: SSLConfig = None,581        timeout: TimeoutConfig = None,582    ) -> SyncResponse:583        response = self._loop.run_until_complete(584            self._client.send(585                request,586                stream=stream,587                allow_redirects=allow_redirects,588                ssl=ssl,589                timeout=timeout,590            )591        )592        return SyncResponse(response, self._loop)593594    def close(self) -> None:595        self._loop.run_until_complete(self._client.close())596597    def __enter__(self) -> "Client":598        return self599600    def __exit__(601        self,602        exc_type: typing.Type[BaseException] = None,603        exc_value: BaseException = None,604        traceback: TracebackType = None,605    ) -> None:606        self.close()