Azure Core shared client library for Python¶
Azure core provides shared exceptions and modules for Python SDK client libraries. These libraries follow the Azure SDK Design Guidelines for Python .
If you are a client library developer, please reference client library developer reference for more information.
Source code | Package (Pypi) | Package (Conda) | API reference documentation
Getting started¶
Typically, you will not need to install azure core; it will be installed when you install one of the client libraries using it. In case you want to install it explicitly (to implement your own client library, for example), you can find it here.
Key concepts¶
Azure Core Library Exceptions¶
AzureError¶
AzureError is the base exception for all errors.
class AzureError(Exception):
def __init__(self, message, *args, **kwargs):
self.inner_exception = kwargs.get("error")
self.exc_type, self.exc_value, self.exc_traceback = sys.exc_info()
self.exc_type = self.exc_type.__name__ if self.exc_type else type(self.inner_exception)
self.exc_msg = "{}, {}: {}".format(message, self.exc_type, self.exc_value) # type: ignore
self.message = str(message)
self.continuation_token = kwargs.get("continuation_token")
super(AzureError, self).__init__(self.message, *args)
message is any message (str) to be associated with the exception.
args are any additional args to be included with exception.
kwargs are keyword arguments to include with the exception. Use the keyword error to pass in an internal exception and continuation_token for a token reference to continue an incomplete operation.
The following exceptions inherit from AzureError:
ServiceRequestError¶
An error occurred while attempt to make a request to the service. No request was sent.
ServiceResponseError¶
The request was sent, but the client failed to understand the response. The connection may have timed out. These errors can be retried for idempotent or safe operations.
HttpResponseError¶
A request was made, and a non-success status code was received from the service.
class HttpResponseError(AzureError):
def __init__(self, message=None, response=None, **kwargs):
self.reason = None
self.response = response
if response:
self.reason = response.reason
self.status_code = response.status_code
self.error = self._parse_odata_body(ODataV4Format, response) # type: Optional[ODataV4Format]
if self.error:
message = str(self.error)
else:
message = message or "Operation returned an invalid status '{}'".format(
self.reason
)
super(HttpResponseError, self).__init__(message=message, **kwargs)
message is the HTTP response error message (optional)
response is the HTTP response (optional).
kwargs are keyword arguments to include with the exception.
The following exceptions inherit from HttpResponseError:
DecodeError¶
An error raised during response de-serialization.
IncompleteReadError¶
An error raised if peer closes the connection before we have received the complete message body.
ResourceExistsError¶
An error response with status code 4xx. This will not be raised directly by the Azure core pipeline.
ResourceNotFoundError¶
An error response, typically triggered by a 412 response (for update) or 404 (for get/post).
ResourceModifiedError¶
An error response with status code 4xx, typically 412 Conflict. This will not be raised directly by the Azure core pipeline.
ResourceNotModifiedError¶
An error response with status code 304. This will not be raised directly by the Azure core pipeline.
ClientAuthenticationError¶
An error response with status code 4xx. This will not be raised directly by the Azure core pipeline.
TooManyRedirectsError¶
An error raised when the maximum number of redirect attempts is reached. The maximum amount of redirects can be configured in the RedirectPolicy.
class TooManyRedirectsError(HttpResponseError):
def __init__(self, history, *args, **kwargs):
self.history = history
message = "Reached maximum redirect attempts."
super(TooManyRedirectsError, self).__init__(message, *args, **kwargs)
history is used to document the requests/responses that resulted in redirected requests.
args are any additional args to be included with exception.
kwargs are keyword arguments to include with the exception.
StreamConsumedError¶
An error thrown if you try to access the stream of azure.core.rest.HttpResponse
or azure.core.rest.AsyncHttpResponse
once
the response stream has been consumed.
StreamClosedError¶
An error thrown if you try to access the stream of the azure.core.rest.HttpResponse
or azure.core.rest.AsyncHttpResponse
once
the response stream has been closed.
ResponseNotReadError¶
An error thrown if you try to access the content
of azure.core.rest.HttpResponse
or azure.core.rest.AsyncHttpResponse
before
reading in the response’s bytes first.
Configurations¶
When calling the methods, some properties can be configured by passing in as kwargs arguments.
Parameters |
Description |
---|---|
headers |
The HTTP Request headers. |
request_id |
The request id to be added into header. |
user_agent |
If specified, this will be added in front of the user agent string. |
logging_enable |
Use to enable per operation. Defaults to |
logger |
If specified, it will be used to log information. |
response_encoding |
The encoding to use if known for this service (will disable auto-detection). |
raw_request_hook |
Callback function. Will be invoked on request. |
raw_response_hook |
Callback function. Will be invoked on response. |
network_span_namer |
A callable to customize the span name. |
tracing_attributes |
Attributes to set on all created spans. |
permit_redirects |
Whether the client allows redirects. Defaults to |
redirect_max |
The maximum allowed redirects. Defaults to |
retry_total |
Total number of retries to allow. Takes precedence over other counts. Default value is |
retry_connect |
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 |
retry_read |
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 |
retry_status |
How many times to retry on bad status codes. Default value is |
retry_backoff_factor |
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: |
retry_backoff_max |
The maximum back off time. Default value is |
retry_mode |
Fixed or exponential delay between attempts, default is |
timeout |
Timeout setting for the operation in seconds, default is |
connection_timeout |
A single float in seconds for the connection timeout. Defaults to |
read_timeout |
A single float in seconds for the read timeout. Defaults to |
connection_verify |
SSL certificate verification. Enabled by default. Set to False to disable, alternatively can be set to the path to a CA_BUNDLE file or directory with certificates of trusted CAs. |
connection_cert |
Client-side certificates. You can specify a local cert to use as client side certificate, as a single file (containing the private key and the certificate) or as a tuple of both files’ paths. |
proxies |
Dictionary mapping protocol or protocol and hostname to the URL of the proxy. |
cookies |
Dict or CookieJar object to send with the |
connection_data_block_size |
The block size of data sent over the connection. Defaults to |
Async transport¶
The async transport is designed to be opt-in. AioHttp is one of the supported implementations of async transport. It is not installed by default. You need to install it separately.
Shared modules¶
MatchConditions¶
MatchConditions is an enum to describe match conditions.
class MatchConditions(Enum):
Unconditionally = 1 # Matches any condition
IfNotModified = 2 # If the target object is not modified. Usually it maps to etag=<specific etag>
IfModified = 3 # Only if the target object is modified. Usually it maps to etag!=<specific etag>
IfPresent = 4 # If the target object exists. Usually it maps to etag='*'
IfMissing = 5 # If the target object does not exist. Usually it maps to etag!='*'
CaseInsensitiveEnumMeta¶
A metaclass to support case-insensitive enums.
from enum import Enum
from azure.core import CaseInsensitiveEnumMeta
class MyCustomEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta):
FOO = 'foo'
BAR = 'bar'
Null Sentinel Value¶
A falsy sentinel object which is supposed to be used to specify attributes
with no data. This gets serialized to null
on the wire.
from azure.core.serialization import NULL
assert bool(NULL) is False
foo = Foo(
attr=NULL
)
Contributing¶
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
Indices and tables¶
- azure-core
AsyncPipelineClient
AsyncPipelineClient.close()
AsyncPipelineClient.delete()
AsyncPipelineClient.format_url()
AsyncPipelineClient.get()
AsyncPipelineClient.head()
AsyncPipelineClient.merge()
AsyncPipelineClient.options()
AsyncPipelineClient.patch()
AsyncPipelineClient.post()
AsyncPipelineClient.put()
AsyncPipelineClient.send_request()
AzureClouds
AzureClouds.capitalize()
AzureClouds.casefold()
AzureClouds.center()
AzureClouds.count()
AzureClouds.encode()
AzureClouds.endswith()
AzureClouds.expandtabs()
AzureClouds.find()
AzureClouds.format()
AzureClouds.format_map()
AzureClouds.index()
AzureClouds.isalnum()
AzureClouds.isalpha()
AzureClouds.isascii()
AzureClouds.isdecimal()
AzureClouds.isdigit()
AzureClouds.isidentifier()
AzureClouds.islower()
AzureClouds.isnumeric()
AzureClouds.isprintable()
AzureClouds.isspace()
AzureClouds.istitle()
AzureClouds.isupper()
AzureClouds.join()
AzureClouds.ljust()
AzureClouds.lower()
AzureClouds.lstrip()
AzureClouds.maketrans()
AzureClouds.partition()
AzureClouds.removeprefix()
AzureClouds.removesuffix()
AzureClouds.replace()
AzureClouds.rfind()
AzureClouds.rindex()
AzureClouds.rjust()
AzureClouds.rpartition()
AzureClouds.rsplit()
AzureClouds.rstrip()
AzureClouds.split()
AzureClouds.splitlines()
AzureClouds.startswith()
AzureClouds.strip()
AzureClouds.swapcase()
AzureClouds.title()
AzureClouds.translate()
AzureClouds.upper()
AzureClouds.zfill()
AzureClouds.AZURE_CHINA_CLOUD
AzureClouds.AZURE_PUBLIC_CLOUD
AzureClouds.AZURE_US_GOVERNMENT
CaseInsensitiveEnumMeta
MatchConditions
PipelineClient
- Subpackages
- azure.core.pipeline
- azure.core.polling
- azure.core.tracing
AbstractSpan
AbstractSpan.add_attribute()
AbstractSpan.change_context()
AbstractSpan.finish()
AbstractSpan.get_current_span()
AbstractSpan.get_current_tracer()
AbstractSpan.get_trace_parent()
AbstractSpan.link()
AbstractSpan.link_from_headers()
AbstractSpan.set_current_span()
AbstractSpan.set_current_tracer()
AbstractSpan.set_http_attributes()
AbstractSpan.span()
AbstractSpan.start()
AbstractSpan.to_header()
AbstractSpan.with_current_context()
AbstractSpan.kind
AbstractSpan.span_instance
HttpSpanMixin
Link
SpanKind
- Submodules
- azure.core.tracing.common
- azure.core.tracing.decorator
- azure.core.tracing.decorator_async
- Submodules
- azure.core.async_paging
- azure.core.credentials
AccessToken
AccessTokenInfo
AzureKeyCredential
AzureNamedKeyCredential
AzureSasCredential
SupportsTokenInfo
TokenCredential
TokenRequestOptions
TokenRequestOptions.clear()
TokenRequestOptions.copy()
TokenRequestOptions.fromkeys()
TokenRequestOptions.get()
TokenRequestOptions.items()
TokenRequestOptions.keys()
TokenRequestOptions.pop()
TokenRequestOptions.popitem()
TokenRequestOptions.setdefault()
TokenRequestOptions.update()
TokenRequestOptions.values()
TokenRequestOptions.claims
TokenRequestOptions.enable_cae
TokenRequestOptions.tenant_id
- azure.core.credentials_async
- azure.core.exceptions
AzureError
ClientAuthenticationError
DecodeError
DeserializationError
HttpResponseError
ODataV4Error
ResourceExistsError
ResourceModifiedError
ResourceNotFoundError
ResourceNotModifiedError
ResponseNotReadError
SerializationError
ServiceRequestError
ServiceResponseError
StreamClosedError
StreamConsumedError
TooManyRedirectsError
ODataV4Format
- azure.core.messaging
- azure.core.paging
- azure.core.settings
- azure.core.serialization
- azure.core.rest
AsyncHttpResponse
AsyncHttpResponse.close()
AsyncHttpResponse.iter_bytes()
AsyncHttpResponse.iter_raw()
AsyncHttpResponse.json()
AsyncHttpResponse.raise_for_status()
AsyncHttpResponse.read()
AsyncHttpResponse.text()
AsyncHttpResponse.content
AsyncHttpResponse.content_type
AsyncHttpResponse.encoding
AsyncHttpResponse.headers
AsyncHttpResponse.is_closed
AsyncHttpResponse.is_stream_consumed
AsyncHttpResponse.reason
AsyncHttpResponse.request
AsyncHttpResponse.status_code
AsyncHttpResponse.url
HttpRequest
HttpResponse
HttpResponse.close()
HttpResponse.iter_bytes()
HttpResponse.iter_raw()
HttpResponse.json()
HttpResponse.raise_for_status()
HttpResponse.read()
HttpResponse.text()
HttpResponse.content
HttpResponse.content_type
HttpResponse.encoding
HttpResponse.headers
HttpResponse.is_closed
HttpResponse.is_stream_consumed
HttpResponse.reason
HttpResponse.request
HttpResponse.status_code
HttpResponse.url
- azure.core.utils
CaseInsensitiveDict
CaseInsensitiveDict.clear()
CaseInsensitiveDict.copy()
CaseInsensitiveDict.get()
CaseInsensitiveDict.items()
CaseInsensitiveDict.keys()
CaseInsensitiveDict.lowerkey_items()
CaseInsensitiveDict.pop()
CaseInsensitiveDict.popitem()
CaseInsensitiveDict.setdefault()
CaseInsensitiveDict.update()
CaseInsensitiveDict.values()
case_insensitive_dict()
parse_connection_string()