Пример #1
0
    def _create_appconfig_pipeline(self, credential, base_url=None, aad_mode=False, **kwargs):
        transport = kwargs.get('transport')
        policies = kwargs.get('policies')

        if policies is None:  # [] is a valid policy list
            if aad_mode:
                scope = base_url.strip("/") + "/.default"
                if hasattr(credential, "get_token"):
                    credential_policy = AsyncBearerTokenCredentialPolicy(credential, scope)
                else:
                    raise TypeError("Please provide an instance from azure-identity "
                                    "or a class that implement the 'get_token protocol")
            else:
                credential_policy = AppConfigRequestsCredentialsPolicy(credential)

            policies = [
                self._config.headers_policy,
                self._config.user_agent_policy,
                credential_policy,
                self._config.retry_policy,
                SyncTokenPolicy(),
                self._config.logging_policy,  # HTTP request/response log
                DistributedTracingPolicy(**kwargs),
                HttpLoggingPolicy(**kwargs),
            ]

        if not transport:
            transport = AsyncioRequestsTransport(**kwargs)

        return AsyncPipeline(
            transport,
            policies,
        )
Пример #2
0
async def test_async_transport_sleep():

    async with AsyncioRequestsTransport() as transport:
        await transport.sleep(1)

    async with AioHttpTransport() as transport:
        await transport.sleep(1)
Пример #3
0
async def test_send_data(port):
    async with AsyncioRequestsTransport() as transport:
        req = HttpRequest('PUT',
                          'http://localhost:{}/basic/anything'.format(port),
                          data=b"azerty")
        response = await transport.send(req)
        assert json.loads(response.text())['data'] == "azerty"
Пример #4
0
async def test_send_data(port):
    async with AsyncioRequestsTransport() as transport:
        client = AsyncTestRestClient(port, transport=transport)
        request = HttpRequest('PUT', 'http://localhost:{}/basic/anything'.format(port), content=b"azerty")
        response = await client.send_request(request)

        assert response.json()['data'] == "azerty"
Пример #5
0
async def test_conf_async_requests():

    request = HttpRequest("GET", "https://www.bing.com/")
    async with AsyncioRequestsTransport() as sender:
        response = await sender.send(request)
        assert response.body() is not None

    assert isinstance(response.status_code, int)
Пример #6
0
async def test_conf_async_requests():

    conf = Configuration()
    request = HttpRequest("GET", "https://www.bing.com/")
    async with AsyncioRequestsTransport(conf) as sender:
        response = await sender.send(request)
        assert response.body() is not None

    assert response.status_code == 200
Пример #7
0
async def test_conf_async_requests():

    request = HttpRequest("GET", "https://bing.com/")
    policies = [UserAgentPolicy("myusergant"), AsyncRedirectPolicy()]
    async with AsyncPipeline(AsyncioRequestsTransport(),
                             policies=policies) as pipeline:
        response = await pipeline.run(request)

    assert isinstance(response.http_response.status_code, int)
async def test_conf_async_requests(port, http_request):

    request = http_request("GET",
                           "http://localhost:{}/basic/string".format(port))
    async with AsyncioRequestsTransport() as sender:
        response = await sender.send(request)
        assert response.body() is not None

    assert isinstance(response.status_code, int)
Пример #9
0
async def test_conf_async_requests(port):

    request = HttpRequest("GET",
                          "http://localhost:{}/basic/string".format(port))
    policies = [UserAgentPolicy("myusergant"), AsyncRedirectPolicy()]
    async with AsyncPipeline(AsyncioRequestsTransport(),
                             policies=policies) as pipeline:
        response = await pipeline.run(request)

    assert isinstance(response.http_response.status_code, int)
async def test_example_asyncio():

    request = HttpRequest("GET", "https://bing.com")
    policies = [UserAgentPolicy("myuseragent"), AsyncRedirectPolicy()]
    # [START asyncio]
    from azure.core.pipeline.transport import AsyncioRequestsTransport

    async with AsyncPipeline(AsyncioRequestsTransport(),
                             policies=policies) as pipeline:
        response = await pipeline.run(request)
    # [END asyncio]
    assert pipeline._transport.session is None
    assert response.http_response.status_code == 200
    def _create_appconfig_pipeline(self):
        policies = [
            self.config.headers_policy,
            self.config.user_agent_policy,
            self.config.logging_policy,  # HTTP request/response log
            AppConfigRequestsCredentialsPolicy(self.config.credentials),
            DistributedTracingPolicy()
        ]

        return AsyncPipeline(
            AsyncioRequestsTransport(configuration=self.config),  # Send HTTP request using requests
            policies,
        )
    def _build_pipeline(config: Configuration, transport: HttpTransport,
                        **kwargs: Any) -> AsyncPipeline:
        policies = [
            config.headers_policy, config.user_agent_policy,
            config.proxy_policy, config.redirect_policy, config.retry_policy,
            config.authentication_policy, config.logging_policy,
            DistributedTracingPolicy()
        ]

        if transport is None:
            transport = AsyncioRequestsTransport(**kwargs)

        return AsyncPipeline(transport, policies=policies)
Пример #13
0
 def __init__(self,
              config: "Optional[Configuration]" = None,
              policies: "Optional[Iterable[HTTPPolicy]]" = None,
              transport: "Optional[AsyncHttpTransport]" = None,
              **kwargs: "Any") -> None:
     config = config or self._create_config(**kwargs)
     policies = policies or [
         ContentDecodePolicy(),
         config.retry_policy,
         config.logging_policy,
         DistributedTracingPolicy(),
     ]
     if not transport:
         transport = AsyncioRequestsTransport(**kwargs)
     self._pipeline = AsyncPipeline(transport=transport, policies=policies)
     super().__init__(**kwargs)
Пример #14
0
    def _build_pipeline(config: Configuration,
                        transport: HttpTransport) -> AsyncPipeline:
        policies = [
            config.headers_policy,
            config.user_agent_policy,
            config.proxy_policy,
            config.redirect_policy,
            config.retry_policy,
            config.authentication_policy,
            config.logging_policy,
        ]

        if transport is None:
            transport = AsyncioRequestsTransport(config)

        return AsyncPipeline(transport, policies=policies)
async def test_async_gen_data():
    class AsyncGen:
        def __init__(self):
            self._range = iter([b"azerty"])

        def __aiter__(self):
            return self

        async def __anext__(self):
            try:
                return next(self._range)
            except StopIteration:
                raise StopAsyncIteration

    async with AsyncioRequestsTransport() as transport:
        req = HttpRequest('GET', 'http://httpbin.org/post', data=AsyncGen())
        await transport.send(req)
Пример #16
0
async def test_async_gen_data(port):
    class AsyncGen:
        def __init__(self):
            self._range = iter([b"azerty"])

        def __aiter__(self):
            return self

        async def __anext__(self):
            try:
                return next(self._range)
            except StopIteration:
                raise StopAsyncIteration

    async with AsyncioRequestsTransport() as transport:
        client = AsyncTestRestClient(port, transport=transport)
        request = HttpRequest('GET', 'http://localhost:{}/basic/anything'.format(port), content=AsyncGen())
        response = await client.send_request(request)
        assert response.json()['data'] == "azerty"
Пример #17
0
async def test_async_gen_data(port):
    class AsyncGen:
        def __init__(self):
            self._range = iter([b"azerty"])

        def __aiter__(self):
            return self

        async def __anext__(self):
            try:
                return next(self._range)
            except StopIteration:
                raise StopAsyncIteration

    async with AsyncioRequestsTransport() as transport:
        req = HttpRequest('GET',
                          'http://localhost:{}/basic/anything'.format(port),
                          data=AsyncGen())
        response = await transport.send(req)
        assert json.loads(response.text())['data'] == "azerty"
Пример #18
0
    def _create_appconfig_pipeline(self, **kwargs):
        transport = kwargs.get('transport')
        policies = kwargs.get('policies')

        if policies is None:  # [] is a valid policy list
            policies = [
                self.config.headers_policy,
                self.config.user_agent_policy,
                AppConfigRequestsCredentialsPolicy(self.config.credentials),
                self.config.retry_policy,
                self.config.logging_policy,  # HTTP request/response log
                DistributedTracingPolicy(),
            ]

        if not transport:
            transport = AsyncioRequestsTransport(**kwargs)

        return AsyncPipeline(
            transport,
            policies,
        )
Пример #19
0
    def __init__(self, identity_service_url: str, **kwargs: Any) -> None:  # pylint: disable=missing-client-constructor-parameter-credential
        client = kwargs.get("generated_client")
        if client:
            # caller provided a configured client -> nothing left to initialize
            self._client = client
            return

        try:
            identity_service_url = identity_service_url.strip(" /")
            if not identity_service_url.lower().startswith("https://"):
                self._identity_service_url = "https://" + identity_service_url
            else:
                self._identity_service_url = identity_service_url
        except AttributeError:
            raise ValueError("Identity Service URL must be a string.")

        self.api_version = kwargs.pop("api_version", DEFAULT_VERSION)

        pipeline = kwargs.pop("pipeline", None)
        transport = kwargs.pop("transport", AsyncioRequestsTransport(**kwargs))
        http_logging_policy = HttpLoggingPolicy(**kwargs)
        http_logging_policy.allowed_header_names.update(
            {
                "x-ms-keyvault-network-info",
                "x-ms-keyvault-region",
                "x-ms-keyvault-service-version",
            }
        )

        authentication_policy = None

        self._client = _ConfidentialLedgerIdentityServiceClient(
            self._identity_service_url,
            api_version=self.api_version,
            pipeline=pipeline,
            transport=transport,
            authentication_policy=authentication_policy,
            http_logging_policy=http_logging_policy,
            **kwargs
        )
Пример #20
0
    def __init__(self,
                 vault_url,
                 credentials,
                 config=None,
                 api_version=None,
                 **kwargs):
        if not credentials:
            raise ValueError("credentials")

        if not vault_url:
            raise ValueError("vault_url")

        self._vault_url = vault_url

        if api_version is None:
            api_version = KeyVaultClient.DEFAULT_API_VERSION

        # TODO: need config to get default policies, config requires credentials but doesn't do anything with them
        config = config or KeyVaultClient.get_configuration_class(
            api_version, aio=True)(credentials)

        # TODO generated default pipeline should be fine when token policy isn't necessary
        policies = [
            config.headers_policy,
            config.user_agent_policy,
            config.proxy_policy,
            _BearerTokenCredentialPolicy(credentials),
            config.redirect_policy,
            config.retry_policy,
            config.logging_policy,
        ]
        transport = AsyncioRequestsTransport(config)
        pipeline = AsyncPipeline(transport, policies=policies)

        self._client = KeyVaultClient(credentials,
                                      api_version=api_version,
                                      pipeline=pipeline,
                                      aio=True)
async def client(port):
    async with AsyncioRequestsTransport() as transport:
        async with AsyncTestRestClient(port, transport=transport) as client:
            yield client
async def test_send_data():
    async with AsyncioRequestsTransport() as transport:
        req = HttpRequest('PUT', 'http://httpbin.org/anything', data=b"azerty")
        response = await transport.send(req)

        assert json.loads(response.text())['data'] == "azerty"