azure-core

class azure.core.AsyncPipelineClient(base_url, **kwargs)[source]

Service client core methods.

Builds an AsyncPipeline client.

Parameters

base_url (str) – URL for the request.

Keyword Arguments
Returns

An async pipeline object.

Return type

AsyncPipeline

Example:

Builds the async pipeline client.
from azure.core import AsyncPipelineClient
from azure.core.pipeline.policies import AsyncRedirectPolicy, UserAgentPolicy
from azure.core.pipeline.transport import HttpRequest

# example policies
request = HttpRequest("GET", url)
policies = [
    UserAgentPolicy("myuseragent"),
    AsyncRedirectPolicy(),
]

async with AsyncPipelineClient(base_url=url, policies=policies) as client:
    response = await client._pipeline.run(request)
async close()[source]
delete(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, content: Optional[Any] = None, form_content: Optional[Dict[str, Any]] = None)azure.core.pipeline.transport._base.HttpRequest

Create a DELETE request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

format_url(url_template: str, **kwargs: Any)str

Format request URL with the client base URL, unless the supplied URL is already absolute.

Parameters

url_template (str) – The request URL to be formatted if necessary.

get(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, content: Optional[Any] = None, form_content: Optional[Dict[str, Any]] = None)azure.core.pipeline.transport._base.HttpRequest

Create a GET request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

head(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, content: Optional[Any] = None, form_content: Optional[Dict[str, Any]] = None, stream_content: Optional[Any] = None)azure.core.pipeline.transport._base.HttpRequest

Create a HEAD request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

merge(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, content: Optional[Any] = None, form_content: Optional[Dict[str, Any]] = None)azure.core.pipeline.transport._base.HttpRequest

Create a MERGE request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

options(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, **kwargs: Any)azure.core.pipeline.transport._base.HttpRequest

Create a OPTIONS request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

Keyword Arguments
  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

patch(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, content: Optional[Any] = None, form_content: Optional[Dict[str, Any]] = None, stream_content: Optional[Any] = None)azure.core.pipeline.transport._base.HttpRequest

Create a PATCH request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

post(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, content: Optional[Any] = None, form_content: Optional[Dict[str, Any]] = None, stream_content: Optional[Any] = None)azure.core.pipeline.transport._base.HttpRequest

Create a POST request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

put(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, content: Optional[Any] = None, form_content: Optional[Dict[str, Any]] = None, stream_content: Optional[Any] = None)azure.core.pipeline.transport._base.HttpRequest

Create a PUT request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

send_request(request: HTTPRequestType, *, stream: bool = False, **kwargs: Any)Awaitable[AsyncHTTPResponseType][source]

Provisional method that runs the network request through the client’s chained policies.

This method is marked as provisional, meaning it may be changed in a future release.

>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest('GET', 'http://www.example.com')
<HttpRequest [GET], url: 'http://www.example.com'>
>>> response = await client.send_request(request)
<AsyncHttpResponse: 200 OK>
Parameters

request (HttpRequest) – The network request you want to make. Required.

Keyword Arguments

stream (bool) – Whether the response payload will be streamed. Defaults to False.

Returns

The response of your network call. Does not do error handling on your response.

Return type

AsyncHttpResponse

class azure.core.CaseInsensitiveEnumMeta(cls, bases, classdict)[source]

Enum metaclass to allow for interoperability with case-insensitive strings.

Consuming this metaclass in an SDK should be done in the following manner:

from enum import Enum
from six import with_metaclass
from azure.core import CaseInsensitiveEnumMeta

class MyCustomEnum(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
    FOO = 'foo'
    BAR = 'bar'
mro()list

return a type’s method resolution order

class azure.core.MatchConditions(value)[source]

An enum to describe match conditions.

IfMissing = 5
IfModified = 3
IfNotModified = 2
IfPresent = 4
Unconditionally = 1
class azure.core.PipelineClient(base_url, **kwargs)[source]

Service client core methods.

Builds a Pipeline client.

Parameters

base_url (str) – URL for the request.

Keyword Arguments
Returns

A pipeline object.

Return type

Pipeline

Example:

Builds the pipeline client.
from azure.core import PipelineClient
from azure.core.pipeline.policies import RedirectPolicy, UserAgentPolicy

# example configuration with some policies
policies = [
    UserAgentPolicy("myuseragent"),
    RedirectPolicy()
]

client = PipelineClient(base_url=url, policies=policies)
request = client.get("https://bing.com")

pipeline_response = client._pipeline.run(request)
close()[source]
delete(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, content: Optional[Any] = None, form_content: Optional[Dict[str, Any]] = None)azure.core.pipeline.transport._base.HttpRequest

Create a DELETE request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

format_url(url_template: str, **kwargs: Any)str

Format request URL with the client base URL, unless the supplied URL is already absolute.

Parameters

url_template (str) – The request URL to be formatted if necessary.

get(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, content: Optional[Any] = None, form_content: Optional[Dict[str, Any]] = None)azure.core.pipeline.transport._base.HttpRequest

Create a GET request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

head(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, content: Optional[Any] = None, form_content: Optional[Dict[str, Any]] = None, stream_content: Optional[Any] = None)azure.core.pipeline.transport._base.HttpRequest

Create a HEAD request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

merge(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, content: Optional[Any] = None, form_content: Optional[Dict[str, Any]] = None)azure.core.pipeline.transport._base.HttpRequest

Create a MERGE request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

options(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, **kwargs: Any)azure.core.pipeline.transport._base.HttpRequest

Create a OPTIONS request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

Keyword Arguments
  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

patch(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, content: Optional[Any] = None, form_content: Optional[Dict[str, Any]] = None, stream_content: Optional[Any] = None)azure.core.pipeline.transport._base.HttpRequest

Create a PATCH request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

post(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, content: Optional[Any] = None, form_content: Optional[Dict[str, Any]] = None, stream_content: Optional[Any] = None)azure.core.pipeline.transport._base.HttpRequest

Create a POST request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

put(url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, content: Optional[Any] = None, form_content: Optional[Dict[str, Any]] = None, stream_content: Optional[Any] = None)azure.core.pipeline.transport._base.HttpRequest

Create a PUT request object.

Parameters
  • url (str) – The request URL.

  • params (dict) – Request URL parameters.

  • headers (dict) – Headers

  • content – The body content

  • form_content (dict) – Form content

Returns

An HttpRequest object

Return type

HttpRequest

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

Provisional method that runs the network request through the client’s chained policies.

This method is marked as provisional, meaning it may be changed in a future release.

>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest('GET', 'http://www.example.com')
<HttpRequest [GET], url: 'http://www.example.com'>
>>> response = client.send_request(request)
<HttpResponse: 200 OK>
Parameters

request (HttpRequest) – The network request you want to make. Required.

Keyword Arguments

stream (bool) – Whether the response payload will be streamed. Defaults to False.

Returns

The response of your network call. Does not do error handling on your response.

Return type

HttpResponse

#

Submodules

azure.core.async_paging

class azure.core.async_paging.AsyncItemPaged(*args, **kwargs)[source]

Return an async iterator of items.

args and kwargs will be passed to the AsyncPageIterator constructor directly, except page_iterator_class

by_page(continuation_token: Optional[str] = None)AsyncIterator[AsyncIterator[ReturnType]][source]

Get an async iterator of pages of objects, instead of an async iterator of objects.

Parameters

continuation_token (str) – An opaque continuation token. This value can be retrieved from the continuation_token field of a previous generator object. If specified, this generator will begin returning results from this point.

Returns

An async iterator of pages (themselves async iterator of objects)

class azure.core.async_paging.AsyncPageIterator(get_next: Callable[Optional[str], Awaitable[ResponseType]], extract_data: Callable[ResponseType, Awaitable[Tuple[str, AsyncIterator[ReturnType]]]], continuation_token: Optional[str] = None)[source]

Return an async iterator of pages.

Parameters
  • get_next – Callable that take the continuation token and return a HTTP response

  • extract_data – Callable that take an HTTP response and return a tuple continuation token, list of ReturnType

  • continuation_token (str) – The continuation token needed by get_next

azure.core.credentials

class azure.core.credentials.AccessToken(token, expires_on)

Create new instance of AccessToken(token, expires_on)

count(value)integer return number of occurrences of value
index(value[, start[, stop]])integer return first index of value.

Raises ValueError if the value is not present.

property expires_on

Alias for field number 1

property token

Alias for field number 0

class azure.core.credentials.AzureKeyCredential(key: str)[source]

Credential type used for authenticating to an Azure service. It provides the ability to update the key without creating a new client.

Parameters

key (str) – The key used to authenticate to an Azure service

Raises

TypeError

update(key: str)None[source]

Update the key.

This can be used when you’ve regenerated your service key and want to update long-lived clients.

Parameters

key (str) – The key used to authenticate to an Azure service

Raises

ValueError or TypeError

property key

The value of the configured key.

Return type

str

class azure.core.credentials.AzureNamedKeyCredential(name: str, key: str)[source]

Credential type used for working with any service needing a named key that follows patterns established by the other credential types.

Parameters
  • name (str) – The name of the credential used to authenticate to an Azure service.

  • key (str) – The key used to authenticate to an Azure service.

Raises

TypeError

update(name: str, key: str)None[source]

Update the named key credential.

Both name and key must be provided in order to update the named key credential. Individual attributes cannot be updated.

Parameters
  • name (str) – The name of the credential used to authenticate to an Azure service.

  • key (str) – The key used to authenticate to an Azure service.

property named_key

The value of the configured name.

Return type

AzureNamedKey

class azure.core.credentials.AzureSasCredential(signature: str)[source]

Credential type used for authenticating to an Azure service. It provides the ability to update the shared access signature without creating a new client.

Parameters

signature (str) – The shared access signature used to authenticate to an Azure service

Raises

TypeError

update(signature: str)None[source]

Update the shared access signature.

This can be used when you’ve regenerated your shared access signature and want to update long-lived clients.

Parameters

signature (str) – The shared access signature used to authenticate to an Azure service

Raises

ValueError or TypeError

property signature

The value of the configured shared access signature.

Return type

str

azure.core.exceptions

exception azure.core.exceptions.AzureError(message, *args, **kwargs)[source]

Base exception for all errors.

Parameters

message – The message object stringified as ‘message’ attribute

Keyword Arguments

error (Exception) – The original exception if any

Variables
  • inner_exception (Exception) – The exception passed with the ‘error’ kwarg

  • exc_type – The exc_type from sys.exc_info()

  • exc_value – The exc_value from sys.exc_info()

  • exc_traceback – The exc_traceback from sys.exc_info()

  • exc_msg – A string formatting of message parameter, exc_type and exc_value

  • message (str) – A stringified version of the message parameter

  • continuation_token (str) – A token reference to continue an incomplete operation. This value is optional and will be None where continuation is either unavailable or not applicable.

raise_with_traceback()[source]
exception azure.core.exceptions.ClientAuthenticationError(message=None, response=None, **kwargs)[source]

An error response with status code 4xx. This will not be raised directly by the Azure core pipeline.

exception azure.core.exceptions.DecodeError(message=None, response=None, **kwargs)[source]

Error raised during response deserialization.

exception azure.core.exceptions.HttpResponseError(message=None, response=None, **kwargs)[source]

A request was made, and a non-success status code was received from the service.

Parameters
  • message (string) – HttpResponse’s error message

  • response (HttpResponse or AsyncHttpResponse) – The response that triggered the exception.

Variables
  • reason (str) – The HTTP response reason

  • status_code (int) – HttpResponse’s status code

  • response (HttpResponse or AsyncHttpResponse) – The response that triggered the exception.

  • model (Model) – The request body/response body model

  • error (ODataV4Format) – The formatted error

exception azure.core.exceptions.ODataV4Error(response: _HttpResponseBase, **kwargs: Any)[source]

An HTTP response error where the JSON is decoded as OData V4 error format.

http://docs.oasis-open.org/odata/odata-json-format/v4.0/os/odata-json-format-v4.0-os.html#_Toc372793091

Variables
  • odata_json (dict) – The parsed JSON body as attribute for convenience.

  • code (str) – Its value is a service-defined error code. This code serves as a sub-status for the HTTP error code specified in the response.

  • message (str) – Human-readable, language-dependent representation of the error.

  • target (str) – The target of the particular error (for example, the name of the property in error). This field is optional and may be None.

  • details (list[ODataV4Format]) – Array of ODataV4Format instances that MUST contain name/value pairs for code and message, and MAY contain a name/value pair for target, as described above.

  • innererror (dict) – An object. The contents of this object are service-defined. Usually this object contains information that will help debug the service.

exception azure.core.exceptions.ResourceExistsError(message=None, response=None, **kwargs)[source]

An error response with status code 4xx. This will not be raised directly by the Azure core pipeline.

exception azure.core.exceptions.ResourceModifiedError(message=None, response=None, **kwargs)[source]

An error response with status code 4xx, typically 412 Conflict. This will not be raised directly by the Azure core pipeline.

exception azure.core.exceptions.ResourceNotFoundError(message=None, response=None, **kwargs)[source]

An error response, typically triggered by a 412 response (for update) or 404 (for get/post)

exception azure.core.exceptions.ResourceNotModifiedError(message=None, response=None, **kwargs)[source]

An error response with status code 304. This will not be raised directly by the Azure core pipeline.

exception azure.core.exceptions.ResponseNotReadError(response)[source]

Provisional error thrown if you try to access a response’s content without reading first.

This error is marked as provisional, meaning it may be changed in a future release. It is thrown if you try to access an ~azure.core.rest.HttpResponse or ~azure.core.rest.AsyncHttpResponse’s content without first reading the response’s bytes in first.

exception azure.core.exceptions.ServiceRequestError(message, *args, **kwargs)[source]

An error occurred while attempt to make a request to the service. No request was sent.

exception azure.core.exceptions.ServiceResponseError(message, *args, **kwargs)[source]

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

exception azure.core.exceptions.StreamClosedError(response)[source]

Provisional error thrown if you try to access the stream of a response once closed.

This error is marked as provisional, meaning it may be changed in a future release. It is thrown if you try to read / stream an ~azure.core.rest.HttpResponse or ~azure.core.rest.AsyncHttpResponse once the response’s stream has been closed.

exception azure.core.exceptions.StreamConsumedError(response)[source]

Provisional error thrown if you try to access the stream of a response once consumed.

This error is marked as provisional, meaning it may be changed in a future release. It is thrown if you try to read / stream an ~azure.core.rest.HttpResponse or ~azure.core.rest.AsyncHttpResponse once the response’s stream has been consumed.

exception azure.core.exceptions.TooManyRedirectsError(history, *args, **kwargs)[source]

Reached the maximum number of redirect attempts.

class azure.core.exceptions.ODataV4Format(json_object)[source]

Class to describe OData V4 error format.

http://docs.oasis-open.org/odata/odata-json-format/v4.0/os/odata-json-format-v4.0-os.html#_Toc372793091

Example of JSON:

error: {

“code”: “ValidationError”, “message”: “One or more fields contain incorrect values: “, “details”: [

{

“code”: “ValidationError”, “target”: “representation”, “message”: “Parsing error(s): String ‘’ does not match regex pattern ‘^[^{}/ :]+(?: :\d+)?$’. Path ‘host’, line 1, position 297.”

}, {

“code”: “ValidationError”, “target”: “representation”, “message”: “Parsing error(s): The input OpenAPI file is not valid for the OpenAPI specificate https: //github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md (schema https://github.com/OAI/OpenAPI-Specification/blob/master/schemas/v2.0/schema.json).”

}

]

}

Parameters

json_object (dict) – A Python dict representing a ODataV4 JSON

Variables
  • code (str) – Its value is a service-defined error code. This code serves as a sub-status for the HTTP error code specified in the response.

  • message (str) – Human-readable, language-dependent representation of the error.

  • target (str) – The target of the particular error (for example, the name of the property in error). This field is optional and may be None.

  • details (list[ODataV4Format]) – Array of ODataV4Format instances that MUST contain name/value pairs for code and message, and MAY contain a name/value pair for target, as described above.

  • innererror (dict) – An object. The contents of this object are service-defined. Usually this object contains information that will help debug the service.

message_details()[source]

Return a detailled string of the error.

CODE_LABEL = 'code'
DETAILS_LABEL = 'details'
INNERERROR_LABEL = 'innererror'
MESSAGE_LABEL = 'message'
TARGET_LABEL = 'target'
property error

azure.core.messaging

class azure.core.messaging.CloudEvent(source: str, type: str, **kwargs: Any)[source]

Properties of the CloudEvent 1.0 Schema. All required parameters must be populated in order to send to Azure.

Parameters
  • source (str) – Required. Identifies the context in which an event happened. The combination of id and source must be unique for each distinct event. If publishing to a domain topic, source must be the domain name.

  • type (str) – Required. Type of event related to the originating occurrence.

Keyword Arguments
  • data – Optional. Event data specific to the event type.

  • time – Optional. The time (in UTC) the event was generated.

  • dataschema – Optional. Identifies the schema that data adheres to.

  • datacontenttype – Optional. Content type of data value.

  • subject – Optional. This describes the subject of the event in the context of the event producer (identified by source).

  • specversion – Optional. The version of the CloudEvent spec. Defaults to “1.0”

  • id – Optional. An identifier for the event. The combination of id and source must be unique for each distinct event. If not provided, a random UUID will be generated and used.

  • extensions – Optional. A CloudEvent MAY include any number of additional context attributes with distinct names represented as key - value pairs. Each extension must be alphanumeric, lower cased and must not exceed the length of 20 characters.

Variables
  • source (str) – Identifies the context in which an event happened. The combination of id and source must be unique for each distinct event. If publishing to a domain topic, source must be the domain name.

  • data (object) – Event data specific to the event type.

  • type (str) – Type of event related to the originating occurrence.

  • time (datetime) – The time (in UTC) the event was generated.

  • dataschema (str) – Identifies the schema that data adheres to.

  • datacontenttype (str) – Content type of data value.

  • subject (str) – This describes the subject of the event in the context of the event producer (identified by source).

  • specversion (str) – Optional. The version of the CloudEvent spec. Defaults to “1.0”

  • id (str) – An identifier for the event. The combination of id and source must be unique for each distinct event. If not provided, a random UUID will be generated and used.

  • extensions (Dict) – A CloudEvent MAY include any number of additional context attributes with distinct names represented as key - value pairs. Each extension must be alphanumeric, lower cased and must not exceed the length of 20 characters.

classmethod from_dict(event: Dict)CloudEvent[source]

Returns the deserialized CloudEvent object when a dict is provided. :param event: The dict representation of the event which needs to be deserialized. :type event: dict :rtype: CloudEvent

classmethod from_json(event: Any)CloudEvent[source]

Returns the deserialized CloudEvent object when a json payload is provided. :param event: The json string that should be converted into a CloudEvent. This can also be

a storage QueueMessage, eventhub’s EventData or ServiceBusMessage

Return type

CloudEvent

Raises

ValueError – If the provided JSON is invalid.

azure.core.paging

class azure.core.paging.ItemPaged(*args, **kwargs)[source]

Return an iterator of items.

args and kwargs will be passed to the PageIterator constructor directly, except page_iterator_class

by_page(continuation_token: Optional[str] = None)Iterator[Iterator[ReturnType]][source]

Get an iterator of pages of objects, instead of an iterator of objects.

Parameters

continuation_token (str) – An opaque continuation token. This value can be retrieved from the continuation_token field of a previous generator object. If specified, this generator will begin returning results from this point.

Returns

An iterator of pages (themselves iterator of objects)

next()

Return the next item from the iterator. When exhausted, raise StopIteration

class azure.core.paging.PageIterator(get_next, extract_data, continuation_token=None)[source]

Return an iterator of pages.

Parameters
  • get_next – Callable that take the continuation token and return a HTTP response

  • extract_data – Callable that take an HTTP response and return a tuple continuation token, list of ReturnType

  • continuation_token (str) – The continuation token needed by get_next

next()Iterator[ReturnType]

Return the next item from the iterator. When exhausted, raise StopIteration

azure.core.settings

Provide access to settings for globally used Azure configuration values.

class azure.core.settings.Settings[source]

Settings for globally used Azure configuration values.

You probably don’t want to create an instance of this class, but call the singleton instance:

from azure.common.settings import settings
settings.log_level = log_level = logging.DEBUG

The following methods are searched in order for a setting:

4. immediate values 3. previously user-set value 2. environment variable 1. system setting 0. implicit default

An implicit default is (optionally) defined by the setting attribute itself.

A system setting value can be obtained from registries or other OS configuration for settings that support that method.

An environment variable value is obtained from os.environ

User-set values many be specified by assigning to the attribute:

settings.log_level = log_level = logging.DEBUG

Immediate values are (optionally) provided when the setting is retrieved:

settings.log_level(logging.DEBUG())

Immediate values are most often useful to provide from optional arguments to client functions. If the argument value is not None, it will be returned as-is. Otherwise, the setting searches other methods according to the precedence rules.

Immutable configuration snapshots can be created with the following methods:

  • settings.defaults returns the base defaultsvalues , ignoring any environment or system or user settings

  • settings.current returns the current computation of settings including prioritizatiom of configuration sources, unless defaults_only is set to True (in which case the result is identical to settings.defaults)

  • settings.config can be called with specific values to override what settings.current would provide

# return current settings with log level overridden
settings.config(log_level=logging.DEBUG)
Variables
  • log_level – a log level to use across all Azure client SDKs (AZURE_LOG_LEVEL)

  • tracing_enabled – Whether tracing should be enabled across Azure SDKs (AZURE_TRACING_ENABLED)

  • tracing_implementation – The tracing implementation to use (AZURE_SDK_TRACING_IMPLEMENTATION)

Example

>>> import logging
>>> from azure.core.settings import settings
>>> settings.log_level = logging.DEBUG
>>> settings.log_level()
10
>>> settings.log_level(logging.WARN)
30
config(**kwargs)[source]

Return the currently computed settings, with values overridden by parameter values.

Examples:

# return current settings with log level overridden
settings.config(log_level=logging.DEBUG)
property current

Return the current values for all settings.

Return type

namedtuple

property defaults

Return implicit default values for all settings, ignoring environment and system.

Return type

namedtuple

property defaults_only

Whether to ignore environment and system settings and return only base default values.

Return type

bool

log_level

Return a value for a global setting according to configuration precedence.

The following methods are searched in order for the setting:

4. immediate values 3. previously user-set value 2. environment variable 1. system setting 0. implicit default

If a value cannot be determined, a RuntimeError is raised.

The env_var argument specifies the name of an environment to check for setting values, e.g. "AZURE_LOG_LEVEL".

The optional system_hook can be used to specify a function that will attempt to look up a value for the setting from system-wide configurations.

The optional default argument specified an implicit default value for the setting that is returned if no other methods provide a value.

A convert agument may be provided to convert values before they are returned. For instance to concert log levels in environment variables to logging module values.

tracing_enabled

Return a value for a global setting according to configuration precedence.

The following methods are searched in order for the setting:

4. immediate values 3. previously user-set value 2. environment variable 1. system setting 0. implicit default

If a value cannot be determined, a RuntimeError is raised.

The env_var argument specifies the name of an environment to check for setting values, e.g. "AZURE_LOG_LEVEL".

The optional system_hook can be used to specify a function that will attempt to look up a value for the setting from system-wide configurations.

The optional default argument specified an implicit default value for the setting that is returned if no other methods provide a value.

A convert agument may be provided to convert values before they are returned. For instance to concert log levels in environment variables to logging module values.

tracing_implementation

Return a value for a global setting according to configuration precedence.

The following methods are searched in order for the setting:

4. immediate values 3. previously user-set value 2. environment variable 1. system setting 0. implicit default

If a value cannot be determined, a RuntimeError is raised.

The env_var argument specifies the name of an environment to check for setting values, e.g. "AZURE_LOG_LEVEL".

The optional system_hook can be used to specify a function that will attempt to look up a value for the setting from system-wide configurations.

The optional default argument specified an implicit default value for the setting that is returned if no other methods provide a value.

A convert agument may be provided to convert values before they are returned. For instance to concert log levels in environment variables to logging module values.

azure.core.settings.settings = <azure.core.settings.Settings object>

The settings unique instance.

azure.core.serialization

class azure.core.serialization.AzureJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

A JSON encoder that’s capable of serializing datetime objects and bytes.

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (‘, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

default(o)[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)
encode(o)

Return a JSON string representation of a Python data structure.

>>> from json.encoder import JSONEncoder
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
iterencode(o, _one_shot=False)

Encode the given object and yield each string representation as available.

For example:

for chunk in JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)
item_separator = ', '
key_separator = ': '
azure.core.serialization.NULL = <azure.core.serialization._Null object>

A falsy sentinel object which is supposed to be used to specify attributes with no data. This gets serialized to null on the wire.

azure.core.rest

*THIS MODULE IS PROVISIONAL*

This module is *provisional*, meaning any of the objects and methods in this module may be changed.

class azure.core.rest.AsyncHttpResponse(*, request: azure.core.rest._rest_py3.HttpRequest, **kwargs)[source]

Provisional object that represents an Async HTTP response.

This object is provisional, meaning it may be changed in a future release.

It is returned from your async client’s send_request method if you pass in an HttpRequest

>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest('GET', 'http://www.example.com')
<HttpRequest [GET], url: 'http://www.example.com'>
>>> response = await client.send_request(request)
<AsyncHttpResponse: 200 OK>
Keyword Arguments

request (HttpRequest) – The request that resulted in this response.

Variables
  • status_code (int) – The status code of this response

  • headers (mapping) – The response headers

  • reason (str) – The reason phrase for this response

  • content (bytes) – The response content in bytes.

  • url (str) – The URL that resulted in this response

  • encoding (str) – The response encoding. Is settable, by default is the response Content-Type header

  • text (str) – The response body as a string.

  • request (HttpRequest) – The request that resulted in this response.

  • content_type (str) – The content type of the response

  • is_closed (bool) – Whether the network connection has been closed yet

  • is_stream_consumed (bool) – When getting a stream response, checks whether the stream has been fully consumed

async close()None[source]

Close the response.

Returns

None

Return type

None

iter_bytes()AsyncIterator[bytes][source]

Asynchronously iterates over the response’s bytes. Will decompress in the process

Returns

An async iterator of bytes from the response

Return type

AsyncIterator[bytes]

iter_raw()AsyncIterator[bytes][source]

Asynchronously iterates over the response’s bytes. Will not decompress in the process

Returns

An async iterator of bytes from the response

Return type

AsyncIterator[bytes]

json()Any

Returns the whole body as a json object.

Returns

The JSON deserialized response body

Return type

any

Raises

json.decoder.JSONDecodeError or ValueError (in python 2.7) if object is not JSON decodable

raise_for_status()None

Raises an HttpResponseError if the response has an error status code.

If response is good, does nothing.

async read()bytes[source]

Read the response’s bytes into memory.

Returns

The response’s bytes

Return type

bytes

text(encoding: Optional[str] = None)str

Returns the response body as a string

Parameters

encoding (optional[str]) – The encoding you want to decode the text with. Can also be set independently through our encoding property

Returns

The response’s content decoded as a string.

property content

Return the response’s content in bytes.

property encoding

Returns the response encoding.

Returns

The response encoding. We either return the encoding set by the user, or try extracting the encoding from the response’s content type. If all fails, we return None.

Return type

optional[str]

property url

Returns the URL that resulted in this response

class azure.core.rest.HttpRequest(method: str, url: str, *, params: Optional[Mapping[str, Union[str, int, float, None, Sequence[Optional[Union[str, int, float]]]]]] = None, headers: Optional[Mapping[str, str]] = None, json: Optional[Any] = None, content: Optional[Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]] = None, data: Optional[dict] = None, files: Optional[Union[Mapping[str, Tuple[Optional[str], Union[str, bytes, IO[str], IO[bytes]]]], Sequence[Tuple[str, Tuple[Optional[str], Union[str, bytes, IO[str], IO[bytes]]]]]]] = None, **kwargs)[source]

Provisional object that represents an HTTP request.

This object is provisional, meaning it may be changed in a future release.

It should be passed to your client’s send_request method.

>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest('GET', 'http://www.example.com')
<HttpRequest [GET], url: 'http://www.example.com'>
>>> response = client.send_request(request)
<HttpResponse: 200 OK>
Parameters
  • method (str) – HTTP method (GET, HEAD, etc.)

  • url (str) – The url for your request

Keyword Arguments
  • params (mapping) – Query parameters to be mapped into your URL. Your input should be a mapping of query name to query value(s).

  • headers (mapping) – HTTP headers you want in your request. Your input should be a mapping of header name to header value.

  • json (any) – A JSON serializable object. We handle JSON-serialization for your object, so use this for more complicated data structures than data.

  • content (str or bytes or iterable[bytes] or asynciterable[bytes]) – Content you want in your request body. Think of it as the kwarg you should input if your data doesn’t fit into json, data, or files. Accepts a bytes type, or a generator that yields bytes.

  • data (dict) – Form data you want in your request body. Use for form-encoded data, i.e. HTML forms.

  • files (mapping) – Files you want to in your request body. Use for uploading files with multipart encoding. Your input should be a mapping of file name to file content. Use the data kwarg in addition if you want to include non-file data files as part of your request.

Variables
  • url (str) – The URL this request is against.

  • method (str) – The method type of this request.

  • headers (mapping) – The HTTP headers you passed in to your request

  • content (any) – The content passed in for the request

property content

Get’s the request’s content

Returns

The request’s content

Return type

any

class azure.core.rest.HttpResponse(*, request: azure.core.rest._rest_py3.HttpRequest, **kwargs)[source]

Provisional object that represents an HTTP response.

This object is provisional, meaning it may be changed in a future release.

It is returned from your client’s send_request method if you pass in an HttpRequest

>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest('GET', 'http://www.example.com')
<HttpRequest [GET], url: 'http://www.example.com'>
>>> response = client.send_request(request)
<HttpResponse: 200 OK>
Keyword Arguments

request (HttpRequest) – The request that resulted in this response.

Variables
  • status_code (int) – The status code of this response

  • headers (mapping) – The case-insensitive response headers. While looking up headers is case-insensitive, when looking up keys in header.keys(), we recommend using lowercase.

  • reason (str) – The reason phrase for this response

  • content (bytes) – The response content in bytes.

  • url (str) – The URL that resulted in this response

  • encoding (str) – The response encoding. Is settable, by default is the response Content-Type header

  • text (str) – The response body as a string.

  • request (HttpRequest) – The request that resulted in this response.

  • content_type (str) – The content type of the response

  • is_closed (bool) – Whether the network connection has been closed yet

  • is_stream_consumed (bool) – When getting a stream response, checks whether the stream has been fully consumed

close()None[source]

Close the response

Returns

None

Return type

None

iter_bytes()Iterator[bytes][source]

Iterates over the response’s bytes. Will decompress in the process

Returns

An iterator of bytes from the response

Return type

Iterator[str]

iter_raw()Iterator[bytes][source]

Iterates over the response’s bytes. Will not decompress in the process

Returns

An iterator of bytes from the response

Return type

Iterator[str]

json()Any

Returns the whole body as a json object.

Returns

The JSON deserialized response body

Return type

any

Raises

json.decoder.JSONDecodeError or ValueError (in python 2.7) if object is not JSON decodable

raise_for_status()None

Raises an HttpResponseError if the response has an error status code.

If response is good, does nothing.

read()bytes[source]

Read the response’s bytes.

Returns

The read in bytes

Return type

bytes

text(encoding: Optional[str] = None)str

Returns the response body as a string

Parameters

encoding (optional[str]) – The encoding you want to decode the text with. Can also be set independently through our encoding property

Returns

The response’s content decoded as a string.

property content

Return the response’s content in bytes.

property encoding

Returns the response encoding.

Returns

The response encoding. We either return the encoding set by the user, or try extracting the encoding from the response’s content type. If all fails, we return None.

Return type

optional[str]

property url

Returns the URL that resulted in this response