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.
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, response: PipelineResponse) → 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
request (PipelineRequest) – the request which elicited an authentication challenge
response (PipelineResponse) – the resource provider’s response
- Returns
a bool indicating whether the policy should send the request
-
on_exception
(request: PipelineRequest) → 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) → 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
-
on_response
(request: PipelineRequest, response: PipelineResponse) → Union[None, Awaitable[None]][source]¶ Executed after the request comes back from the next policy.
- Parameters
request (PipelineRequest) – Request to be modified after returning from the policy.
response (PipelineResponse) – Pipeline response object
-
async
send
(request: PipelineRequest) → PipelineResponse[source]¶ Authorize request with a bearer token and send it to the next policy
- Parameters
request (PipelineRequest) – The pipeline request object
-
class
azure.core.pipeline.policies.
AsyncHTTPPolicy
[source]¶ 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.
AsyncRedirectPolicy
(**kwargs)[source]¶ An async redirect policy.
An async redirect policy in the pipeline can be configured directly or per operation.
- Keyword Arguments
Example:
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(base_url=url, policies=[redirect_policy]) as client: response = await client._pipeline.run(request, permit_redirects=True, redirect_max=5)
-
configure_redirects
(options)¶ 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)¶ 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)¶ 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
-
classmethod
no_redirects
()¶ Disable redirects.
-
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.
-
REDIRECT_HEADERS_BLACKLIST
= frozenset({'Authorization'})¶
-
REDIRECT_STATUSES
= frozenset({300, 301, 302, 303, 307, 308})¶
-
class
azure.core.pipeline.policies.
AsyncRetryPolicy
(**kwargs)[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:
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(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)¶ Configures the retry settings.
- Parameters
options – keyword arguments from context.
- Returns
A dict containing settings and history for retries.
- Return type
-
get_backoff_time
(settings)¶ Returns the current backoff time.
-
get_retry_after
(response)¶ 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)¶ 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_exhausted
(settings)¶ Checks if any retries left.
-
is_retry
(settings, response)¶ 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
-
classmethod
no_retries
()¶ Disable retries.
-
parse_retry_after
(retry_after)¶ Helper to parse Retry-After and get value in seconds.
-
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.
-
update_context
(context, retry_settings)¶ 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.
AzureKeyCredentialPolicy
(credential: AzureKeyCredential, name: str, **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.
- Raises
ValueError or TypeError
-
on_exception
(request: azure.core.pipeline.PipelineRequest) → 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
Example:
-
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.
-
on_response
(request: azure.core.pipeline.PipelineRequest, response: azure.core.pipeline.PipelineResponse) → Union[None, Awaitable[None]]¶ 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.
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: azure.core.pipeline.PipelineRequest) → 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
Example:
-
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.
-
on_response
(request: azure.core.pipeline.PipelineRequest, response: azure.core.pipeline.PipelineResponse) → Union[None, Awaitable[None]]¶ 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: 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.
- Raises
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, response: PipelineResponse) → 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
request (PipelineRequest) – the request which elicited an authentication challenge
response (PipelineResponse) – the resource provider’s response
- Returns
a bool indicating whether the policy should send the request
-
on_exception
(request: PipelineRequest) → 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) → 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, response: PipelineResponse) → None[source]¶ Executed after the request comes back from the next policy.
- Parameters
request (PipelineRequest) – Request to be modified after returning from the policy.
response (PipelineResponse) – Pipeline response object
-
send
(request: PipelineRequest) → PipelineResponse[source]¶ Authorize request with a bearer token and send it to the next policy
- Parameters
request (PipelineRequest) – The pipeline request object
-
class
azure.core.pipeline.policies.
ContentDecodePolicy
(response_encoding: Optional[str] = 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, 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_exception
(request: azure.core.pipeline.PipelineRequest) → 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
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.
-
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.
CustomHookPolicy
(**kwargs)[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: azure.core.pipeline.PipelineRequest) → 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
Example:
-
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]¶ 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) → 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
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.
HTTPPolicy
[source]¶ 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.
HeadersPolicy
(base_headers: Optional[Dict[str, str]] = 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:
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(base_url=url, policies=policies) request = client.get(url) pipeline_response = client._pipeline.run(request, headers={'CustomValue': 'Bar'})
-
on_exception
(request: azure.core.pipeline.PipelineRequest) → 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
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
-
on_response
(request: azure.core.pipeline.PipelineRequest, response: azure.core.pipeline.PipelineResponse) → Union[None, Awaitable[None]]¶ 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
-
property
headers
¶ The current headers collection.
-
class
azure.core.pipeline.policies.
HttpLoggingPolicy
(logger=None, **kwargs)[source]¶ The Pipeline policy that handles logging of HTTP requests and responses.
-
on_exception
(request: azure.core.pipeline.PipelineRequest) → 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
Example:
-
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'}¶
-
MULTI_RECORD_LOG
= 'AZURE_SDK_LOGGING_MULTIRECORD'¶
-
REDACTED_PLACEHOLDER
= 'REDACTED'¶
-
-
class
azure.core.pipeline.policies.
NetworkTraceLoggingPolicy
(logging_enable=False, **kwargs)[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:
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(base_url=url, policies=policies) request = client.get(url) pipeline_response = client._pipeline.run(request, logging_enable=True)
-
on_exception
(request: azure.core.pipeline.PipelineRequest) → 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
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.
ProxyPolicy
(proxies=None, **kwargs)[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 (dict) – Maps protocol or protocol and hostname to the URL of the proxy.
Example:
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: azure.core.pipeline.PipelineRequest) → 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
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.
-
on_response
(request: azure.core.pipeline.PipelineRequest, response: azure.core.pipeline.PipelineResponse) → Union[None, Awaitable[None]]¶ 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.
RedirectPolicy
(**kwargs)[source]¶ A redirect policy.
A redirect policy in the pipeline can be configured directly or per operation.
- Keyword Arguments
Example:
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(base_url=url, policies=[redirect_policy]) request = client.get(url) pipeline_response = client._pipeline.run(request, permit_redirects=True, redirect_max=5)
-
configure_redirects
(options)¶ 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)¶ 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)¶ 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
-
classmethod
no_redirects
()¶ Disable redirects.
-
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.
RequestHistory
(http_request: HTTPRequestType, http_response: Optional[HTTPResponseType] = None, error: Optional[Exception] = None, context: Optional[Dict[str, Any]] = 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
(**kwargs: dict)[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
Example:
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(base_url=url, policies=policies) request = client.get(url) pipeline_response = client._pipeline.run(request, request_id="azconfig-test")
-
on_exception
(request: azure.core.pipeline.PipelineRequest) → 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
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
-
on_response
(request: azure.core.pipeline.PipelineRequest, response: azure.core.pipeline.PipelineResponse) → Union[None, Awaitable[None]]¶ 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.
RetryMode
(value)[source]¶ An enumeration.
-
Exponential
= 'exponential'¶
-
Fixed
= 'fixed'¶
-
-
class
azure.core.pipeline.policies.
RetryPolicy
(**kwargs)[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 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:
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(base_url=url, policies=policies) request = client.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)¶ Configures the retry settings.
- Parameters
options – keyword arguments from context.
- Returns
A dict containing settings and history for retries.
- Return type
-
get_backoff_time
(settings)¶ Returns the current backoff time.
-
get_retry_after
(response)¶ 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)¶ 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_exhausted
(settings)¶ Checks if any retries left.
-
is_retry
(settings, response)¶ 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
-
classmethod
no_retries
()¶ Disable retries.
-
parse_retry_after
(retry_after)¶ Helper to parse Retry-After and get value in seconds.
-
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)¶ 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.
SansIOHTTPPolicy
(*args, **kwds)[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: azure.core.pipeline.PipelineRequest) → 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
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.
UserAgentPolicy
(base_user_agent: Optional[str] = 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:
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(base_url=url, policies=policies) request = client.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: azure.core.pipeline.PipelineRequest) → 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
Example:
-
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
-
on_response
(request: azure.core.pipeline.PipelineRequest, response: azure.core.pipeline.PipelineResponse) → Union[None, Awaitable[None]]¶ 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
-
property
user_agent
¶ The current user agent value.