azure.core.pipeline.policies

class azure.core.pipeline.policies.AsyncBearerTokenCredentialPolicy(credential: AsyncTokenCredential, *scopes: str, **kwargs: Any)[source]

Adds a bearer token Authorization header to requests.

Parameters:
  • credential (TokenCredential) – The credential.

  • scopes (str) – Lets you specify the type of access needed.

Keyword Arguments:

enable_cae (bool) – Indicates whether to enable Continuous Access Evaluation (CAE) on all requested tokens. Defaults to False.

async authorize_request(request: PipelineRequest[HTTPRequestType], *scopes: str, **kwargs: Any) None[source]

Acquire a token from the credential and authorize the request with it.

Keyword arguments are passed to the credential’s get_token method. The token will be cached and used to authorize future requests.

Parameters:
  • request (PipelineRequest) – the request

  • scopes (str) – required scopes of authentication

async on_challenge(request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, AsyncHTTPResponseType]) bool[source]

Authorize request according to an authentication challenge

This method is called when the resource provider responds 401 with a WWW-Authenticate header.

Parameters:
Returns:

a bool indicating whether the policy should send the request

Return type:

bool

on_exception(request: PipelineRequest[HTTPRequestType]) None[source]

Executed when an exception is raised while executing the next policy.

This method is executed inside the exception handler.

Parameters:

request (PipelineRequest) – The Pipeline request object

async on_request(request: PipelineRequest[HTTPRequestType]) None[source]

Adds a bearer token Authorization header to request and sends request to next policy.

Parameters:

request (PipelineRequest) – The pipeline request object to be modified.

Raises:

ServiceRequestError

on_response(request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, AsyncHTTPResponseType]) Awaitable[None] | None[source]

Executed after the request comes back from the next policy.

Parameters:
async send(request: PipelineRequest[HTTPRequestType]) PipelineResponse[HTTPRequestType, AsyncHTTPResponseType][source]

Authorize request with a bearer token and send it to the next policy

Parameters:

request (PipelineRequest) – The pipeline request object

Returns:

The pipeline response object

Return type:

PipelineResponse

next: AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType]

Pointer to the next policy or a transport (wrapped as a policy). Will be set at pipeline creation.

class azure.core.pipeline.policies.AsyncHTTPPolicy[source]

An async HTTP policy ABC.

Use with an asynchronous pipeline.

abstract async send(request: PipelineRequest[HTTPRequestType]) PipelineResponse[HTTPRequestType, AsyncHTTPResponseType][source]

Abstract send method for a asynchronous pipeline. Mutates the request.

Context content is dependent on the HttpTransport.

Parameters:

request (PipelineRequest) – The pipeline request object.

Returns:

The pipeline response object.

Return type:

PipelineResponse

next: AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType]

Pointer to the next policy or a transport (wrapped as a policy). Will be set at pipeline creation.

class azure.core.pipeline.policies.AsyncRedirectPolicy(**kwargs: Any)[source]

An async redirect policy.

An async redirect policy in the pipeline can be configured directly or per operation.

Keyword Arguments:
  • permit_redirects (bool) – Whether the client allows redirects. Defaults to True.

  • redirect_max (int) – The maximum allowed redirects. Defaults to 30.

Example:

Configuring an async redirect policy.
from azure.core.pipeline.policies import AsyncRedirectPolicy

redirect_policy = AsyncRedirectPolicy()

# Client allows redirects. Defaults to True.
redirect_policy.allow = True

# The maximum allowed redirects. The default value is 30
redirect_policy.max_redirects = 10

# Alternatively you can disable redirects entirely
redirect_policy = AsyncRedirectPolicy.no_redirects()

# It can also be overridden per operation.
async with AsyncPipelineClient[HttpRequest, AsyncHttpResponse](base_url=url, policies=[redirect_policy]) as client:
    response = await client._pipeline.run(request, permit_redirects=True, redirect_max=5)

configure_redirects(options: Dict[str, Any]) Dict[str, Any]

Configures the redirect settings.

Parameters:

options (dict) – Keyword arguments from context.

Returns:

A dict containing redirect settings and a history of redirects.

Return type:

dict

get_redirect_location(response: PipelineResponse[Any, AllHttpResponseType]) str | None | Literal[False]

Checks for redirect status code and gets redirect location.

Parameters:

response (PipelineResponse) – The PipelineResponse object

Returns:

Truthy redirect location string if we got a redirect status code and valid location. None if redirect status and no location. False if not a redirect status code.

Return type:

str or bool or None

increment(settings: Dict[str, Any], response: PipelineResponse[Any, AllHttpResponseType], redirect_location: str) bool

Increment the redirect attempts for this request.

Parameters:
  • settings (dict) – The redirect settings

  • response (PipelineResponse) – A pipeline response object.

  • redirect_location (str) – The redirected endpoint.

Returns:

Whether further redirect attempts are remaining. False if exhausted; True if more redirect attempts available.

Return type:

bool

classmethod no_redirects() ClsRedirectPolicy

Disable redirects.

Returns:

A redirect policy with redirects disabled.

Return type:

RedirectPolicy or AsyncRedirectPolicy

async send(request: PipelineRequest[HTTPRequestType]) PipelineResponse[HTTPRequestType, AsyncHTTPResponseType][source]

Sends the PipelineRequest object to the next policy. Uses redirect settings to send the request to redirect endpoint if necessary.

Parameters:

request (PipelineRequest) – The PipelineRequest object

Returns:

Returns the PipelineResponse or raises error if maximum redirects exceeded.

Return type:

PipelineResponse

Raises:

~azure.core.exceptions.TooManyRedirectsError if maximum redirects exceeded.

REDIRECT_HEADERS_BLACKLIST = frozenset({'Authorization'})
REDIRECT_STATUSES = frozenset({300, 301, 302, 303, 307, 308})
next: AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType]

Pointer to the next policy or a transport (wrapped as a policy). Will be set at pipeline creation.

class azure.core.pipeline.policies.AsyncRetryPolicy(**kwargs: Any)[source]

Async flavor of the retry policy.

The async retry policy in the pipeline can be configured directly, or tweaked on a per-call basis.

Keyword Arguments:
  • retry_total (int) – Total number of retries to allow. Takes precedence over other counts. Default value is 10.

  • retry_connect (int) – How many connection-related errors to retry on. These are errors raised before the request is sent to the remote server, which we assume has not triggered the server to process the request. Default value is 3.

  • retry_read (int) – How many times to retry on read errors. These errors are raised after the request was sent to the server, so the request may have side-effects. Default value is 3.

  • retry_status (int) – How many times to retry on bad status codes. Default value is 3.

  • retry_backoff_factor (float) – A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a second try without a delay). Retry policy will sleep for: {backoff factor} * (2 ** ({number of total retries} - 1)) seconds. If the backoff_factor is 0.1, then the retry will sleep for [0.0s, 0.2s, 0.4s, …] between retries. The default value is 0.8.

  • retry_backoff_max (int) – The maximum back off time. Default value is 120 seconds (2 minutes).

Example:

Configuring an async retry policy.
from azure.core.pipeline.policies import AsyncRetryPolicy

retry_policy = AsyncRetryPolicy()

# Total number of retries to allow. Takes precedence over other counts.
# Default value is 10.
retry_policy.total_retries = 5

# How many connection-related errors to retry on.
# These are errors raised before the request is sent to the remote server,
# which we assume has not triggered the server to process the request. Default value is 3
retry_policy.connect_retries = 2

# How many times to retry on read errors.
# These errors are raised after the request was sent to the server, so the
# request may have side-effects. Default value is 3.
retry_policy.read_retries = 4

# How many times to retry on bad status codes. Default value is 3.
retry_policy.status_retries = 3

# A backoff factor to apply between attempts after the second try
# (most errors are resolved immediately by a second try without a delay).
# Retry policy will sleep for:
#    {backoff factor} * (2 ** ({number of total retries} - 1))
# seconds. If the backoff_factor is 0.1, then the retry will sleep
# for [0.0s, 0.2s, 0.4s, ...] between retries.
# The default value is 0.8.
retry_policy.backoff_factor = 0.5

# The maximum back off time. Default value is 120 seconds (2 minutes).
retry_policy.backoff_max = 120

# Alternatively you can disable redirects entirely
retry_policy = AsyncRetryPolicy.no_retries()

# All of these settings can also be configured per operation.
policies.append(retry_policy)
async with AsyncPipelineClient[HttpRequest, AsyncHttpResponse](base_url=url, policies=policies) as client:
    response = await client._pipeline.run(
        request,
        retry_total=10,
        retry_connect=1,
        retry_read=1,
        retry_status=5,
        retry_backoff_factor=0.5,
        retry_backoff_max=60,
        retry_on_methods=["GET"],
    )
configure_retries(options: Dict[str, Any]) Dict[str, Any]

Configures the retry settings.

Parameters:

options (dict) – keyword arguments from context.

Returns:

A dict containing settings and history for retries.

Return type:

dict

get_backoff_time(settings: Dict[str, Any]) float

Returns the current backoff time.

Parameters:

settings (dict) – The retry settings.

Returns:

The current backoff value.

Return type:

float

get_retry_after(response: PipelineResponse[Any, AllHttpResponseType]) float | None

Get the value of Retry-After in seconds.

Parameters:

response (PipelineResponse) – The PipelineResponse object

Returns:

Value of Retry-After in seconds.

Return type:

float or None

increment(settings: Dict[str, Any], response: PipelineRequest[HTTPRequestType] | PipelineResponse[HTTPRequestType, AllHttpResponseType] | None = None, error: Exception | None = None) bool

Increment the retry counters.

Parameters:
  • settings (dict) – The retry settings.

  • response (PipelineResponse) – A pipeline response object.

  • error (AzureError) – An error encountered during the request, or None if the response was received successfully.

Returns:

Whether any retry attempt is available True if more retry attempts available, False otherwise

Return type:

bool

is_exhausted(settings: Dict[str, Any]) bool

Checks if any retries left.

Parameters:

settings (dict) – the retry settings

Returns:

False if have more retries. True if retries exhausted.

Return type:

bool

is_retry(settings: Dict[str, Any], response: PipelineResponse[HTTPRequestType, AllHttpResponseType]) bool

Checks if method/status code is retryable.

Based on allowlists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the returned status code is on the list of status codes to be retried upon on the presence of the aforementioned header.

The behavior is: - If status_code < 400: don’t retry - Else if Retry-After present: retry - Else: retry based on the safe status code list ([408, 429, 500, 502, 503, 504])

Parameters:
  • settings (dict) – The retry settings.

  • response (PipelineResponse) – The PipelineResponse object

Returns:

True if method/status code is retryable. False if not retryable.

Return type:

bool

classmethod no_retries() ClsRetryPolicy

Disable retries.

Returns:

A retry policy with retries disabled.

Return type:

RetryPolicy or AsyncRetryPolicy

parse_retry_after(retry_after: str) float

Helper to parse Retry-After and get value in seconds.

Parameters:

retry_after (str) – Retry-After header

Return type:

float

Returns:

Value of Retry-After in seconds.

async send(request: PipelineRequest[HTTPRequestType]) PipelineResponse[HTTPRequestType, AsyncHTTPResponseType][source]

Uses the configured retry policy to send the request to the next policy in the pipeline.

Parameters:

request (PipelineRequest) – The PipelineRequest object

Returns:

Returns the PipelineResponse or raises error if maximum retries exceeded.

Return type:

PipelineResponse

Raise:

~azure.core.exceptions.AzureError if maximum retries exceeded.

Raise:

~azure.core.exceptions.ClientAuthenticationError if authentication fails

async sleep(settings: Dict[str, Any], transport: AsyncHttpTransport[HTTPRequestType, AsyncHTTPResponseType], response: PipelineResponse[HTTPRequestType, AsyncHTTPResponseType] | None = None) None[source]

Sleep between retry attempts.

This method will respect a server’s Retry-After response header and sleep the duration of the time requested. If that is not present, it will use an exponential backoff. By default, the backoff factor is 0 and this method will return immediately.

Parameters:
update_context(context: PipelineContext, retry_settings: Dict[str, Any]) None

Updates retry history in pipeline context.

Parameters:
  • context (PipelineContext) – The pipeline context.

  • retry_settings (dict) – The retry settings.

BACKOFF_MAX = 120

Maximum backoff time.

next: AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType]

Pointer to the next policy or a transport (wrapped as a policy). Will be set at pipeline creation.

class azure.core.pipeline.policies.AzureKeyCredentialPolicy(credential: AzureKeyCredential, name: str, *, prefix: str | None = None, **kwargs: Any)[source]

Adds a key header for the provided credential.

Parameters:
  • credential (AzureKeyCredential) – The credential used to authenticate requests.

  • name (str) – The name of the key header used for the credential.

Keyword Arguments:

prefix (str) – The name of the prefix for the header value if any.

Raises:

ValueError or TypeError

on_exception(request: PipelineRequest[HTTPRequestType]) None

Is executed if an exception is raised while executing the next policy.

This method is executed inside the exception handler.

Parameters:

request (PipelineRequest) – The Pipeline request object

on_request(request: PipelineRequest[HTTPRequestType]) None[source]

Is executed before sending the request from next policy.

Parameters:

request (PipelineRequest) – Request to be modified before sent from next policy.

on_response(request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType]) None | Awaitable[None]

Is executed after the request comes back from the policy.

Parameters:
class azure.core.pipeline.policies.AzureSasCredentialPolicy(credential: AzureSasCredential, **kwargs: Any)[source]

Adds a shared access signature to query for the provided credential.

Parameters:

credential (AzureSasCredential) – The credential used to authenticate requests.

Raises:

ValueError or TypeError

on_exception(request: PipelineRequest[HTTPRequestType]) None

Is executed if an exception is raised while executing the next policy.

This method is executed inside the exception handler.

Parameters:

request (PipelineRequest) – The Pipeline request object

on_request(request: PipelineRequest[HTTPRequestType]) None[source]

Is executed before sending the request from next policy.

Parameters:

request (PipelineRequest) – Request to be modified before sent from next policy.

on_response(request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType]) None | Awaitable[None]

Is executed after the request comes back from the policy.

Parameters:
class azure.core.pipeline.policies.BearerTokenCredentialPolicy(credential: TokenCredential, *scopes: str, **kwargs: Any)[source]

Adds a bearer token Authorization header to requests.

Parameters:
  • credential (TokenCredential) – The credential.

  • scopes (str) – Lets you specify the type of access needed.

Keyword Arguments:

enable_cae (bool) – Indicates whether to enable Continuous Access Evaluation (CAE) on all requested tokens. Defaults to False.

Raises:

ServiceRequestError

authorize_request(request: PipelineRequest[HTTPRequestType], *scopes: str, **kwargs: Any) None[source]

Acquire a token from the credential and authorize the request with it.

Keyword arguments are passed to the credential’s get_token method. The token will be cached and used to authorize future requests.

Parameters:
  • request (PipelineRequest) – the request

  • scopes (str) – required scopes of authentication

on_challenge(request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType]) bool[source]

Authorize request according to an authentication challenge

This method is called when the resource provider responds 401 with a WWW-Authenticate header.

Parameters:
Returns:

a bool indicating whether the policy should send the request

Return type:

bool

on_exception(request: PipelineRequest[HTTPRequestType]) None[source]

Executed when an exception is raised while executing the next policy.

This method is executed inside the exception handler.

Parameters:

request (PipelineRequest) – The Pipeline request object

on_request(request: PipelineRequest[HTTPRequestType]) None[source]

Called before the policy sends a request.

The base implementation authorizes the request with a bearer token.

Parameters:

request (PipelineRequest) – the request

on_response(request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType]) None[source]

Executed after the request comes back from the next policy.

Parameters:
send(request: PipelineRequest[HTTPRequestType]) PipelineResponse[HTTPRequestType, HTTPResponseType][source]

Authorize request with a bearer token and send it to the next policy

Parameters:

request (PipelineRequest) – The pipeline request object

Returns:

The pipeline response object

Return type:

PipelineResponse

next: HTTPPolicy[HTTPRequestType, HTTPResponseType]

Pointer to the next policy or a transport (wrapped as a policy). Will be set at pipeline creation.

class azure.core.pipeline.policies.ContentDecodePolicy(response_encoding: str | None = None, **kwargs: Any)[source]

Policy for decoding unstreamed response content.

Parameters:

response_encoding (str) – The encoding to use if known for this service (will disable auto-detection)

classmethod deserialize_from_http_generics(response: _HttpResponseBase | _HttpResponseBase, encoding: str | None = None) Any[source]

Deserialize from HTTP response.

Headers will tested for “content-type”

Parameters:
  • response (any) – The HTTP response

  • encoding (str) – The encoding to use if known for this service (will disable auto-detection)

Raises:

DecodeError – If deserialization fails

Returns:

A dict (JSON), XML tree or str, depending of the mime_type

Return type:

dict[str, Any] or xml.etree.ElementTree.Element or str

classmethod deserialize_from_text(data: AnyStr | IO | None, mime_type: str | None = None, response: _HttpResponseBase | _HttpResponseBase | None = None) Any[source]

Decode response data according to content-type.

Accept a stream of data as well, but will be load at once in memory for now. If no content-type, will return the string version (not bytes, not stream)

Parameters:
  • data (str or bytes or file-like object) – The data to deserialize.

  • response (any) – The HTTP response.

  • mime_type (str) – The mime type. As mime type, charset is not expected.

  • response – If passed, exception will be annotated with that response

Raises:

DecodeError – If deserialization fails

Returns:

A dict (JSON), XML tree or str, depending of the mime_type

Return type:

dict[str, Any] or xml.etree.ElementTree.Element or str

on_exception(request: PipelineRequest[HTTPRequestType]) None

Is executed if an exception is raised while executing the next policy.

This method is executed inside the exception handler.

Parameters:

request (PipelineRequest) – The Pipeline request object

on_request(request: PipelineRequest[HttpRequest | HttpRequest]) None[source]

Is executed before sending the request from next policy.

Parameters:

request (PipelineRequest) – Request to be modified before sent from next policy.

on_response(request: PipelineRequest[HttpRequest | HttpRequest], response: PipelineResponse[HttpRequest | HttpRequest, _HttpResponseBase | _HttpResponseBase]) None[source]

Extract data from the body of a REST response object. This will load the entire payload in memory. Will follow Content-Type to parse. We assume everything is UTF8 (BOM acceptable).

Parameters:
Raises:
CONTEXT_NAME = 'deserialized_data'
JSON_REGEXP = re.compile('^(application|text)/([0-9a-z+.-]+\\+)?json$')
class azure.core.pipeline.policies.CustomHookPolicy(**kwargs: Any)[source]

A simple policy that enable the given callback with the response.

Keyword Arguments:
  • raw_request_hook (callback) – Callback function. Will be invoked on request.

  • raw_response_hook (callback) – Callback function. Will be invoked on response.

on_exception(request: PipelineRequest[HTTPRequestType]) None

Is executed if an exception is raised while executing the next policy.

This method is executed inside the exception handler.

Parameters:

request (PipelineRequest) – The Pipeline request object

on_request(request: PipelineRequest[HTTPRequestType]) None[source]

This is executed before sending the request to the next policy.

Parameters:

request (PipelineRequest) – The PipelineRequest object.

on_response(request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType]) None[source]

This is executed after the request comes back from the policy.

Parameters:
class azure.core.pipeline.policies.DistributedTracingPolicy(**kwargs: Any)[source]

The policy to create spans for Azure calls.

Keyword Arguments:
  • network_span_namer – A callable to customize the span name

  • tracing_attributes – Attributes to set on all created spans

end_span(request: PipelineRequest[HTTPRequestType], response: HTTPResponseType | None = None, exc_info: Tuple[Type[BaseException], BaseException, TracebackType] | Tuple[None, None, None] | None = None) None[source]

Ends the span that is tracing the network and updates its status.

Parameters:
  • request (PipelineRequest) – The PipelineRequest object

  • response (HTTPResponse or HttpResponse) – The HttpResponse object

  • exc_info (tuple) – The exception information

on_exception(request: PipelineRequest[HTTPRequestType]) None[source]

Is executed if an exception is raised while executing the next policy.

This method is executed inside the exception handler.

Parameters:

request (PipelineRequest) – The Pipeline request object

on_request(request: PipelineRequest[HTTPRequestType]) None[source]

Is executed before sending the request from next policy.

Parameters:

request (PipelineRequest) – Request to be modified before sent from next policy.

on_response(request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType]) None[source]

Is executed after the request comes back from the policy.

Parameters:
TRACING_CONTEXT = 'TRACING_CONTEXT'
class azure.core.pipeline.policies.HTTPPolicy[source]

An HTTP policy ABC.

Use with a synchronous pipeline.

abstract send(request: PipelineRequest[HTTPRequestType]) PipelineResponse[HTTPRequestType, HTTPResponseType][source]

Abstract send method for a synchronous pipeline. Mutates the request.

Context content is dependent on the HttpTransport.

Parameters:

request (PipelineRequest) – The pipeline request object

Returns:

The pipeline response object.

Return type:

PipelineResponse

next: HTTPPolicy[HTTPRequestType, HTTPResponseType]

Pointer to the next policy or a transport (wrapped as a policy). Will be set at pipeline creation.

class azure.core.pipeline.policies.HeadersPolicy(base_headers: Dict[str, str] | None = None, **kwargs: Any)[source]

A simple policy that sends the given headers with the request.

This will overwrite any headers already defined in the request. Headers can be configured up front, where any custom headers will be applied to all outgoing operations, and additional headers can also be added dynamically per operation.

Parameters:

base_headers (dict) – Headers to send with the request.

Example:

Configuring a headers policy.
from azure.core.pipeline.policies import HeadersPolicy

headers_policy = HeadersPolicy()
headers_policy.add_header("CustomValue", "Foo")

# Or headers can be added per operation. These headers will supplement existing headers
# or those defined in the config headers policy. They will also overwrite existing
# identical headers.
policies.append(headers_policy)
client: PipelineClient[HttpRequest, HttpResponse] = PipelineClient(base_url=url, policies=policies)
request = HttpRequest("GET", url)
pipeline_response = client._pipeline.run(request, headers={"CustomValue": "Bar"})
add_header(key: str, value: str) None[source]

Add a header to the configuration to be applied to all requests.

Parameters:
  • key (str) – The header.

  • value (str) – The header’s value.

on_exception(request: PipelineRequest[HTTPRequestType]) None

Is executed if an exception is raised while executing the next policy.

This method is executed inside the exception handler.

Parameters:

request (PipelineRequest) – The Pipeline request object

on_request(request: PipelineRequest[HttpRequest | HttpRequest]) None[source]

Updates with the given headers before sending the request to the next policy.

Parameters:

request (PipelineRequest) – The PipelineRequest object

on_response(request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType]) None | Awaitable[None]

Is executed after the request comes back from the policy.

Parameters:
property headers: Dict[str, str]

The current headers collection.

Return type:

dict[str, str]

Returns:

The current headers collection.

class azure.core.pipeline.policies.HttpLoggingPolicy(logger: Logger | None = None, **kwargs: Any)[source]

The Pipeline policy that handles logging of HTTP requests and responses.

Parameters:

logger (logging.Logger) – The logger to use for logging. Default to azure.core.pipeline.policies.http_logging_policy.

on_exception(request: PipelineRequest[HTTPRequestType]) None

Is executed if an exception is raised while executing the next policy.

This method is executed inside the exception handler.

Parameters:

request (PipelineRequest) – The Pipeline request object

on_request(request: PipelineRequest[HttpRequest | HttpRequest]) None[source]

Logs HTTP method, url and headers. :param request: The PipelineRequest object. :type request: ~azure.core.pipeline.PipelineRequest

on_response(request: PipelineRequest[HttpRequest | HttpRequest], response: PipelineResponse[HttpRequest | HttpRequest, _HttpResponseBase | _HttpResponseBase]) None[source]

Is executed after the request comes back from the policy.

Parameters:
DEFAULT_HEADERS_ALLOWLIST: Set[str] = {'Accept', 'Cache-Control', 'Connection', 'Content-Length', 'Content-Type', 'Date', 'ETag', 'Expires', 'If-Match', 'If-Modified-Since', 'If-None-Match', 'If-Unmodified-Since', 'Last-Modified', 'Pragma', 'Request-Id', 'Retry-After', 'Server', 'Transfer-Encoding', 'User-Agent', 'WWW-Authenticate', 'traceparent', 'x-ms-client-request-id', 'x-ms-error-code', 'x-ms-request-id', 'x-ms-return-client-request-id'}
MULTI_RECORD_LOG: str = 'AZURE_SDK_LOGGING_MULTIRECORD'
REDACTED_PLACEHOLDER: str = 'REDACTED'
class azure.core.pipeline.policies.NetworkTraceLoggingPolicy(logging_enable: bool = False, **kwargs: Any)[source]

The logging policy in the pipeline is used to output HTTP network trace to the configured logger.

This accepts both global configuration, and per-request level with “enable_http_logger”

Parameters:

logging_enable (bool) – Use to enable per operation. Defaults to False.

Example:

Configuring a network trace logging policy.
from azure.core.pipeline.policies import NetworkTraceLoggingPolicy
import sys
import logging

# Create a logger for the 'azure' SDK
logger = logging.getLogger("azure")
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

# Configure a file output
file_handler = logging.FileHandler(filename)
logger.addHandler(file_handler)

# Enable network trace logging. This will be logged at DEBUG level.
# By default, logging is disabled.
logging_policy = NetworkTraceLoggingPolicy()
logging_policy.enable_http_logger = True

# The logger can also be enabled per operation.
policies.append(logging_policy)
client: PipelineClient[HttpRequest, HttpResponse] = PipelineClient(base_url=url, policies=policies)
request = HttpRequest("GET", url)
pipeline_response = client._pipeline.run(request, logging_enable=True)

on_exception(request: PipelineRequest[HTTPRequestType]) None

Is executed if an exception is raised while executing the next policy.

This method is executed inside the exception handler.

Parameters:

request (PipelineRequest) – The Pipeline request object

on_request(request: PipelineRequest[HttpRequest | HttpRequest]) None[source]

Logs HTTP request to the DEBUG logger.

Parameters:

request (PipelineRequest) – The PipelineRequest object.

on_response(request: PipelineRequest[HttpRequest | HttpRequest], response: PipelineResponse[HttpRequest | HttpRequest, _HttpResponseBase | _HttpResponseBase]) None[source]

Logs HTTP response to the DEBUG logger.

Parameters:
class azure.core.pipeline.policies.ProxyPolicy(proxies: MutableMapping[str, str] | None = None, **kwargs: Any)[source]

A proxy policy.

Dictionary mapping protocol or protocol and host to the URL of the proxy to be used on each Request.

Parameters:

proxies (MutableMapping) – Maps protocol or protocol and hostname to the URL of the proxy.

Example:

Configuring a proxy policy.
from azure.core.pipeline.policies import ProxyPolicy

proxy_policy = ProxyPolicy()

# Example
proxy_policy.proxies = {"http": "http://10.10.1.10:3148"}

# Use basic auth
proxy_policy.proxies = {"https": "http://user:password@10.10.1.10:1180/"}

# You can also configure proxies by setting the environment variables
# HTTP_PROXY and HTTPS_PROXY.
on_exception(request: PipelineRequest[HTTPRequestType]) None

Is executed if an exception is raised while executing the next policy.

This method is executed inside the exception handler.

Parameters:

request (PipelineRequest) – The Pipeline request object

on_request(request: PipelineRequest[HttpRequest | HttpRequest]) None[source]

Is executed before sending the request from next policy.

Parameters:

request (PipelineRequest) – Request to be modified before sent from next policy.

on_response(request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType]) None | Awaitable[None]

Is executed after the request comes back from the policy.

Parameters:
class azure.core.pipeline.policies.RedirectPolicy(**kwargs: Any)[source]

A redirect policy.

A redirect policy in the pipeline can be configured directly or per operation.

Keyword Arguments:
  • permit_redirects (bool) – Whether the client allows redirects. Defaults to True.

  • redirect_max (int) – The maximum allowed redirects. Defaults to 30.

Example:

Configuring a redirect policy.
from azure.core.rest import HttpRequest
from azure.core.pipeline.policies import RedirectPolicy

redirect_policy = RedirectPolicy()

# Client allows redirects. Defaults to True.
redirect_policy.allow = True

# The maximum allowed redirects. The default value is 30
redirect_policy.max_redirects = 10

# Alternatively you can disable redirects entirely
redirect_policy = RedirectPolicy.no_redirects()

# It can also be overridden per operation.
client: PipelineClient[HttpRequest, HttpResponse] = PipelineClient(base_url=url, policies=[redirect_policy])
request = HttpRequest("GET", url)
pipeline_response = client._pipeline.run(request, permit_redirects=True, redirect_max=5)
configure_redirects(options: Dict[str, Any]) Dict[str, Any]

Configures the redirect settings.

Parameters:

options (dict) – Keyword arguments from context.

Returns:

A dict containing redirect settings and a history of redirects.

Return type:

dict

get_redirect_location(response: PipelineResponse[Any, AllHttpResponseType]) str | None | Literal[False]

Checks for redirect status code and gets redirect location.

Parameters:

response (PipelineResponse) – The PipelineResponse object

Returns:

Truthy redirect location string if we got a redirect status code and valid location. None if redirect status and no location. False if not a redirect status code.

Return type:

str or bool or None

increment(settings: Dict[str, Any], response: PipelineResponse[Any, AllHttpResponseType], redirect_location: str) bool

Increment the redirect attempts for this request.

Parameters:
  • settings (dict) – The redirect settings

  • response (PipelineResponse) – A pipeline response object.

  • redirect_location (str) – The redirected endpoint.

Returns:

Whether further redirect attempts are remaining. False if exhausted; True if more redirect attempts available.

Return type:

bool

classmethod no_redirects() ClsRedirectPolicy

Disable redirects.

Returns:

A redirect policy with redirects disabled.

Return type:

RedirectPolicy or AsyncRedirectPolicy

send(request: PipelineRequest[HTTPRequestType]) PipelineResponse[HTTPRequestType, HTTPResponseType][source]

Sends the PipelineRequest object to the next policy. Uses redirect settings to send request to redirect endpoint if necessary.

Parameters:

request (PipelineRequest) – The PipelineRequest object

Returns:

Returns the PipelineResponse or raises error if maximum redirects exceeded.

Return type:

PipelineResponse

Raises:

~azure.core.exceptions.TooManyRedirectsError if maximum redirects exceeded.

REDIRECT_HEADERS_BLACKLIST = frozenset({'Authorization'})
REDIRECT_STATUSES = frozenset({300, 301, 302, 303, 307, 308})
next: HTTPPolicy[HTTPRequestType, HTTPResponseType]

Pointer to the next policy or a transport (wrapped as a policy). Will be set at pipeline creation.

class azure.core.pipeline.policies.RequestHistory(http_request: HTTPRequestType, http_response: HTTPResponseType | None = None, error: Exception | None = None, context: Dict[str, Any] | None = None)[source]

A container for an attempted request and the applicable response.

This is used to document requests/responses that resulted in redirected/retried requests.

Parameters:
  • http_request (HttpRequest) – The request.

  • http_response (HttpResponse) – The HTTP response.

  • error (Exception) – An error encountered during the request, or None if the response was received successfully.

  • context (dict) – The pipeline context.

class azure.core.pipeline.policies.RequestIdPolicy(*, request_id: str | ~typing.Any = <class 'azure.core.pipeline.policies._universal._Unset'>, auto_request_id: bool = True, request_id_header_name: str = 'x-ms-client-request-id', **kwargs: ~typing.Any)[source]

A simple policy that sets the given request id in the header.

This will overwrite request id that is already defined in the request. Request id can be configured up front, where the request id will be applied to all outgoing operations, and additional request id can also be set dynamically per operation.

Keyword Arguments:
  • request_id (str) – The request id to be added into header.

  • auto_request_id (bool) – Auto generates a unique request ID per call if true which is by default.

  • request_id_header_name (str) – Header name to use. Default is “x-ms-client-request-id”.

Example:

Configuring a request id policy.
from azure.core.pipeline.policies import HeadersPolicy

request_id_policy = RequestIdPolicy()
request_id_policy.set_request_id("azconfig-test")

# Or headers can be added per operation. These headers will supplement existing headers
# or those defined in the config headers policy. They will also overwrite existing
# identical headers.
policies.append(request_id_policy)
client: PipelineClient[HttpRequest, HttpResponse] = PipelineClient(base_url=url, policies=policies)
request = HttpRequest("GET", url)
pipeline_response = client._pipeline.run(request, request_id="azconfig-test")
on_exception(request: PipelineRequest[HTTPRequestType]) None

Is executed if an exception is raised while executing the next policy.

This method is executed inside the exception handler.

Parameters:

request (PipelineRequest) – The Pipeline request object

on_request(request: PipelineRequest[HttpRequest | HttpRequest]) None[source]

Updates with the given request id before sending the request to the next policy.

Parameters:

request (PipelineRequest) – The PipelineRequest object

on_response(request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType]) None | Awaitable[None]

Is executed after the request comes back from the policy.

Parameters:
set_request_id(value: str) None[source]

Add the request id to the configuration to be applied to all requests.

Parameters:

value (str) – The request id value.

class azure.core.pipeline.policies.RetryMode(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count(sub[, start[, end]]) int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith(suffix[, start[, end]]) bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format(*args, **kwargs) str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping) str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

index(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace(old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith(prefix[, start[, end]]) bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

Exponential = 'exponential'
Fixed = 'fixed'
class azure.core.pipeline.policies.RetryPolicy(**kwargs: Any)[source]

A retry policy.

The retry policy in the pipeline can be configured directly, or tweaked on a per-call basis.

Keyword Arguments:
  • retry_total (int) – Total number of retries to allow. Takes precedence over other counts. Default value is 10.

  • retry_connect (int) – How many connection-related errors to retry on. These are errors raised before the request is sent to the remote server, which we assume has not triggered the server to process the request. Default value is 3.

  • retry_read (int) – How many times to retry on read errors. These errors are raised after the request was sent to the server, so the request may have side-effects. Default value is 3.

  • retry_status (int) – How many times to retry on bad status codes. Default value is 3.

  • retry_backoff_factor (float) – A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a second try without a delay). In fixed mode, retry policy will always sleep for {backoff factor}. In ‘exponential’ mode, retry policy will sleep for: {backoff factor} * (2 ** ({number of total retries} - 1)) seconds. If the backoff_factor is 0.1, then the retry will sleep for [0.0s, 0.2s, 0.4s, …] between retries. The default value is 0.8.

  • retry_backoff_max (int) – The maximum back off time. Default value is 120 seconds (2 minutes).

  • retry_mode (RetryMode) – Fixed or exponential delay between attemps, default is exponential.

  • timeout (int) – Timeout setting for the operation in seconds, default is 604800s (7 days).

Example:

Configuring a retry policy.
from azure.core.pipeline.policies import RetryPolicy

retry_policy = RetryPolicy()

# Total number of retries to allow. Takes precedence over other counts.
# Default value is 10.
retry_policy.total_retries = 5

# How many connection-related errors to retry on.
# These are errors raised before the request is sent to the remote server,
# which we assume has not triggered the server to process the request. Default value is 3
retry_policy.connect_retries = 2

# How many times to retry on read errors.
# These errors are raised after the request was sent to the server, so the
# request may have side-effects. Default value is 3.
retry_policy.read_retries = 4

# How many times to retry on bad status codes. Default value is 3.
retry_policy.status_retries = 3

# A backoff factor to apply between attempts after the second try
# (most errors are resolved immediately by a second try without a delay).
# Retry policy will sleep for:
#    {backoff factor} * (2 ** ({number of total retries} - 1))
# seconds. If the backoff_factor is 0.1, then the retry will sleep
# for [0.0s, 0.2s, 0.4s, ...] between retries.
# The default value is 0.8.
retry_policy.backoff_factor = 0.5

# The maximum back off time. Default value is 120 seconds (2 minutes).
retry_policy.backoff_max = 120

# Alternatively you can disable redirects entirely
retry_policy = RetryPolicy.no_retries()

# All of these settings can also be configured per operation.
policies.append(retry_policy)
client: PipelineClient[HttpRequest, HttpResponse] = PipelineClient(base_url=url, policies=policies)
request = HttpRequest("GET", url)
pipeline_response = client._pipeline.run(
    request,
    retry_total=10,
    retry_connect=1,
    retry_read=1,
    retry_status=5,
    retry_backoff_factor=0.5,
    retry_backoff_max=120,
    retry_on_methods=["GET"],
)
configure_retries(options: Dict[str, Any]) Dict[str, Any]

Configures the retry settings.

Parameters:

options (dict) – keyword arguments from context.

Returns:

A dict containing settings and history for retries.

Return type:

dict

get_backoff_time(settings: Dict[str, Any]) float

Returns the current backoff time.

Parameters:

settings (dict) – The retry settings.

Returns:

The current backoff value.

Return type:

float

get_retry_after(response: PipelineResponse[Any, AllHttpResponseType]) float | None

Get the value of Retry-After in seconds.

Parameters:

response (PipelineResponse) – The PipelineResponse object

Returns:

Value of Retry-After in seconds.

Return type:

float or None

increment(settings: Dict[str, Any], response: PipelineRequest[HTTPRequestType] | PipelineResponse[HTTPRequestType, AllHttpResponseType] | None = None, error: Exception | None = None) bool

Increment the retry counters.

Parameters:
  • settings (dict) – The retry settings.

  • response (PipelineResponse) – A pipeline response object.

  • error (AzureError) – An error encountered during the request, or None if the response was received successfully.

Returns:

Whether any retry attempt is available True if more retry attempts available, False otherwise

Return type:

bool

is_exhausted(settings: Dict[str, Any]) bool

Checks if any retries left.

Parameters:

settings (dict) – the retry settings

Returns:

False if have more retries. True if retries exhausted.

Return type:

bool

is_retry(settings: Dict[str, Any], response: PipelineResponse[HTTPRequestType, AllHttpResponseType]) bool

Checks if method/status code is retryable.

Based on allowlists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the returned status code is on the list of status codes to be retried upon on the presence of the aforementioned header.

The behavior is: - If status_code < 400: don’t retry - Else if Retry-After present: retry - Else: retry based on the safe status code list ([408, 429, 500, 502, 503, 504])

Parameters:
  • settings (dict) – The retry settings.

  • response (PipelineResponse) – The PipelineResponse object

Returns:

True if method/status code is retryable. False if not retryable.

Return type:

bool

classmethod no_retries() ClsRetryPolicy

Disable retries.

Returns:

A retry policy with retries disabled.

Return type:

RetryPolicy or AsyncRetryPolicy

parse_retry_after(retry_after: str) float

Helper to parse Retry-After and get value in seconds.

Parameters:

retry_after (str) – Retry-After header

Return type:

float

Returns:

Value of Retry-After in seconds.

send(request: PipelineRequest[HTTPRequestType]) PipelineResponse[HTTPRequestType, HTTPResponseType][source]

Sends the PipelineRequest object to the next policy. Uses retry settings if necessary.

Parameters:

request (PipelineRequest) – The PipelineRequest object

Returns:

Returns the PipelineResponse or raises error if maximum retries exceeded.

Return type:

PipelineResponse

Raises:

~azure.core.exceptions.AzureError if maximum retries exceeded.

Raises:

~azure.core.exceptions.ClientAuthenticationError if authentication

sleep(settings: Dict[str, Any], transport: HttpTransport[HTTPRequestType, HTTPResponseType], response: PipelineResponse[HTTPRequestType, HTTPResponseType] | None = None) None[source]

Sleep between retry attempts.

This method will respect a server’s Retry-After response header and sleep the duration of the time requested. If that is not present, it will use an exponential backoff. By default, the backoff factor is 0 and this method will return immediately.

Parameters:
update_context(context: PipelineContext, retry_settings: Dict[str, Any]) None

Updates retry history in pipeline context.

Parameters:
  • context (PipelineContext) – The pipeline context.

  • retry_settings (dict) – The retry settings.

BACKOFF_MAX = 120

Maximum backoff time.

next: HTTPPolicy[HTTPRequestType, HTTPResponseType]

Pointer to the next policy or a transport (wrapped as a policy). Will be set at pipeline creation.

class azure.core.pipeline.policies.SansIOHTTPPolicy[source]

Represents a sans I/O policy.

SansIOHTTPPolicy is a base class for policies that only modify or mutate a request based on the HTTP specification, and do not depend on the specifics of any particular transport. SansIOHTTPPolicy subclasses will function in either a Pipeline or an AsyncPipeline, and can act either before the request is done, or after. You can optionally make these methods coroutines (or return awaitable objects) but they will then be tied to AsyncPipeline usage.

on_exception(request: PipelineRequest[HTTPRequestType]) None[source]

Is executed if an exception is raised while executing the next policy.

This method is executed inside the exception handler.

Parameters:

request (PipelineRequest) – The Pipeline request object

on_request(request: PipelineRequest[HTTPRequestType]) None | Awaitable[None][source]

Is executed before sending the request from next policy.

Parameters:

request (PipelineRequest) – Request to be modified before sent from next policy.

on_response(request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType]) None | Awaitable[None][source]

Is executed after the request comes back from the policy.

Parameters:
class azure.core.pipeline.policies.SensitiveHeaderCleanupPolicy(*, blocked_redirect_headers: List[str] | None = None, disable_redirect_cleanup: bool = False, **kwargs: Any)[source]

A simple policy that cleans up sensitive headers

Keyword Arguments:
  • blocked_redirect_headers (list[str]) – The headers to clean up when redirecting to another domain.

  • disable_redirect_cleanup (bool) – Opt out cleaning up sensitive headers when redirecting to another domain.

on_exception(request: PipelineRequest[HTTPRequestType]) None

Is executed if an exception is raised while executing the next policy.

This method is executed inside the exception handler.

Parameters:

request (PipelineRequest) – The Pipeline request object

on_request(request: PipelineRequest[HTTPRequestType]) None[source]

This is executed before sending the request to the next policy.

Parameters:

request (PipelineRequest) – The PipelineRequest object.

on_response(request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType]) None | Awaitable[None]

Is executed after the request comes back from the policy.

Parameters:
DEFAULT_SENSITIVE_HEADERS = {'Authorization', 'x-ms-authorization-auxiliary'}
class azure.core.pipeline.policies.UserAgentPolicy(base_user_agent: str | None = None, **kwargs: Any)[source]

User-Agent Policy. Allows custom values to be added to the User-Agent header.

Parameters:

base_user_agent (str) – Sets the base user agent value.

Keyword Arguments:
  • user_agent_overwrite (bool) – Overwrites User-Agent when True. Defaults to False.

  • user_agent_use_env (bool) – Gets user-agent from environment. Defaults to True.

  • user_agent (str) – If specified, this will be added in front of the user agent string.

  • sdk_moniker (str) – If specified, the user agent string will be azsdk-python-[sdk_moniker] Python/[python_version] ([platform_version])

Example:

Configuring a user agent policy.
from azure.core.pipeline.policies import UserAgentPolicy

user_agent_policy = UserAgentPolicy()

# The user-agent policy allows you to append a custom value to the header.
user_agent_policy.add_user_agent("CustomValue")

# You can also pass in a custom value per operation to append to the end of the user-agent.
# This can be used together with the policy configuration to append multiple values.
policies = [
    redirect_policy,
    user_agent_policy,
]
client: PipelineClient[HttpRequest, HttpResponse] = PipelineClient(base_url=url, policies=policies)
request = HttpRequest("GET", url)
pipeline_response = client._pipeline.run(request, user_agent="AnotherValue")
add_user_agent(value: str) None[source]

Add value to current user agent with a space. :param str value: value to add to user agent.

on_exception(request: PipelineRequest[HTTPRequestType]) None

Is executed if an exception is raised while executing the next policy.

This method is executed inside the exception handler.

Parameters:

request (PipelineRequest) – The Pipeline request object

on_request(request: PipelineRequest[HttpRequest | HttpRequest]) None[source]

Modifies the User-Agent header before the request is sent.

Parameters:

request (PipelineRequest) – The PipelineRequest object

on_response(request: PipelineRequest[HTTPRequestType], response: PipelineResponse[HTTPRequestType, HTTPResponseType]) None | Awaitable[None]

Is executed after the request comes back from the policy.

Parameters:
property user_agent: str

The current user agent value.

Returns:

The current user agent value.

Return type:

str