azure.core.pipeline.policies package¶
Module contents¶
-
class
azure.core.pipeline.policies.
HTTPPolicy
[source]¶ Bases:
abc.ABC
,typing.Generic
An HTTP policy ABC.
Use with a synchronous pipeline.
- Parameters
next (HTTPPolicy or HttpTransport) – Use to process the next policy in the pipeline. Set when pipeline is instantiated and all policies chained.
-
abstract
send
(request: azure.core.pipeline.PipelineRequest) → azure.core.pipeline.PipelineResponse[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
-
class
azure.core.pipeline.policies.
SansIOHTTPPolicy
[source]¶ Bases:
typing.Generic
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 no 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: azure.core.pipeline.PipelineRequest) → Union[bool, Awaitable[bool]][source]¶ Is executed if an exception is raised while executing the next policy.
Developer can optionally implement this method to return True if the exception has been handled and should not be forwarded to the caller.
This method is executed inside the exception handler.
- Parameters
request (PipelineRequest) – The Pipeline request object
- Returns
False by default, override with True to stop the exception.
- Return type
Example:
-
on_request
(request: azure.core.pipeline.PipelineRequest) → Union[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: azure.core.pipeline.PipelineRequest, response: azure.core.pipeline.PipelineResponse) → Union[None, Awaitable[None]][source]¶ Is executed after the request comes back from the policy.
- Parameters
request (PipelineRequest) – Request to be modified after returning from the policy.
response (PipelineResponse) – Pipeline response object
-
-
class
azure.core.pipeline.policies.
BearerTokenCredentialPolicy
(credential: TokenCredential, *scopes: str, **kwargs: Mapping[str, Any])[source]¶ Bases:
azure.core.pipeline.policies._authentication._BearerTokenCredentialPolicyBase
,azure.core.pipeline.policies._base.SansIOHTTPPolicy
Adds a bearer token Authorization header to requests.
- Parameters
credential (TokenCredential) – The credential.
scopes (str) – Lets you specify the type of access needed.
- Raises
-
on_request
(request: PipelineRequest) → None[source]¶ Adds a bearer token Authorization header to request and sends request to next policy.
- Parameters
request (PipelineRequest) – The pipeline request object
-
class
azure.core.pipeline.policies.
AzureKeyCredentialPolicy
(credential: AzureKeyCredential, name: str)[source]¶ Bases:
azure.core.pipeline.policies._base.SansIOHTTPPolicy
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.
- Raises
ValueError or TypeError
-
on_request
(request)[source]¶ Is executed before sending the request from next policy.
- Parameters
request (PipelineRequest) – Request to be modified before sent from next policy.
-
class
azure.core.pipeline.policies.
HeadersPolicy
(base_headers: Optional[Dict[str, str]] = None, **kwargs: Any)[source]¶ Bases:
azure.core.pipeline.policies._base.SansIOHTTPPolicy
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:
-
on_request
(request: azure.core.pipeline.PipelineRequest) → None[source]¶ Updates with the given headers before sending the request to the next policy.
- Parameters
request (PipelineRequest) – The PipelineRequest object
-
property
headers
¶ The current headers collection.
-
class
azure.core.pipeline.policies.
UserAgentPolicy
(base_user_agent: Optional[str] = None, **kwargs: Any)[source]¶ Bases:
azure.core.pipeline.policies._base.SansIOHTTPPolicy
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:
-
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_request
(request: azure.core.pipeline.PipelineRequest) → None[source]¶ Modifies the User-Agent header before the request is sent.
- Parameters
request (PipelineRequest) – The PipelineRequest object
-
property
user_agent
¶ The current user agent value.
-
class
azure.core.pipeline.policies.
NetworkTraceLoggingPolicy
(logging_enable=False, **kwargs)[source]¶ Bases:
azure.core.pipeline.policies._base.SansIOHTTPPolicy
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:
-
on_request
(request: azure.core.pipeline.PipelineRequest) → None[source]¶ Logs HTTP request to the DEBUG logger.
- Parameters
request (PipelineRequest) – The PipelineRequest object.
-
on_response
(request: azure.core.pipeline.PipelineRequest, response: azure.core.pipeline.PipelineResponse) → None[source]¶ Logs HTTP response to the DEBUG logger.
- Parameters
request (PipelineRequest) – The PipelineRequest object.
response (PipelineResponse) – The PipelineResponse object.
-
class
azure.core.pipeline.policies.
ContentDecodePolicy
(response_encoding: Optional[str] = None, **kwargs: Any)[source]¶ Bases:
azure.core.pipeline.policies._base.SansIOHTTPPolicy
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, encoding=None)[source]¶ Deserialize from HTTP response.
Headers will tested for “content-type”
- Parameters
response – The HTTP response
encoding – The encoding to use if known for this service (will disable auto-detection)
- Raises
DecodeError – If deserialization fails
- Returns
A dict or XML tree, depending of the mime-type
-
classmethod
deserialize_from_text
(data, mime_type=None, response=None)[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
response (HttpResponse) – 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 or XML tree, depending of the mime_type
-
on_request
(request: azure.core.pipeline.PipelineRequest) → 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, Union[HttpResponse, AsyncHttpResponse]]) → 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
request (PipelineRequest) – The PipelineRequest object.
response (PipelineResponse) – The PipelineResponse object.
raw_data – Data to be processed.
content_type – How to parse if raw_data is a string/bytes.
- Raises
JSONDecodeError – If JSON is requested and parsing is impossible.
UnicodeDecodeError – If bytes is not UTF8
xml.etree.ElementTree.ParseError – If bytes is not valid XML
DecodeError – If deserialization fails
-
CONTEXT_NAME
= 'deserialized_data'¶
-
JSON_REGEXP
= re.compile('^(application|text)/([0-9a-z+.]+\\+)?json$')¶
-
class
azure.core.pipeline.policies.
RetryMode
[source]¶ -
An enumeration.
-
Exponential
= 'exponential'¶
-
Fixed
= 'fixed'¶
-
-
class
azure.core.pipeline.policies.
RetryPolicy
(**kwargs)[source]¶ Bases:
azure.core.pipeline.policies._base.HTTPPolicy
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 alwasy 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:
-
configure_retries
(options)[source]¶ Configures the retry settings.
- Parameters
options – keyword arguments from context.
- Returns
A dict containing settings and history for retries.
- Return type
-
get_retry_after
(response)[source]¶ Get the value of Retry-After in seconds.
- Parameters
response (PipelineResponse) – The PipelineResponse object
- Returns
Value of Retry-After in seconds.
- Return type
-
increment
(settings, response=None, error=None)[source]¶ Increment the retry counters.
- Parameters
settings – The retry settings.
response (PipelineResponse) – A pipeline response object.
error – 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
-
is_retry
(settings, response)[source]¶ Checks if method/status code is retryable.
Based on whitelists 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
-
send
(request)[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
- Raises
~azure.core.exceptions.AzureError if maximum retries exceeded.
- Raises
~azure.core.exceptions.ClientAuthenticationError if authentication
-
sleep
(settings, transport, response=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
settings (dict) – The retry settings.
transport – The HTTP transport type.
response (PipelineResponse) – The PipelineResponse object.
-
update_context
(context, retry_settings)[source]¶ Updates retry history in pipeline context.
- Parameters
context (PipelineContext) – The pipeline context.
retry_settings (dict) – The retry settings.
-
BACKOFF_MAX
= 120¶ Maximum backoff time.
-
class
azure.core.pipeline.policies.
RedirectPolicy
(**kwargs)[source]¶ Bases:
azure.core.pipeline.policies._base.HTTPPolicy
A redirect policy.
A redirect policy in the pipeline can be configured directly or per operation.
- Keyword Arguments
Example:
-
configure_redirects
(options)[source]¶ Configures the redirect settings.
- Parameters
options – Keyword arguments from context.
- Returns
A dict containing redirect settings and a history of redirects.
- Return type
-
get_redirect_location
(response)[source]¶ 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.
-
increment
(settings, response, redirect_location)[source]¶ 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
-
send
(request)[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
- Raises
~azure.core.exceptions.TooManyRedirectsError if maximum redirects exceeded.
-
REDIRECT_HEADERS_BLACKLIST
= frozenset({'Authorization'})¶
-
REDIRECT_STATUSES
= frozenset({300, 301, 302, 303, 307, 308})¶
-
class
azure.core.pipeline.policies.
ProxyPolicy
(proxies=None, **kwargs)[source]¶ Bases:
azure.core.pipeline.policies._base.SansIOHTTPPolicy
A proxy policy.
Dictionary mapping protocol or protocol and host to the URL of the proxy to be used on each Request.
- Parameters
proxies (dict) – Maps protocol or protocol and hostname to the URL of the proxy.
Example:
-
on_request
(request: azure.core.pipeline.PipelineRequest) → None[source]¶ Is executed before sending the request from next policy.
- Parameters
request (PipelineRequest) – Request to be modified before sent from next policy.
-
class
azure.core.pipeline.policies.
CustomHookPolicy
(**kwargs)[source]¶ Bases:
azure.core.pipeline.policies._base.SansIOHTTPPolicy
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_request
(request: azure.core.pipeline.PipelineRequest) → None[source]¶ This is executed before sending the request to the next policy.
- Parameters
request (PipelineRequest) – The PipelineRequest object.
-
on_response
(request: azure.core.pipeline.PipelineRequest, response: azure.core.pipeline.PipelineResponse) → None[source]¶ This is executed after the request comes back from the policy.
- Parameters
request (PipelineRequest) – The PipelineRequest object.
response (PipelineResponse) – The PipelineResponse object.
-
class
azure.core.pipeline.policies.
DistributedTracingPolicy
(**kwargs)[source]¶ Bases:
azure.core.pipeline.policies._base.SansIOHTTPPolicy
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, response: Optional[HttpResponseType] = None, exc_info: Optional[Tuple] = None) → None[source]¶ Ends the span that is tracing the network and updates its status.
-
on_exception
(request: PipelineRequest) → bool[source]¶ Is executed if an exception is raised while executing the next policy.
Developer can optionally implement this method to return True if the exception has been handled and should not be forwarded to the caller.
This method is executed inside the exception handler.
- Parameters
request (PipelineRequest) – The Pipeline request object
- Returns
False by default, override with True to stop the exception.
- Return type
Example:
-
on_request
(request: PipelineRequest) → 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, response: PipelineResponse) → None[source]¶ Is executed after the request comes back from the policy.
- Parameters
request (PipelineRequest) – Request to be modified after returning from the policy.
response (PipelineResponse) – Pipeline response object
-
TRACING_CONTEXT
= 'TRACING_CONTEXT'¶
-
class
azure.core.pipeline.policies.
RequestHistory
(http_request: HTTPRequestType, http_response: Optional[HTTPResponseType] = None, error: Optional[Exception] = None, context: Optional[Dict[str, Any]] = None)[source]¶ Bases:
object
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.
HttpLoggingPolicy
(logger=None, **kwargs)[source]¶ Bases:
azure.core.pipeline.policies._base.SansIOHTTPPolicy
The Pipeline policy that handles logging of HTTP requests and responses.
-
on_request
(request: azure.core.pipeline.PipelineRequest) → None[source]¶ Logs HTTP method, url and headers. :param request: The PipelineRequest object. :type request: ~azure.core.pipeline.PipelineRequest
-
on_response
(request: azure.core.pipeline.PipelineRequest, response: azure.core.pipeline.PipelineResponse) → None[source]¶ Is executed after the request comes back from the policy.
- Parameters
request (PipelineRequest) – Request to be modified after returning from the policy.
response (PipelineResponse) – Pipeline response object
-
DEFAULT_HEADERS_WHITELIST
= {'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', 'traceparent', 'x-ms-client-request-id', 'x-ms-request-id', 'x-ms-return-client-request-id'}¶
-
REDACTED_PLACEHOLDER
= 'REDACTED'¶
-
-
class
azure.core.pipeline.policies.
RequestIdPolicy
(**kwargs: dict)[source]¶ Bases:
azure.core.pipeline.policies._base.SansIOHTTPPolicy
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
Example:
-
on_request
(request: azure.core.pipeline.PipelineRequest) → None[source]¶ Updates with the given request id before sending the request to the next policy.
- Parameters
request (PipelineRequest) – The PipelineRequest object
-
class
azure.core.pipeline.policies.
AsyncHTTPPolicy
[source]¶ Bases:
abc.ABC
,typing.Generic
An async HTTP policy ABC.
Use with an asynchronous pipeline.
- Parameters
next (AsyncHTTPPolicy or AsyncHttpTransport) – Use to process the next policy in the pipeline. Set when pipeline is instantiated and all policies chained.
-
abstract async
send
(request: azure.core.pipeline.PipelineRequest)[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
-
class
azure.core.pipeline.policies.
AsyncBearerTokenCredentialPolicy
(credential, *scopes, **kwargs)[source]¶ Bases:
azure.core.pipeline.policies._authentication._BearerTokenCredentialPolicyBase
,azure.core.pipeline.policies._base.SansIOHTTPPolicy
Adds a bearer token Authorization header to requests.
- Parameters
credential (TokenCredential) – The credential.
scopes (str) – Lets you specify the type of access needed.
-
async
on_request
(request: azure.core.pipeline.PipelineRequest)[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
-
class
azure.core.pipeline.policies.
AsyncRedirectPolicy
(**kwargs)[source]¶ Bases:
azure.core.pipeline.policies._redirect.RedirectPolicy
,azure.core.pipeline.policies._base_async.AsyncHTTPPolicy
An async redirect policy.
An async redirect policy in the pipeline can be configured directly or per operation.
- Keyword Arguments
Example:
-
async
send
(request)[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
- Raises
~azure.core.exceptions.TooManyRedirectsError if maximum redirects exceeded.
-
class
azure.core.pipeline.policies.
AsyncRetryPolicy
(**kwargs)[source]¶ Bases:
azure.core.pipeline.policies._retry.RetryPolicy
,azure.core.pipeline.policies._base_async.AsyncHTTPPolicy
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:
-
async
send
(request)[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
- Raise
~azure.core.exceptions.AzureError if maximum retries exceeded.
- Raise
~azure.core.exceptions.ClientAuthenticationError if authentication fails
-
async
sleep
(settings, transport, response=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
settings (dict) – The retry settings.
transport – The HTTP transport type.
response (PipelineResponse) – The PipelineResponse object.