azure.core.pipeline.transport

class azure.core.pipeline.transport.AioHttpTransport(*, session: ClientSession | None = None, loop=None, session_owner: bool = True, **kwargs)[source]

AioHttp HTTP sender implementation.

Fully asynchronous implementation using the aiohttp library.

Keyword Arguments:
  • session (ClientSession) – The client session.

  • session_owner (bool) – Session owner. Defaults True.

  • use_env_settings (bool) – Uses proxy settings from environment. Defaults to True.

Example:

Asynchronous transport with aiohttp.
from azure.core.pipeline.transport import AioHttpTransport

async with AsyncPipeline(AioHttpTransport(), policies=policies) as pipeline:
    response = await pipeline.run(request)
async close()[source]

Closes the connection.

async open()[source]

Opens the connection.

async send(request: HttpRequest, *, stream: bool = False, proxies: MutableMapping[str, str] | None = None, **config: Any) AsyncHttpResponse[source]
async send(request: RestHttpRequest, *, stream: bool = False, proxies: MutableMapping[str, str] | None = None, **config: Any) RestAsyncHttpResponse

Send the request using this HTTP sender.

Will pre-load the body into memory to be available with a sync method. Pass stream=True to avoid this behavior.

Parameters:

request (HttpRequest) – The HttpRequest object

Returns:

The AsyncHttpResponse

Return type:

AsyncHttpResponse

Keyword Arguments:
  • stream (bool) – Defaults to False.

  • proxies (MutableMapping) – dict of proxy to used based on protocol. Proxy is a dict (protocol, url)

async sleep(duration: float) None

Sleep for the specified duration.

You should always ask the transport to sleep, and not call directly the stdlib. This is mostly important in async, as the transport may not use asyncio but other implementation like trio and they their own way to sleep, but to keep design consistent, it’s cleaner to always ask the transport to sleep and let the transport implementor decide how to do it. By default, this method will use “asyncio”, and don’t need to be overridden if your transport does too.

Parameters:

duration (float) – The number of seconds to sleep.

class azure.core.pipeline.transport.AioHttpTransportResponse(request: HttpRequest, aiohttp_response: ClientResponse, block_size: int | None = None, *, decompress: bool = True)[source]

Methods for accessing response body data.

Parameters:
  • request (HttpRequest) – The HttpRequest object

  • aiohttp_response (aiohttp.ClientResponse object) – Returned from ClientSession.request().

  • block_size (int) – block size of data sent over connection.

Keyword Arguments:

decompress (bool) – If True which is default, will attempt to decode the body based on the content-encoding header.

body() bytes[source]

Return the whole body as bytes in memory.

Return type:

bytes

Returns:

The whole response body.

async load_body() None[source]

Load in memory the body, so it could be accessible from sync methods.

parts() AsyncIterator[AsyncHttpResponse]

Assuming the content-type is multipart/mixed, will return the parts as an async iterator.

Returns:

An async iterator of the parts

Return type:

AsyncIterator

Raises:

ValueError – If the content is not multipart/mixed

raise_for_status() None

Raises an HttpResponseError if the response has an error status code. If response is good, does nothing.

stream_download(pipeline: AsyncPipeline[HttpRequest, AsyncHttpResponse], *, decompress: bool = True, **kwargs) AsyncIterator[bytes][source]

Generator for streaming response body data.

Parameters:

pipeline (azure.core.pipeline.AsyncPipeline) – The pipeline object

Keyword Arguments:

decompress (bool) – If True which is default, will attempt to decode the body based on the content-encoding header.

Return type:

AsyncIterator[bytes]

Returns:

An iterator of bytes chunks.

text(encoding: str | None = None) str[source]

Return the whole body as a string.

If encoding is not provided, rely on aiohttp auto-detection.

Parameters:

encoding (str) – The encoding to apply.

Return type:

str

Returns:

The whole response body as a string.

class azure.core.pipeline.transport.AsyncHttpResponse(request: HttpRequest, internal_response: Any, block_size: int | None = None)[source]

An AsyncHttpResponse ABC.

Allows for the asynchronous streaming of data from the response.

body() bytes

Return the whole body as bytes in memory.

Sync implementer should load the body in memory if they can. Async implementer should rely on async load_body to have been called first.

Return type:

bytes

Returns:

The whole body as bytes in memory.

parts() AsyncIterator[AsyncHttpResponse][source]

Assuming the content-type is multipart/mixed, will return the parts as an async iterator.

Returns:

An async iterator of the parts

Return type:

AsyncIterator

Raises:

ValueError – If the content is not multipart/mixed

raise_for_status() None

Raises an HttpResponseError if the response has an error status code. If response is good, does nothing.

stream_download(pipeline: AsyncPipeline[HttpRequest, 'AsyncHttpResponse'], *, decompress: bool = True, **kwargs: Any) AsyncIteratorType[bytes][source]

Generator for streaming response body data.

Should be implemented by sub-classes if streaming download is supported. Will return an asynchronous generator.

Parameters:

pipeline (azure.core.pipeline.Pipeline) – The pipeline object

Keyword Arguments:

decompress (bool) – If True which is default, will attempt to decode the body based on the content-encoding header.

Returns:

An async iterator of bytes

Return type:

AsyncIterator[bytes]

text(encoding: str | None = None) str

Return the whole body as a string.

See also

~body()

Parameters:

encoding (str) – The encoding to apply. If None, use “utf-8” with BOM parsing (utf-8-sig). Implementation can be smarter if they want (using headers or chardet).

Return type:

str

Returns:

The whole body as a string.

class azure.core.pipeline.transport.AsyncHttpTransport[source]

An http sender ABC.

abstract async close() None[source]

Close the session if it is not externally owned.

abstract async open() None[source]

Assign new session if one does not already exist.

abstract async send(request: HTTPRequestType, **kwargs: Any) AsyncHTTPResponseType[source]

Send the request using this HTTP sender.

Parameters:

request (any) – The request object. Exact type can be inferred from the pipeline.

Returns:

The response object. Exact type can be inferred from the pipeline.

Return type:

any

async sleep(duration: float) None[source]

Sleep for the specified duration.

You should always ask the transport to sleep, and not call directly the stdlib. This is mostly important in async, as the transport may not use asyncio but other implementation like trio and they their own way to sleep, but to keep design consistent, it’s cleaner to always ask the transport to sleep and let the transport implementor decide how to do it. By default, this method will use “asyncio”, and don’t need to be overridden if your transport does too.

Parameters:

duration (float) – The number of seconds to sleep.

class azure.core.pipeline.transport.AsyncioRequestsTransport(**kwargs)[source]

Identical implementation as the synchronous RequestsTransport wrapped in a class with asynchronous methods. Uses the built-in asyncio event loop.

Example:

Asynchronous transport with asyncio.
from azure.core.pipeline.transport import AsyncioRequestsTransport

async with AsyncPipeline(AsyncioRequestsTransport(), policies=policies) as pipeline:
    response = await pipeline.run(request)
close()

Close the session if it is not externally owned.

open()

Assign new session if one does not already exist.

async send(request: HttpRequest, *, proxies: MutableMapping[str, str] | None = None, **kwargs: Any) AsyncHttpResponse[source]
async send(request: RestHttpRequest, *, proxies: MutableMapping[str, str] | None = None, **kwargs: Any) RestAsyncHttpResponse

Send the request using this HTTP sender.

Parameters:

request (HttpRequest) – The HttpRequest

Returns:

The AsyncHttpResponse

Return type:

AsyncHttpResponse

Keyword Arguments:

proxies (MutableMapping) – will define the proxy to use. Proxy is a dict (protocol, url)

async sleep(duration)[source]

Sleep for the specified duration.

You should always ask the transport to sleep, and not call directly the stdlib. This is mostly important in async, as the transport may not use asyncio but other implementations like trio and they have their own way to sleep, but to keep design consistent, it’s cleaner to always ask the transport to sleep and let the transport implementor decide how to do it.

Parameters:

duration (float) – The number of seconds to sleep.

class azure.core.pipeline.transport.AsyncioRequestsTransportResponse(request, requests_response, block_size=None)[source]

Asynchronous streaming of data from the response.

body()

Return the whole body as bytes in memory.

Sync implementer should load the body in memory if they can. Async implementer should rely on async load_body to have been called first.

Return type:

bytes

Returns:

The whole body as bytes in memory.

parts() AsyncIterator[AsyncHttpResponse]

Assuming the content-type is multipart/mixed, will return the parts as an async iterator.

Returns:

An async iterator of the parts

Return type:

AsyncIterator

Raises:

ValueError – If the content is not multipart/mixed

raise_for_status() None

Raises an HttpResponseError if the response has an error status code. If response is good, does nothing.

stream_download(pipeline, **kwargs) AsyncIterator[bytes][source]

Generator for streaming request body data.

Parameters:

pipeline (AsyncPipeline) – The pipeline object

Return type:

AsyncIterator[bytes]

Returns:

An async iterator of bytes chunks

text(encoding: str | None = None) str

Return the whole body as a string.

If encoding is not provided, mostly rely on requests auto-detection, except for BOM, that requests ignores. If we see a UTF8 BOM, we assumes UTF8 unlike requests.

Parameters:

encoding (str) – The encoding to apply.

Return type:

str

Returns:

The body as text.

class azure.core.pipeline.transport.HttpRequest(method: str, url: str, headers: Mapping[str, str] | None = None, files: Any | None = None, data: bytes | str | Dict[str, str | int] | None = None)[source]

Represents an HTTP request.

URL can be given without query parameters, to be added later using “format_parameters”.

Parameters:
  • method (str) – HTTP method (GET, HEAD, etc.)

  • url (str) – At least complete scheme/host/path

  • headers (dict[str,str]) – HTTP headers

  • files (dict[str, tuple[str, IO, str, dict]] or dict[str, IO]) – Dictionary of 'name': file-like-objects (or {'name': file-tuple}) for multipart encoding upload. file-tuple can be a 2-tuple ('filename', fileobj), 3-tuple ('filename', fileobj, 'content_type') or a 4-tuple ('filename', fileobj, 'content_type', custom_headers), where 'content_type' is a string defining the content type of the given file and custom_headers a dict-like object containing additional headers to add for the file.

  • data (bytes or dict (for form)) – Body to be sent.

format_parameters(params: Dict[str, str]) None[source]

Format parameters into a valid query string. It’s assumed all parameters have already been quoted as valid URL strings.

Parameters:

params (dict) – A dictionary of parameters.

prepare_multipart_body(content_index: int = 0) int[source]

Will prepare the body of this request according to the multipart information.

This call assumes the on_request policies have been applied already in their correct context (sync/async)

Does nothing if “set_multipart_mixed” was never called.

Parameters:

content_index (int) – The current index of parts within the batch message.

Returns:

The updated index after all parts in this request have been added.

Return type:

int

serialize() bytes[source]

Serialize this request using application/http spec.

Return type:

bytes

Returns:

The requests serialized as HTTP low-level message in bytes.

set_bytes_body(data: bytes) None[source]

Set generic bytes as the body of the request.

Will set content-length.

Parameters:

data (bytes) – The request field data.

set_formdata_body(data: Dict[str, str] | None = None) None[source]

Set form-encoded data as the body of the request.

Parameters:

data (dict) – The request field data.

set_json_body(data: Any) None[source]

Set a JSON-friendly object as the body of the request.

Parameters:

data (dict) – A JSON serializable object

set_multipart_mixed(*requests: HttpRequest, policies: List[SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType]] | None = None, boundary: str | None = None, **kwargs: Any) None[source]

Set the part of a multipart/mixed.

Only supported args for now are HttpRequest objects.

boundary is optional, and one will be generated if you don’t provide one. Note that no verification are made on the boundary, this is considered advanced enough so you know how to respect RFC1341 7.2.1 and provide a correct boundary.

Any additional kwargs will be passed into the pipeline context for per-request policy configuration.

Parameters:

requests (HttpRequest) – The requests to add to the multipart/mixed

Keyword Arguments:
  • policies (list[SansIOHTTPPolicy]) – SansIOPolicy to apply at preparation time

  • boundary (str) – Optional boundary

set_streamed_data_body(data: Any) None[source]

Set a streamable data body.

Parameters:

data (stream or generator or asyncgenerator) – The request field data.

set_text_body(data: str) None[source]

Set a text as body of the request.

Parameters:

data (str) – A text to send as body.

set_xml_body(data: Any) None[source]

Set an XML element tree as the body of the request.

Parameters:

data (XML node) – The request field data.

property body: bytes | str | Dict[str, str | int] | None

Alias to data.

Return type:

bytes or str or dict or None

Returns:

The body of the request.

property query: Dict[str, str]

The query parameters of the request as a dict.

Return type:

dict[str, str]

Returns:

The query parameters of the request as a dict.

class azure.core.pipeline.transport.HttpResponse(request: HttpRequest, internal_response: Any, block_size: int | None = None)[source]
body() bytes

Return the whole body as bytes in memory.

Sync implementer should load the body in memory if they can. Async implementer should rely on async load_body to have been called first.

Return type:

bytes

Returns:

The whole body as bytes in memory.

parts() Iterator[HttpResponse][source]

Assuming the content-type is multipart/mixed, will return the parts as an iterator.

Return type:

iterator[HttpResponse]

Returns:

The iterator of HttpResponse if request was multipart/mixed

Raises:

ValueError – If the content is not multipart/mixed

raise_for_status() None

Raises an HttpResponseError if the response has an error status code. If response is good, does nothing.

stream_download(pipeline: Pipeline[HttpRequest, 'HttpResponse'], **kwargs: Any) Iterator[bytes][source]

Generator for streaming request body data.

Should be implemented by sub-classes if streaming download is supported.

Parameters:

pipeline (Pipeline) – The pipeline object

Return type:

iterator[bytes]

Returns:

The generator of bytes connected to the socket

text(encoding: str | None = None) str

Return the whole body as a string.

See also

~body()

Parameters:

encoding (str) – The encoding to apply. If None, use “utf-8” with BOM parsing (utf-8-sig). Implementation can be smarter if they want (using headers or chardet).

Return type:

str

Returns:

The whole body as a string.

class azure.core.pipeline.transport.HttpTransport[source]

An http sender ABC.

abstract close() None[source]

Close the session if it is not externally owned.

abstract open() None[source]

Assign new session if one does not already exist.

abstract send(request: HTTPRequestType, **kwargs: Any) HTTPResponseType[source]

Send the request using this HTTP sender.

Parameters:

request (HTTPRequest) – The pipeline request object

Returns:

The pipeline response object.

Return type:

HttpResponse

sleep(duration: float) None[source]

Sleep for the specified duration.

You should always ask the transport to sleep, and not call directly the stdlib. This is mostly important in async, as the transport may not use asyncio but other implementations like trio and they have their own way to sleep, but to keep design consistent, it’s cleaner to always ask the transport to sleep and let the transport implementor decide how to do it.

Parameters:

duration (float) – The number of seconds to sleep.

class azure.core.pipeline.transport.RequestsTransport(**kwargs)[source]

Implements a basic requests HTTP sender.

Since requests team recommends to use one session per requests, you should not consider this class as thread-safe, since it will use one Session per instance.

In this simple implementation: - You provide the configured session if you want to, or a basic session is created. - All kwargs received by “send” are sent to session.request directly

Keyword Arguments:
  • session (requests.Session) – Request session to use instead of the default one.

  • session_owner (bool) – Decide if the session provided by user is owned by this transport. Default to True.

  • use_env_settings (bool) – Uses proxy settings from environment. Defaults to True.

Example:

Synchronous transport with Requests.
from azure.core.pipeline.transport import RequestsTransport

with Pipeline(transport=RequestsTransport(), policies=policies) as pipeline:
    response = pipeline.run(request)
close()[source]

Close the session if it is not externally owned.

open()[source]

Assign new session if one does not already exist.

send(request: HttpRequest, *, proxies: MutableMapping[str, str] | None = None, **kwargs) HttpResponse[source]
send(request: RestHttpRequest, *, proxies: MutableMapping[str, str] | None = None, **kwargs) RestHttpResponse

Send request object according to configuration.

Parameters:

request (HttpRequest) – The request object to be sent.

Returns:

An HTTPResponse object.

Return type:

HttpResponse

Keyword Arguments:

proxies (MutableMapping) – will define the proxy to use. Proxy is a dict (protocol, url)

sleep(duration: float) None

Sleep for the specified duration.

You should always ask the transport to sleep, and not call directly the stdlib. This is mostly important in async, as the transport may not use asyncio but other implementations like trio and they have their own way to sleep, but to keep design consistent, it’s cleaner to always ask the transport to sleep and let the transport implementor decide how to do it.

Parameters:

duration (float) – The number of seconds to sleep.

class azure.core.pipeline.transport.RequestsTransportResponse(request, requests_response, block_size=None)[source]

Streaming of data from the response.

body()

Return the whole body as bytes in memory.

Sync implementer should load the body in memory if they can. Async implementer should rely on async load_body to have been called first.

Return type:

bytes

Returns:

The whole body as bytes in memory.

parts() Iterator[HttpResponse]

Assuming the content-type is multipart/mixed, will return the parts as an iterator.

Return type:

iterator[HttpResponse]

Returns:

The iterator of HttpResponse if request was multipart/mixed

Raises:

ValueError – If the content is not multipart/mixed

raise_for_status() None

Raises an HttpResponseError if the response has an error status code. If response is good, does nothing.

stream_download(pipeline: PipelineType, **kwargs) Iterator[bytes][source]

Generator for streaming request body data.

Parameters:

pipeline (Pipeline) – The pipeline object

Return type:

iterator[bytes]

Returns:

The stream of data

text(encoding: str | None = None) str

Return the whole body as a string.

If encoding is not provided, mostly rely on requests auto-detection, except for BOM, that requests ignores. If we see a UTF8 BOM, we assumes UTF8 unlike requests.

Parameters:

encoding (str) – The encoding to apply.

Return type:

str

Returns:

The body as text.

class azure.core.pipeline.transport.TrioRequestsTransport(**kwargs)[source]

Identical implementation as the synchronous RequestsTransport wrapped in a class with asynchronous methods. Uses the third party trio event loop.

Example:

Asynchronous transport with trio.
    from azure.core.pipeline.transport import TrioRequestsTransport

    async with AsyncPipeline(TrioRequestsTransport(), policies=policies) as pipeline:
        return await pipeline.run(request)
close()

Close the session if it is not externally owned.

open()

Assign new session if one does not already exist.

async send(request: HttpRequest, *, proxies: MutableMapping[str, str] | None = None, **kwargs: Any) AsyncHttpResponse[source]
async send(request: RestHttpRequest, *, proxies: MutableMapping[str, str] | None = None, **kwargs: Any) RestAsyncHttpResponse

Send the request using this HTTP sender.

Parameters:

request (HttpRequest) – The HttpRequest

Returns:

The AsyncHttpResponse

Return type:

AsyncHttpResponse

Keyword Arguments:

proxies (MutableMapping) – will define the proxy to use. Proxy is a dict (protocol, url)

async sleep(duration)[source]

Sleep for the specified duration.

You should always ask the transport to sleep, and not call directly the stdlib. This is mostly important in async, as the transport may not use asyncio but other implementations like trio and they have their own way to sleep, but to keep design consistent, it’s cleaner to always ask the transport to sleep and let the transport implementor decide how to do it.

Parameters:

duration (float) – The number of seconds to sleep.

class azure.core.pipeline.transport.TrioRequestsTransportResponse(request, requests_response, block_size=None)[source]

Asynchronous streaming of data from the response.

body()

Return the whole body as bytes in memory.

Sync implementer should load the body in memory if they can. Async implementer should rely on async load_body to have been called first.

Return type:

bytes

Returns:

The whole body as bytes in memory.

parts() AsyncIterator[AsyncHttpResponse]

Assuming the content-type is multipart/mixed, will return the parts as an async iterator.

Returns:

An async iterator of the parts

Return type:

AsyncIterator

Raises:

ValueError – If the content is not multipart/mixed

raise_for_status() None

Raises an HttpResponseError if the response has an error status code. If response is good, does nothing.

stream_download(pipeline, **kwargs) AsyncIterator[bytes][source]

Generator for streaming response data.

Parameters:

pipeline (AsyncPipeline) – The pipeline object

Return type:

AsyncIterator[bytes]

Returns:

An async iterator of bytes chunks

text(encoding: str | None = None) str

Return the whole body as a string.

If encoding is not provided, mostly rely on requests auto-detection, except for BOM, that requests ignores. If we see a UTF8 BOM, we assumes UTF8 unlike requests.

Parameters:

encoding (str) – The encoding to apply.

Return type:

str

Returns:

The body as text.