azure-core¶
- class azure.core.AsyncPipelineClient(base_url: str, *, pipeline: AsyncPipeline[HTTPRequestType, AsyncHTTPResponseType] | None = None, config: Configuration[HTTPRequestType, AsyncHTTPResponseType] | None = None, **kwargs: Any)[source]¶
Service client core methods.
Builds an AsyncPipeline client.
- Parameters:
base_url (str) – URL for the request.
- Keyword Arguments:
config (Configuration) – If omitted, the standard configuration is used.
pipeline (Pipeline) – If omitted, a Pipeline object is created and returned.
policies (list[AsyncHTTPPolicy]) – If omitted, the standard policies of the configuration object is used.
per_call_policies (Union[AsyncHTTPPolicy, SansIOHTTPPolicy, list[AsyncHTTPPolicy], list[SansIOHTTPPolicy]]) – If specified, the policies will be added into the policy list before RetryPolicy
per_retry_policies (Union[AsyncHTTPPolicy, SansIOHTTPPolicy, list[AsyncHTTPPolicy], list[SansIOHTTPPolicy]]) – If specified, the policies will be added into the policy list after RetryPolicy
transport (AsyncHttpTransport) – If omitted, AioHttpTransport is used for asynchronous transport.
- Returns:
An async pipeline object.
- Return type:
Example:
from azure.core import AsyncPipelineClient from azure.core.pipeline.policies import AsyncRedirectPolicy, UserAgentPolicy from azure.core.rest import HttpRequest # example policies request = HttpRequest("GET", url) policies: Iterable[Union[AsyncHTTPPolicy, SansIOHTTPPolicy]] = [ UserAgentPolicy("myuseragent"), AsyncRedirectPolicy(), ] async with AsyncPipelineClient[HttpRequest, AsyncHttpResponse](base_url=url, policies=policies) as client: response = await client.send_request(request)
- delete(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, content: Any = None, form_content: Dict[str, Any] | None = None) HttpRequest ¶
Create a DELETE request object.
- format_url(url_template: str, **kwargs: Any) str ¶
Format request URL with the client base URL, unless the supplied URL is already absolute.
Note that both the base url and the template url can contain query parameters.
- get(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, content: Any = None, form_content: Dict[str, Any] | None = None) HttpRequest ¶
Create a GET request object.
- head(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, content: Any = None, form_content: Dict[str, Any] | None = None, stream_content: Any = None) HttpRequest ¶
Create a HEAD request object.
- Parameters:
- Returns:
An HttpRequest object
- Return type:
- merge(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, content: Any = None, form_content: Dict[str, Any] | None = None) HttpRequest ¶
Create a MERGE request object.
- options(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, *, content: bytes | str | Dict[Any, Any] | None = None, form_content: Dict[Any, Any] | None = None, **kwargs: Any) HttpRequest ¶
Create a OPTIONS request object.
- Parameters:
- Keyword Arguments:
content – The body content
form_content (dict) – Form content
- Returns:
An HttpRequest object
- Return type:
- patch(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, content: Any = None, form_content: Dict[str, Any] | None = None, stream_content: Any = None) HttpRequest ¶
Create a PATCH request object.
- Parameters:
- Returns:
An HttpRequest object
- Return type:
- post(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, content: Any = None, form_content: Dict[str, Any] | None = None, stream_content: Any = None) HttpRequest ¶
Create a POST request object.
- Parameters:
- Returns:
An HttpRequest object
- Return type:
- put(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, content: Any = None, form_content: Dict[str, Any] | None = None, stream_content: Any = None) HttpRequest ¶
Create a PUT request object.
- Parameters:
- Returns:
An HttpRequest object
- Return type:
- send_request(request: HTTPRequestType, *, stream: bool = False, **kwargs: Any) Awaitable[AsyncHTTPResponseType] [source]¶
Method that runs the network request through the client’s chained policies.
>>> 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:
- class azure.core.AzureClouds(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
An enum to describe Azure Cloud.
- capitalize()¶
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()¶
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)¶
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int ¶
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')¶
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool ¶
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)¶
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int ¶
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str ¶
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str ¶
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int ¶
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()¶
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()¶
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()¶
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()¶
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()¶
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()¶
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()¶
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()¶
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()¶
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()¶
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()¶
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()¶
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)¶
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)¶
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()¶
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)¶
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()¶
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)¶
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)¶
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)¶
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)¶
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int ¶
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int ¶
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)¶
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)¶
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)¶
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)¶
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)¶
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)¶
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool ¶
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)¶
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()¶
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()¶
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)¶
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()¶
Return a copy of the string converted to uppercase.
- zfill(width, /)¶
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- AZURE_CHINA_CLOUD = 'AZURE_CHINA_CLOUD'¶
Azure China cloud
- AZURE_PUBLIC_CLOUD = 'AZURE_PUBLIC_CLOUD'¶
Azure public cloud
- AZURE_US_GOVERNMENT = 'AZURE_US_GOVERNMENT'¶
Azure US government cloud
- class azure.core.CaseInsensitiveEnumMeta(cls, bases, classdict, *, boundary=None, _simple=False, **kwds)[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 azure.core import CaseInsensitiveEnumMeta class MyCustomEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): FOO = 'foo' BAR = 'bar'
- mro()¶
Return a type’s method resolution order.
- class azure.core.MatchConditions(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
An enum to describe match conditions.
- IfMissing = 5¶
If the target object does not exist. Usually it maps to etag!=’*’
- IfModified = 3¶
Only if the target object is modified. Usually it maps to etag!=<specific etag>
- IfNotModified = 2¶
If the target object is not modified. Usually it maps to etag=<specific etag>
- IfPresent = 4¶
If the target object exists. Usually it maps to etag=’*’
- Unconditionally = 1¶
Matches any condition
- class azure.core.PipelineClient(base_url: str, *, pipeline: Pipeline[HTTPRequestType, HTTPResponseType] | None = None, config: Configuration[HTTPRequestType, HTTPResponseType] | None = None, **kwargs: Any)[source]¶
Service client core methods.
Builds a Pipeline client.
- Parameters:
base_url (str) – URL for the request.
- Keyword Arguments:
config (Configuration) – If omitted, the standard configuration is used.
pipeline (Pipeline) – If omitted, a Pipeline object is created and returned.
policies (list[HTTPPolicy]) – If omitted, the standard policies of the configuration object is used.
per_call_policies (Union[HTTPPolicy, SansIOHTTPPolicy, list[HTTPPolicy], list[SansIOHTTPPolicy]]) – If specified, the policies will be added into the policy list before RetryPolicy
per_retry_policies (Union[HTTPPolicy, SansIOHTTPPolicy, list[HTTPPolicy], list[SansIOHTTPPolicy]]) – If specified, the policies will be added into the policy list after RetryPolicy
transport (HttpTransport) – If omitted, RequestsTransport is used for synchronous transport.
- Returns:
A pipeline object.
- Return type:
Example:
from azure.core import PipelineClient from azure.core.rest import HttpRequest from azure.core.pipeline.policies import RedirectPolicy, UserAgentPolicy # example configuration with some policies policies: Iterable[Union[HTTPPolicy, SansIOHTTPPolicy]] = [UserAgentPolicy("myuseragent"), RedirectPolicy()] client: PipelineClient[HttpRequest, HttpResponse] = PipelineClient(base_url=url, policies=policies) request = HttpRequest("GET", "https://bing.com") pipeline_response = client._pipeline.run(request)
- delete(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, content: Any = None, form_content: Dict[str, Any] | None = None) HttpRequest ¶
Create a DELETE request object.
- format_url(url_template: str, **kwargs: Any) str ¶
Format request URL with the client base URL, unless the supplied URL is already absolute.
Note that both the base url and the template url can contain query parameters.
- get(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, content: Any = None, form_content: Dict[str, Any] | None = None) HttpRequest ¶
Create a GET request object.
- head(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, content: Any = None, form_content: Dict[str, Any] | None = None, stream_content: Any = None) HttpRequest ¶
Create a HEAD request object.
- Parameters:
- Returns:
An HttpRequest object
- Return type:
- merge(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, content: Any = None, form_content: Dict[str, Any] | None = None) HttpRequest ¶
Create a MERGE request object.
- options(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, *, content: bytes | str | Dict[Any, Any] | None = None, form_content: Dict[Any, Any] | None = None, **kwargs: Any) HttpRequest ¶
Create a OPTIONS request object.
- Parameters:
- Keyword Arguments:
content – The body content
form_content (dict) – Form content
- Returns:
An HttpRequest object
- Return type:
- patch(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, content: Any = None, form_content: Dict[str, Any] | None = None, stream_content: Any = None) HttpRequest ¶
Create a PATCH request object.
- Parameters:
- Returns:
An HttpRequest object
- Return type:
- post(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, content: Any = None, form_content: Dict[str, Any] | None = None, stream_content: Any = None) HttpRequest ¶
Create a POST request object.
- Parameters:
- Returns:
An HttpRequest object
- Return type:
- put(url: str, params: Dict[str, str] | None = None, headers: Dict[str, str] | None = None, content: Any = None, form_content: Dict[str, Any] | None = None, stream_content: Any = None) HttpRequest ¶
Create a PUT request object.
- Parameters:
- Returns:
An HttpRequest object
- Return type:
- send_request(request: HTTPRequestType, *, stream: bool = False, **kwargs: Any) HTTPResponseType [source]¶
Method that runs the network request through the client’s chained policies.
>>> 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:
Subpackages¶
- azure.core.pipeline
AsyncPipeline
Pipeline
PipelineContext
PipelineRequest
PipelineResponse
- Subpackages
- azure.core.pipeline.policies
AsyncBearerTokenCredentialPolicy
AsyncBearerTokenCredentialPolicy.authorize_request()
AsyncBearerTokenCredentialPolicy.on_challenge()
AsyncBearerTokenCredentialPolicy.on_exception()
AsyncBearerTokenCredentialPolicy.on_request()
AsyncBearerTokenCredentialPolicy.on_response()
AsyncBearerTokenCredentialPolicy.send()
AsyncBearerTokenCredentialPolicy.next
AsyncHTTPPolicy
AsyncRedirectPolicy
AsyncRetryPolicy
AsyncRetryPolicy.configure_retries()
AsyncRetryPolicy.get_backoff_time()
AsyncRetryPolicy.get_retry_after()
AsyncRetryPolicy.increment()
AsyncRetryPolicy.is_exhausted()
AsyncRetryPolicy.is_retry()
AsyncRetryPolicy.no_retries()
AsyncRetryPolicy.parse_retry_after()
AsyncRetryPolicy.send()
AsyncRetryPolicy.sleep()
AsyncRetryPolicy.update_context()
AsyncRetryPolicy.BACKOFF_MAX
AsyncRetryPolicy.next
AzureKeyCredentialPolicy
AzureSasCredentialPolicy
BearerTokenCredentialPolicy
ContentDecodePolicy
CustomHookPolicy
DistributedTracingPolicy
HTTPPolicy
HeadersPolicy
HttpLoggingPolicy
NetworkTraceLoggingPolicy
ProxyPolicy
RedirectPolicy
RequestHistory
RequestIdPolicy
RetryMode
RetryMode.capitalize()
RetryMode.casefold()
RetryMode.center()
RetryMode.count()
RetryMode.encode()
RetryMode.endswith()
RetryMode.expandtabs()
RetryMode.find()
RetryMode.format()
RetryMode.format_map()
RetryMode.index()
RetryMode.isalnum()
RetryMode.isalpha()
RetryMode.isascii()
RetryMode.isdecimal()
RetryMode.isdigit()
RetryMode.isidentifier()
RetryMode.islower()
RetryMode.isnumeric()
RetryMode.isprintable()
RetryMode.isspace()
RetryMode.istitle()
RetryMode.isupper()
RetryMode.join()
RetryMode.ljust()
RetryMode.lower()
RetryMode.lstrip()
RetryMode.maketrans()
RetryMode.partition()
RetryMode.removeprefix()
RetryMode.removesuffix()
RetryMode.replace()
RetryMode.rfind()
RetryMode.rindex()
RetryMode.rjust()
RetryMode.rpartition()
RetryMode.rsplit()
RetryMode.rstrip()
RetryMode.split()
RetryMode.splitlines()
RetryMode.startswith()
RetryMode.strip()
RetryMode.swapcase()
RetryMode.title()
RetryMode.translate()
RetryMode.upper()
RetryMode.zfill()
RetryMode.Exponential
RetryMode.Fixed
RetryPolicy
RetryPolicy.configure_retries()
RetryPolicy.get_backoff_time()
RetryPolicy.get_retry_after()
RetryPolicy.increment()
RetryPolicy.is_exhausted()
RetryPolicy.is_retry()
RetryPolicy.no_retries()
RetryPolicy.parse_retry_after()
RetryPolicy.send()
RetryPolicy.sleep()
RetryPolicy.update_context()
RetryPolicy.BACKOFF_MAX
RetryPolicy.next
SansIOHTTPPolicy
SensitiveHeaderCleanupPolicy
UserAgentPolicy
- azure.core.pipeline.transport
AioHttpTransport
AioHttpTransportResponse
AsyncHttpResponse
AsyncHttpTransport
AsyncioRequestsTransport
AsyncioRequestsTransportResponse
HttpRequest
HttpRequest.format_parameters()
HttpRequest.prepare_multipart_body()
HttpRequest.serialize()
HttpRequest.set_bytes_body()
HttpRequest.set_formdata_body()
HttpRequest.set_json_body()
HttpRequest.set_multipart_mixed()
HttpRequest.set_streamed_data_body()
HttpRequest.set_text_body()
HttpRequest.set_xml_body()
HttpRequest.body
HttpRequest.query
HttpResponse
HttpTransport
RequestsTransport
RequestsTransportResponse
TrioRequestsTransport
TrioRequestsTransportResponse
- azure.core.pipeline.policies
- 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¶
- class azure.core.async_paging.AsyncItemPaged(*args: Any, **kwargs: Any)[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: str | None = 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)
- Return type:
AsyncIterator[AsyncIterator[ReturnType]]
- class azure.core.async_paging.AsyncPageIterator(get_next: Callable[[str | None], Awaitable[ResponseType]], extract_data: Callable[[ResponseType], Awaitable[Tuple[str, AsyncIterator[ReturnType]]]], continuation_token: str | None = 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: str, expires_on: int)[source]¶
Represents an OAuth access token.
Create new instance of AccessToken(token, expires_on)
- count(value, /)¶
Return number of occurrences of value.
- index(value, start=0, stop=9223372036854775807, /)¶
Return first index of value.
Raises ValueError if the value is not present.
- class azure.core.credentials.AccessTokenInfo(token: str, expires_on: int, *, token_type: str = 'Bearer', refresh_on: int | None = None)[source]¶
Information about an OAuth access token.
This class is an alternative to AccessToken which provides additional information about the token.
- Parameters:
- Keyword Arguments:
- 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
- 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:
- 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.
- property named_key: AzureNamedKey¶
The value of the configured name.
- Return type:
AzureNamedKey
- Returns:
The value of the configured name.
- 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
- class azure.core.credentials.SupportsTokenInfo(*args, **kwargs)[source]¶
Protocol for classes able to provide OAuth access tokens with additional properties.
- get_token_info(*scopes: str, options: TokenRequestOptions | None = None) AccessTokenInfo [source]¶
Request an access token for scopes.
This is an alternative to get_token to enable certain scenarios that require additional properties on the token.
- Parameters:
scopes (str) – The type of access needed.
- Keyword Arguments:
options (TokenRequestOptions) – A dictionary of options for the token request. Unknown options will be ignored. Optional.
- Return type:
- Returns:
An AccessTokenInfo instance containing information about the token.
- class azure.core.credentials.TokenCredential(*args, **kwargs)[source]¶
Protocol for classes able to provide OAuth tokens.
- get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, enable_cae: bool = False, **kwargs: Any) AccessToken [source]¶
Request an access token for scopes.
- Parameters:
scopes (str) – The type of access needed.
- Keyword Arguments:
claims (str) – Additional claims required in the token, such as those returned in a resource provider’s claims challenge following an authorization failure.
tenant_id (str) – Optional tenant to include in the token request.
enable_cae (bool) – Indicates whether to enable Continuous Access Evaluation (CAE) for the requested token. Defaults to False.
- Return type:
- Returns:
An AccessToken instance containing the token string and its expiration time in Unix time.
- class azure.core.credentials.TokenRequestOptions[source]¶
Options to use for access token requests. All parameters are optional.
- clear() None. Remove all items from D. ¶
- copy() a shallow copy of D ¶
- fromkeys(value=None, /)¶
Create a new dictionary with keys from iterable and values set to value.
- get(key, default=None, /)¶
Return the value for key if key is in the dictionary, else default.
- items() a set-like object providing a view on D's items ¶
- keys() a set-like object providing a view on D's keys ¶
- pop(k[, d]) v, remove specified key and return the corresponding value. ¶
If the key is not found, return the default if given; otherwise, raise a KeyError.
- popitem()¶
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.
- setdefault(key, default=None, /)¶
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- update([E, ]**F) None. Update D from dict/iterable E and F. ¶
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- values() an object providing a view on D's values ¶
- claims: str¶
Additional claims required in the token, such as those returned in a resource provider’s claims challenge following an authorization failure.
azure.core.credentials_async¶
- class azure.core.credentials_async.AsyncSupportsTokenInfo(*args, **kwargs)[source]¶
Protocol for classes able to provide OAuth access tokens with additional properties.
- async get_token_info(*scopes: str, options: TokenRequestOptions | None = None) AccessTokenInfo [source]¶
Request an access token for scopes.
This is an alternative to get_token to enable certain scenarios that require additional properties on the token.
- Parameters:
scopes (str) – The type of access needed.
- Keyword Arguments:
options (TokenRequestOptions) – A dictionary of options for the token request. Unknown options will be ignored. Optional.
- Return type:
- Returns:
An AccessTokenInfo instance containing the token string and its expiration time in Unix time.
- class azure.core.credentials_async.AsyncTokenCredential(*args, **kwargs)[source]¶
Protocol for classes able to provide OAuth tokens.
- async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, enable_cae: bool = False, **kwargs: Any) AccessToken [source]¶
Request an access token for scopes.
- Parameters:
scopes (str) – The type of access needed.
- Keyword Arguments:
claims (str) – Additional claims required in the token, such as those returned in a resource provider’s claims challenge following an authorization failure.
tenant_id (str) – Optional tenant to include in the token request.
enable_cae (bool) – Indicates whether to enable Continuous Access Evaluation (CAE) for the requested token. Defaults to False.
- Return type:
- Returns:
An AccessToken instance containing the token string and its expiration time in Unix time.
azure.core.exceptions¶
- exception azure.core.exceptions.AzureError(message: object | None, *args: Any, **kwargs: Any)[source]¶
Base exception for all errors.
- Parameters:
message (object) – 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.
- exception azure.core.exceptions.ClientAuthenticationError(message: object | None = None, response: _HttpResponseCommonAPI | None = None, **kwargs: Any)[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: object | None = None, response: _HttpResponseCommonAPI | None = None, **kwargs: Any)[source]¶
Error raised during response deserialization.
- exception azure.core.exceptions.DeserializationError[source]¶
Raised if an error is encountered during deserialization.
- exception azure.core.exceptions.HttpResponseError(message: object | None = None, response: _HttpResponseCommonAPI | None = None, **kwargs: Any)[source]¶
A request was made, and a non-success status code was received from the service.
- Parameters:
message (object) – The message object stringified as ‘message’ attribute
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: _HttpResponseCommonAPI, **kwargs: Any)[source]¶
An HTTP response error where the JSON is decoded as OData V4 error format.
- Parameters:
response (HttpResponse) – The response object.
- 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: object | None = None, response: _HttpResponseCommonAPI | None = None, **kwargs: Any)[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: object | None = None, response: _HttpResponseCommonAPI | None = None, **kwargs: Any)[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: object | None = None, response: _HttpResponseCommonAPI | None = None, **kwargs: Any)[source]¶
An error response, typically triggered by a 412 response (for update) or 404 (for get/post)
- exception azure.core.exceptions.ResourceNotModifiedError(message: object | None = None, response: _HttpResponseCommonAPI | None = None, **kwargs: Any)[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: _HttpResponseCommonAPI)[source]¶
Error thrown if you try to access a response’s content without reading first.
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.
- Parameters:
response (HttpResponse or AsyncHttpResponse) – The response that triggered the exception.
- exception azure.core.exceptions.SerializationError[source]¶
Raised if an error is encountered during serialization.
- exception azure.core.exceptions.ServiceRequestError(message: object | None, *args: Any, **kwargs: Any)[source]¶
An error occurred while attempt to make a request to the service. No request was sent.
- exception azure.core.exceptions.ServiceResponseError(message: object | None, *args: Any, **kwargs: Any)[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: _HttpResponseCommonAPI)[source]¶
Error thrown if you try to access the stream of a response once closed.
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.
- Parameters:
response (HttpResponse or AsyncHttpResponse) – The response that triggered the exception.
- exception azure.core.exceptions.StreamConsumedError(response: _HttpResponseCommonAPI)[source]¶
Error thrown if you try to access the stream of a response once consumed.
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.
- Parameters:
response (HttpResponse or AsyncHttpResponse) – The response that triggered the exception.
- exception azure.core.exceptions.TooManyRedirectsError(history: List[RequestHistory[HTTPRequestType, HTTPResponseType]], *args: Any, **kwargs: Any)[source]¶
Reached the maximum number of redirect attempts.
- Parameters:
history (list[RequestHistory]) – The history of requests made while trying to fulfill the request.
- class azure.core.exceptions.ODataV4Format(json_object: Mapping[str, Any])[source]¶
Class to describe OData V4 error format.
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() str [source]¶
Return a detailed string of the error.
- Returns:
A string with the details of the error.
- Return type:
- CODE_LABEL = 'code'¶
- DETAILS_LABEL = 'details'¶
- INNERERROR_LABEL = 'innererror'¶
- MESSAGE_LABEL = 'message'¶
- TARGET_LABEL = 'target'¶
- property error: SelfODataV4Format¶
azure.core.messaging¶
- class azure.core.messaging.CloudEvent(source: str, type: str, *, specversion: str | None = None, id: str | None = None, time: ~datetime.datetime | None = <object object>, datacontenttype: str | None = None, dataschema: str | None = None, subject: str | None = None, data: ~azure.core.messaging.DataType | None = None, extensions: ~typing.Dict[str, ~typing.Any] | None = None, **kwargs: ~typing.Any)[source]¶
Properties of the CloudEvent 1.0 Schema. All required parameters must be populated in order to send to Azure.
- Parameters:
- Keyword Arguments:
specversion (str) – Optional. The version of the CloudEvent spec. Defaults to “1.0”
data (object) – Optional. Event data specific to the event type.
time (datetime) – Optional. The time (in UTC) the event was generated.
dataschema (str) – Optional. Identifies the schema that data adheres to.
datacontenttype (str) – Optional. Content type of data value.
subject (str) – Optional. This describes the subject of the event in the context of the event producer (identified by source).
id (Optional[str]) – 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[dict]) – 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.
- classmethod from_dict(event: Dict[str, Any]) CloudEvent[DataType] [source]¶
Returns the deserialized CloudEvent object when a dict is provided.
- Parameters:
event (dict) – The dict representation of the event which needs to be deserialized.
- Return type:
- Returns:
The deserialized CloudEvent object.
- classmethod from_json(event: Any) CloudEvent[DataType] [source]¶
Returns the deserialized CloudEvent object when a json payload is provided.
- Parameters:
event (object) – The json string that should be converted into a CloudEvent. This can also be a storage QueueMessage, eventhub’s EventData or ServiceBusMessage
- Return type:
- Returns:
The deserialized CloudEvent object.
- Raises:
ValueError – If the provided JSON is invalid.
- extensions: Dict[str, Any] | None¶
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.
- 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.
- 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 topic name.
azure.core.paging¶
- class azure.core.paging.ItemPaged(*args: Any, **kwargs: Any)[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: str | None = 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)
- Return type:
iterator[iterator[ReturnType]]
- next() ReturnType ¶
Return the next item from the iterator. When exhausted, raise StopIteration
- class azure.core.paging.PageIterator(get_next: Callable[[str | None], ResponseType], extract_data: Callable[[ResponseType], Tuple[str, Iterable[ReturnType]]], continuation_token: str | None = 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
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.core.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 prioritization 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: Any) Tuple[Any, ...] [source]¶
Return the currently computed settings, with values overridden by parameter values.
- Return type:
namedtuple
- Returns:
The current values for all settings, with values overridden by parameter values
Examples:
# return current settings with log level overridden settings.config(log_level=logging.DEBUG)
- azure_cloud: PrioritizedSetting[str | AzureClouds, AzureClouds]¶
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"
. If aconvert
function is provided, the result will be converted before being used.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. If aconvert
function is provided, the hook result will be converted before being used.The optional
default
argument specified an implicit default value for the setting that is returned if no other methods provide a value. If aconvert
function is provided,default
will be converted before being used.A
convert
argument may be provided to convert values before they are returned. For instance to concert log levels in environment variables tologging
module values. If aconvert
function is provided, it must support str as valid input type.- Parameters:
name (str) – the name of the setting
env_var (str) – the name of an environment variable to check for the setting
system_hook (callable) – a function that will attempt to look up a value for the setting
default (any) – an implicit default value for the setting
convert (callable) – a function to convert values before they are returned
- property current: Tuple[Any, ...]¶
Return the current values for all settings.
- Return type:
namedtuple
- Returns:
The current values for all settings
- property defaults: Tuple[Any, ...]¶
Return implicit default values for all settings, ignoring environment and system.
- Return type:
namedtuple
- Returns:
The implicit default values for all settings
- property defaults_only: bool¶
Whether to ignore environment and system settings and return only base default values.
- Return type:
- Returns:
Whether to ignore environment and system settings and return only base default values.
- log_level: PrioritizedSetting[str | int, int]¶
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"
. If aconvert
function is provided, the result will be converted before being used.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. If aconvert
function is provided, the hook result will be converted before being used.The optional
default
argument specified an implicit default value for the setting that is returned if no other methods provide a value. If aconvert
function is provided,default
will be converted before being used.A
convert
argument may be provided to convert values before they are returned. For instance to concert log levels in environment variables tologging
module values. If aconvert
function is provided, it must support str as valid input type.- Parameters:
name (str) – the name of the setting
env_var (str) – the name of an environment variable to check for the setting
system_hook (callable) – a function that will attempt to look up a value for the setting
default (any) – an implicit default value for the setting
convert (callable) – a function to convert values before they are returned
- tracing_enabled: PrioritizedSetting[str | bool, bool]¶
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"
. If aconvert
function is provided, the result will be converted before being used.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. If aconvert
function is provided, the hook result will be converted before being used.The optional
default
argument specified an implicit default value for the setting that is returned if no other methods provide a value. If aconvert
function is provided,default
will be converted before being used.A
convert
argument may be provided to convert values before they are returned. For instance to concert log levels in environment variables tologging
module values. If aconvert
function is provided, it must support str as valid input type.- Parameters:
name (str) – the name of the setting
env_var (str) – the name of an environment variable to check for the setting
system_hook (callable) – a function that will attempt to look up a value for the setting
default (any) – an implicit default value for the setting
convert (callable) – a function to convert values before they are returned
- tracing_implementation: PrioritizedSetting[str | Type[AbstractSpan] | None, Type[AbstractSpan] | None]¶
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"
. If aconvert
function is provided, the result will be converted before being used.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. If aconvert
function is provided, the hook result will be converted before being used.The optional
default
argument specified an implicit default value for the setting that is returned if no other methods provide a value. If aconvert
function is provided,default
will be converted before being used.A
convert
argument may be provided to convert values before they are returned. For instance to concert log levels in environment variables tologging
module values. If aconvert
function is provided, it must support str as valid input type.- Parameters:
name (str) – the name of the setting
env_var (str) – the name of an environment variable to check for the setting
system_hook (callable) – a function that will attempt to look up a value for the setting
default (any) – an implicit default value for the setting
convert (callable) – a function to convert values before they are returned
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 RecursionError). 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: Any) Any [source]¶
Implement this method in a subclass such that it returns a serializable object for
o
, or calls the base implementation (to raise aTypeError
).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 super().default(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¶
- class azure.core.rest.AsyncHttpResponse[source]¶
Abstract base class for Async HTTP responses.
Use this abstract base class to create your own transport responses.
Responses implementing this ABC are 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>
- abstract async iter_bytes(**kwargs: Any) 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]
- abstract async iter_raw(**kwargs: Any) 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]
- abstract 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 –
- abstract raise_for_status() None ¶
Raises an HttpResponseError if the response has an error status code.
If response is good, does nothing.
- Raises:
–
- abstract async read() bytes [source]¶
Read the response’s bytes into memory.
- Returns:
The response’s bytes
- Return type:
- abstract property content: bytes¶
Return the response’s content in bytes.
- Return type:
- Returns:
The response’s content in bytes.
- abstract property content_type: str | None¶
The content type of the response.
- Return type:
- Returns:
The content type of the response.
- abstract property encoding: str | None¶
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]
- abstract property headers: MutableMapping[str, str]¶
The response headers. Must be case-insensitive.
- abstract property is_closed: bool¶
Whether the network connection has been closed yet.
- Return type:
- Returns:
Whether the network connection has been closed yet.
- abstract property is_stream_consumed: bool¶
Whether the stream has been consumed.
- Return type:
- Returns:
Whether the stream has been consumed.
- abstract property reason: str¶
The reason phrase for this response.
- Return type:
- Returns:
The reason phrase for this response.
- abstract property request: HttpRequest¶
The request that resulted in this response.
- Return type:
- Returns:
The request that resulted in this response.
- class azure.core.rest.HttpRequest(method: str, url: str, *, params: Mapping[str, str | int | float | bool | None | Sequence[str | int | float | bool | None]] | None = None, headers: MutableMapping[str, str] | None = None, json: Any = None, content: str | bytes | Iterable[bytes] | AsyncIterable[bytes] | None = None, data: Dict[str, Any] | None = None, files: Mapping[str, str | bytes | IO[str] | IO[bytes] | Tuple[str | None, str | bytes | IO[str] | IO[bytes]] | Tuple[str | None, str | bytes | IO[str] | IO[bytes], str | None]] | Sequence[Tuple[str, str | bytes | IO[str] | IO[bytes] | Tuple[str | None, str | bytes | IO[str] | IO[bytes]] | Tuple[str | None, str | bytes | IO[str] | IO[bytes], str | None]]] | None = None, **kwargs: Any)[source]¶
An HTTP request.
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:
- 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:
- class azure.core.rest.HttpResponse[source]¶
Abstract base class for HTTP responses.
Use this abstract base class to create your own transport responses.
Responses implementing this ABC are 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>
- abstract iter_bytes(**kwargs: Any) 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]
- abstract iter_raw(**kwargs: Any) 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]
- abstract 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 –
- abstract raise_for_status() None ¶
Raises an HttpResponseError if the response has an error status code.
If response is good, does nothing.
- Raises:
–
- abstract property content: bytes¶
Return the response’s content in bytes.
- Return type:
- Returns:
The response’s content in bytes.
- abstract property content_type: str | None¶
The content type of the response.
- Return type:
- Returns:
The content type of the response.
- abstract property encoding: str | None¶
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]
- abstract property headers: MutableMapping[str, str]¶
The response headers. Must be case-insensitive.
- abstract property is_closed: bool¶
Whether the network connection has been closed yet.
- Return type:
- Returns:
Whether the network connection has been closed yet.
- abstract property is_stream_consumed: bool¶
Whether the stream has been consumed.
- Return type:
- Returns:
Whether the stream has been consumed.
- abstract property reason: str¶
The reason phrase for this response.
- Return type:
- Returns:
The reason phrase for this response.
- abstract property request: HttpRequest¶
The request that resulted in this response.
- Return type:
- Returns:
The request that resulted in this response.
azure.core.utils¶
This utils module provides functionality that is intended to be used by developers building on top of azure-core.
- class azure.core.utils.CaseInsensitiveDict(data: Mapping[str, Any] | Iterable[Tuple[str, Any]] | None = None, **kwargs: Any)[source]¶
NOTE: This implementation is heavily inspired from the case insensitive dictionary from the requests library. Thank you !! Case insensitive dictionary implementation. The keys are expected to be strings and will be stored in lower case. case_insensitive_dict = CaseInsensitiveDict() case_insensitive_dict[‘Key’] = ‘some_value’ case_insensitive_dict[‘key’] == ‘some_value’ #True
- Parameters:
data (Mapping[str, Any] or Iterable[Tuple[str, Any]]) – Initial data to store in the dictionary.
- clear() None. Remove all items from D. ¶
- copy() CaseInsensitiveDict [source]¶
- get(k[, d]) D[k] if k in D, else d. d defaults to None. ¶
- items() a set-like object providing a view on D's items ¶
- keys() a set-like object providing a view on D's keys ¶
- pop(k[, d]) v, remove specified key and return the corresponding value. ¶
If key is not found, d is returned if given, otherwise KeyError is raised.
- popitem() (k, v), remove and return some (key, value) pair ¶
as a 2-tuple; but raise KeyError if D is empty.
- setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D ¶
- update([E, ]**F) None. Update D from mapping/iterable E and F. ¶
If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v
- values() an object providing a view on D's values ¶
- azure.core.utils.case_insensitive_dict(*args: Mapping[str, Any] | Iterable[Tuple[str, Any]] | None, **kwargs: Any) MutableMapping[str, Any] [source]¶
Return a case-insensitive mutable mapping from an inputted mapping structure.
- azure.core.utils.parse_connection_string(conn_str: str, case_sensitive_keys: bool = False) Mapping[str, str] [source]¶
Parses the connection string into a dict of its component parts, with the option of preserving case of keys, and validates that each key in the connection string has a provided value. If case of keys is not preserved (ie. case_sensitive_keys=False), then a dict with LOWERCASE KEYS will be returned.
- Parameters:
- Return type:
Mapping
- Returns:
Dict of connection string key/value pairs.
- Raises:
- ValueError: if each key in conn_str does not have a corresponding value and
for other bad formatting of connection strings - including duplicate args, bad syntax, etc.