Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
async_client.py128 linesDownload Raw Back to msrest
1# --------------------------------------------------------------------------2#3# Copyright (c) Microsoft Corporation. All rights reserved.4#5# The MIT License (MIT)6#7# Permission is hereby granted, free of charge, to any person obtaining a copy8# of this software and associated documentation files (the ""Software""), to9# deal in the Software without restriction, including without limitation the10# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or11# sell copies of the Software, and to permit persons to whom the Software is12# furnished to do so, subject to the following conditions:13#14# The above copyright notice and this permission notice shall be included in15# all copies or substantial portions of the Software.16#17# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING22# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS23# IN THE SOFTWARE.24#25# --------------------------------------------------------------------------26 27import functools28import logging29 30from typing import Any, Dict, List, Union, TYPE_CHECKING31 32from .universal_http import ClientRequest33from .universal_http.async_requests import AsyncRequestsHTTPSender34from .pipeline import Request, AsyncPipeline, AsyncHTTPPolicy, SansIOHTTPPolicy35from .pipeline.async_requests import (36    AsyncPipelineRequestsHTTPSender,37    AsyncRequestsCredentialsPolicy38)39from .pipeline.universal import (40    HTTPLogger,41    RawDeserializer,42)43 44from .service_client import _ServiceClientCore45 46if TYPE_CHECKING:47    from .configuration import Configuration  # pylint: disable=unused-import48 49_LOGGER = logging.getLogger(__name__)50 51 52class SDKClientAsync:53    """The base class of all generated SDK async client.54    """55 56    def __init__(self, config: 'Configuration') -> None:57        self._client = ServiceClientAsync(config)58 59    async def __aenter__(self):60        await self._client.__aenter__()61        return self62 63    async def __aexit__(self, *exc_details):64        await self._client.__aexit__(*exc_details)65 66 67class ServiceClientAsync(_ServiceClientCore):68 69    def __init__(self, config: 'Configuration') -> None:70        super(ServiceClientAsync, self).__init__(config)71 72        self.config.pipeline = self._create_default_pipeline()  # type: ignore73 74    def _create_default_pipeline(self):75        creds = self.config.credentials76 77        policies = [78            self.config.user_agent_policy,  # UserAgent policy79            RawDeserializer(),         # Deserialize the raw bytes80            self.config.http_logger_policy  # HTTP request/response log81        ]  # type: List[Union[AsyncHTTPPolicy, SansIOHTTPPolicy]]82        if creds:83            if isinstance(creds, (AsyncHTTPPolicy, SansIOHTTPPolicy)):84                policies.insert(1, creds)85            else:86                # Assume this is the old credentials class, and then requests. Wrap it.87                policies.insert(1, AsyncRequestsCredentialsPolicy(creds))88 89        return AsyncPipeline(90            policies,91            AsyncPipelineRequestsHTTPSender(92                AsyncRequestsHTTPSender(self.config)  # Send HTTP request using requests93            )94        )95 96    async def __aenter__(self):97        await self.config.pipeline.__aenter__()98        return self99 100    async def __aexit__(self, *exc_details):101        await self.config.pipeline.__aexit__(*exc_details)102 103    async def async_send(self, request, **kwargs):104        """Prepare and send request object according to configuration.105 106        :param ClientRequest request: The request object to be sent.107        :param dict headers: Any headers to add to the request.108        :param content: Any body data to add to the request.109        :param config: Any specific config overrides110        """111        kwargs.setdefault('stream', True)112        # In the current backward compatible implementation, return the HTTP response113        # and plug context inside. Could be remove if we modify Autorest,114        # but we still need it to be backward compatible115        pipeline_response = await self.config.pipeline.run(request, **kwargs)116        response = pipeline_response.http_response117        response.context = pipeline_response.context118        return response119 120    def stream_download_async(self, response, user_callback):121        """Async Generator for streaming request body data.122 123        :param response: The initial response124        :param user_callback: Custom callback for monitoring progress.125        """126        block = self.config.connection.data_block_size127        return response.stream_download(block, user_callback)128 
codekingpro/portable-devtools · Team Ai