diff --git a/sdk/appconfiguration/azure-appconfiguration/MANIFEST.in b/sdk/appconfiguration/azure-appconfiguration/MANIFEST.in index c33cc70f3bd4..0483ef9dcf83 100644 --- a/sdk/appconfiguration/azure-appconfiguration/MANIFEST.in +++ b/sdk/appconfiguration/azure-appconfiguration/MANIFEST.in @@ -1,7 +1,6 @@ -recursive-include tests *.py include *.md include LICENSE -include azure/__init__.py -recursive-include samples *.py *.md -recursive-include doc *.rst include azure/appconfiguration/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py \ No newline at end of file diff --git a/sdk/appconfiguration/azure-appconfiguration/_meta.json b/sdk/appconfiguration/azure-appconfiguration/_meta.json new file mode 100644 index 000000000000..084d36169e48 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/_meta.json @@ -0,0 +1,6 @@ +{ + "commit": "26af8eff710ea634da1b33fed369967d1c39b689", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/appconfiguration/AppConfiguration", + "@azure-tools/typespec-python": "0.36.1" +} \ No newline at end of file diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/__init__.py b/sdk/appconfiguration/azure-appconfiguration/azure/__init__.py index 8db66d3d0f0f..d55ccad1f573 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/__init__.py +++ b/sdk/appconfiguration/azure-appconfiguration/azure/__init__.py @@ -1 +1 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/__init__.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/__init__.py index 4dd855d6d711..e478141d10e9 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/__init__.py +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/__init__.py @@ -1,50 +1,32 @@ # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._azure_appconfiguration_client import AzureAppConfigurationClient -from ._constants import FILTER_PERCENTAGE, FILTER_TARGETING, FILTER_TIME_WINDOW -from ._models import ( - ConfigurationSetting, - FeatureFlagConfigurationSetting, - SecretReferenceConfigurationSetting, - ConfigurationSettingsFilter, - ConfigurationSnapshot, - ConfigurationSettingLabel, -) -from ._generated.models import ( - SnapshotStatus, - LabelFields, - SnapshotFields, - ConfigurationSettingFields, - SnapshotComposition, -) +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import AzureAppConfigurationClient # type: ignore from ._version import VERSION -from ._azure_appconfiguration_error import ResourceReadOnlyError __version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + __all__ = [ "AzureAppConfigurationClient", - "ConfigurationSetting", - "ResourceReadOnlyError", - "FeatureFlagConfigurationSetting", - "SecretReferenceConfigurationSetting", - "ConfigurationSnapshot", - "SnapshotStatus", - "SnapshotFields", - "SnapshotComposition", - "LabelFields", - "ConfigurationSettingFields", - "ConfigurationSettingsFilter", - "ConfigurationSettingLabel", - "FILTER_PERCENTAGE", - "FILTER_TARGETING", - "FILTER_TIME_WINDOW", ] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_azure_appconfiguration_client.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_azure_appconfiguration_client.py deleted file mode 100644 index 57c60a9230cf..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_azure_appconfiguration_client.py +++ /dev/null @@ -1,844 +0,0 @@ -# ------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ------------------------------------------------------------------------- -import functools -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, overload, cast -from azure.core import MatchConditions -from azure.core.paging import ItemPaged -from azure.core.credentials import TokenCredential, AzureKeyCredential -from azure.core.pipeline.policies import BearerTokenCredentialPolicy -from azure.core.polling import LROPoller -from azure.core.tracing.decorator import distributed_trace -from azure.core.exceptions import ( - ResourceExistsError, - ResourceNotFoundError, - ResourceModifiedError, - ResourceNotModifiedError, -) -from azure.core.rest import HttpRequest, HttpResponse -from ._azure_appconfiguration_error import ResourceReadOnlyError -from ._azure_appconfiguration_requests import AppConfigRequestsCredentialsPolicy -from ._generated import AzureAppConfiguration -from ._generated.models import ( - SnapshotUpdateParameters, - SnapshotStatus, - SnapshotFields, - SnapshotComposition, - LabelFields, - ConfigurationSettingFields, -) -from ._models import ( - ConfigurationSetting, - ConfigurationSettingPropertiesPaged, - ConfigurationSettingsFilter, - ConfigurationSnapshot, - ConfigurationSettingLabel, -) -from ._utils import ( - prep_if_match, - prep_if_none_match, - get_key_filter, - get_label_filter, - parse_connection_string, -) -from ._sync_token import SyncTokenPolicy - - -class AzureAppConfigurationClient: - """Represents a client that calls restful API of Azure App Configuration service. - - :param str base_url: Base url of the service. - :param credential: An object which can provide secrets for the app configuration service - :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: Api Version. Default value is "2023-11-01". Note that overriding this default - value may result in unsupported behavior. - :paramtype api_version: str - - """ - - # pylint:disable=protected-access - def __init__(self, base_url: str, credential: TokenCredential, **kwargs: Any) -> None: - try: - if not base_url.lower().startswith("http"): - base_url = f"https://{base_url}" - except AttributeError as exc: - raise ValueError("Base URL must be a string.") from exc - - if not credential: - raise ValueError("Missing credential") - - credential_scopes = [f"{base_url.strip('/')}/.default"] - self._sync_token_policy = SyncTokenPolicy() - - if isinstance(credential, AzureKeyCredential): - id_credential = kwargs.pop("id_credential") - kwargs.update( - { - "authentication_policy": AppConfigRequestsCredentialsPolicy(credential, base_url, id_credential), - } - ) - elif isinstance(credential, TokenCredential): - kwargs.update( - { - "authentication_policy": BearerTokenCredentialPolicy(credential, *credential_scopes, **kwargs), - } - ) - else: - raise TypeError( - f"Unsupported credential: {type(credential)}. Use an instance of token credential from azure.identity" - ) - # mypy doesn't compare the credential type hint with the API surface in patch.py - self._impl = AzureAppConfiguration( - credential, base_url, per_call_policies=self._sync_token_policy, **kwargs # type: ignore[arg-type] - ) - - @classmethod - def from_connection_string(cls, connection_string: str, **kwargs: Any) -> "AzureAppConfigurationClient": - """Create AzureAppConfigurationClient from a Connection String. - - :param str connection_string: Connection String - (one of the access keys of the Azure App Configuration resource) - used to access the Azure App Configuration. - :return: An AzureAppConfigurationClient authenticated with the connection string - :rtype: ~azure.appconfiguration.AzureAppConfigurationClient - - Example - - .. code-block:: python - - from azure.appconfiguration import AzureAppConfigurationClient - - connection_str = "" - client = AzureAppConfigurationClient.from_connection_string(connection_str) - """ - endpoint, id_credential, secret = parse_connection_string(connection_string) - # AzureKeyCredential type is for internal use, it's not exposed in public API. - return cls( - credential=AzureKeyCredential(secret), # type: ignore[arg-type] - base_url=endpoint, - id_credential=id_credential, - **kwargs, - ) - - @distributed_trace - def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs a network request using the client's existing pipeline. - - The request URL can be relative to the vault URL. The service API version used for the request is the same as - the client's unless otherwise specified. This method does not raise if the response is an error; to raise an - exception, call `raise_for_status()` on the returned response object. For more information about how to send - custom requests with this method, see https://aka.ms/azsdk/dpcodegen/python/send_request. - - :param request: The network request you want to make. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - return self._impl._send_request(request, stream=stream, **kwargs) - - @overload - def list_configuration_settings( - self, - *, - key_filter: Optional[str] = None, - label_filter: Optional[str] = None, - tags_filter: Optional[List[str]] = None, - accept_datetime: Optional[Union[datetime, str]] = None, - fields: Optional[List[Union[str, ConfigurationSettingFields]]] = None, - **kwargs: Any, - ) -> ItemPaged[ConfigurationSetting]: - """List the configuration settings stored in the configuration service, optionally filtered by - key, label, tags and accept_datetime. For more information about supported filters, see - https://learn.microsoft.com/azure/azure-app-configuration/rest-api-key-value?pivots=v23-11#supported-filters. - - :keyword key_filter: Filter results based on their keys. '*' can be used as wildcard in the beginning or end - of the filter. - :paramtype key_filter: str or None - :keyword label_filter: Filter results based on their label. '*' can be used as wildcard in the beginning or end - of the filter. - :paramtype label_filter: str or None - :keyword tags_filter: Filter results based on their tags. - :paramtype tags_filter: list[str] or None - :keyword accept_datetime: Retrieve ConfigurationSetting that existed at this datetime - :paramtype accept_datetime: ~datetime.datetime or str or None - :keyword fields: Specify which fields to include in the results. If not specified, will include all fields. - Available fields see :class:`~azure.appconfiguration.ConfigurationSettingFields`. - :paramtype fields: list[str] or list[~azure.appconfiguration.ConfigurationSettingFields] or None - :return: An iterator of :class:`~azure.appconfiguration.ConfigurationSetting` - :rtype: ~azure.core.paging.ItemPaged[~azure.appconfiguration.ConfigurationSetting] - :raises: :class:`~azure.core.exceptions.HttpResponseError`, \ - :class:`~azure.core.exceptions.ClientAuthenticationError` - - Example - - .. code-block:: python - - from datetime import datetime, timedelta - - accept_datetime = datetime.utcnow() + timedelta(days=-1) - - all_listed = client.list_configuration_settings() - for item in all_listed: - pass # do something - - filtered_listed = client.list_configuration_settings( - label_filter="Labe*", key_filter="Ke*", accept_datetime=str(accept_datetime) - ) - for item in filtered_listed: - pass # do something - """ - - @overload - def list_configuration_settings( - self, - *, - snapshot_name: str, - fields: Optional[List[Union[str, ConfigurationSettingFields]]] = None, - **kwargs: Any, - ) -> ItemPaged[ConfigurationSetting]: - """List the configuration settings stored under a snapshot in the configuration service, optionally filtered by - fields to present in return. - - :keyword str snapshot_name: The snapshot name. - :keyword fields: Specify which fields to include in the results. If not specified, will include all fields. - Available fields see :class:`~azure.appconfiguration.ConfigurationSettingFields`. - :paramtype fields: list[str] or list[~azure.appconfiguration.ConfigurationSettingFields] or None - :return: An iterator of :class:`~azure.appconfiguration.ConfigurationSetting` - :rtype: ~azure.core.paging.ItemPaged[~azure.appconfiguration.ConfigurationSetting] - :raises: :class:`~azure.core.exceptions.HttpResponseError` - """ - - @distributed_trace - def list_configuration_settings(self, *args: Optional[str], **kwargs: Any) -> ItemPaged[ConfigurationSetting]: - accept_datetime = kwargs.pop("accept_datetime", None) - if isinstance(accept_datetime, datetime): - accept_datetime = str(accept_datetime) - select = kwargs.pop("fields", None) - if select: - select = ["locked" if x == "read_only" else x for x in select] - snapshot_name = kwargs.pop("snapshot_name", None) - - if snapshot_name is not None: - return self._impl.get_key_values( # type: ignore[return-value] - snapshot=snapshot_name, - accept_datetime=accept_datetime, - select=select, - cls=lambda objs: [ConfigurationSetting._from_generated(x) for x in objs], - **kwargs, - ) - tags = kwargs.pop("tags_filter", None) - key_filter, kwargs = get_key_filter(*args, **kwargs) - label_filter, kwargs = get_label_filter(*args, **kwargs) - command = functools.partial(self._impl.get_key_values_in_one_page, **kwargs) # type: ignore[attr-defined] - return ItemPaged( - command, - key=key_filter, - label=label_filter, - accept_datetime=accept_datetime, - select=select, - tags=tags, - page_iterator_class=ConfigurationSettingPropertiesPaged, - ) - - @distributed_trace - def get_configuration_setting( - self, - key: str, - label: Optional[str] = None, - etag: Optional[str] = "*", - match_condition: MatchConditions = MatchConditions.Unconditionally, - *, - accept_datetime: Optional[Union[datetime, str]] = None, - **kwargs: Any, - ) -> Union[None, ConfigurationSetting]: - """Get the matched ConfigurationSetting from Azure App Configuration service - - :param key: Key of the ConfigurationSetting - :type key: str - :param label: Label used to identify the ConfigurationSetting. Default is `None`. - :type label: str or None - :param etag: Check if the ConfigurationSetting is changed. Set None to skip checking etag - :type etag: str or None - :param match_condition: The match condition to use upon the etag - :type match_condition: ~azure.core.MatchConditions - :keyword accept_datetime: Retrieve ConfigurationSetting that existed at this datetime - :paramtype accept_datetime: ~datetime.datetime or str or None - :return: The matched ConfigurationSetting object - :rtype: ~azure.appconfiguration.ConfigurationSetting or None - :raises: :class:`~azure.core.exceptions.HttpResponseError`, \ - :class:`~azure.core.exceptions.ClientAuthenticationError`, \ - :class:`~azure.core.exceptions.ResourceNotFoundError`, \ - :class:`~azure.core.exceptions.ResourceModifiedError`, \ - :class:`~azure.core.exceptions.ResourceExistsError` - - Example - - .. code-block:: python - - fetched_config_setting = client.get_configuration_setting( - key="MyKey", label="MyLabel" - ) - """ - if isinstance(accept_datetime, datetime): - accept_datetime = str(accept_datetime) - - error_map: Dict[int, Any] = {} - if match_condition == MatchConditions.IfNotModified: - error_map.update({412: ResourceModifiedError}) - if match_condition == MatchConditions.IfPresent: - error_map.update({412: ResourceNotFoundError}) - if match_condition == MatchConditions.IfMissing: - error_map.update({412: ResourceExistsError}) - - try: - key_value = self._impl.get_key_value( - key=key, - label=label, - accept_datetime=accept_datetime, - if_match=prep_if_match(etag, match_condition), - if_none_match=prep_if_none_match(etag, match_condition), - error_map=error_map, - **kwargs, - ) - return ConfigurationSetting._from_generated(key_value) - except ResourceNotModifiedError: - return None - - @distributed_trace - def add_configuration_setting( - self, configuration_setting: ConfigurationSetting, **kwargs: Any - ) -> ConfigurationSetting: - """Add a ConfigurationSetting instance into the Azure App Configuration service. - - :param configuration_setting: The ConfigurationSetting object to be added - :type configuration_setting: ~azure.appconfiguration.ConfigurationSetting - :return: The ConfigurationSetting object returned from the App Configuration service - :rtype: ~azure.appconfiguration.ConfigurationSetting - :raises: :class:`~azure.core.exceptions.HttpResponseError`, \ - :class:`~azure.core.exceptions.ClientAuthenticationError`, \ - :class:`~azure.core.exceptions.ResourceExistsError` - - Example - - .. code-block:: python - - config_setting = ConfigurationSetting( - key="MyKey", - label="MyLabel", - value="my value", - content_type="my content type", - tags={"my tag": "my tag value"} - ) - added_config_setting = client.add_configuration_setting(config_setting) - """ - key_value = configuration_setting._to_generated() - error_map = {412: ResourceExistsError} - key_value_added = self._impl.put_key_value( - entity=key_value, - key=key_value.key, # type: ignore - label=key_value.label, - if_none_match="*", - error_map=error_map, - **kwargs, - ) - return ConfigurationSetting._from_generated(key_value_added) - - @distributed_trace - def set_configuration_setting( - self, - configuration_setting: ConfigurationSetting, - match_condition: MatchConditions = MatchConditions.Unconditionally, - *, - etag: Optional[str] = None, - **kwargs: Any, - ) -> ConfigurationSetting: - """Add or update a ConfigurationSetting. - If the configuration setting identified by key and label does not exist, this is a create. - Otherwise this is an update. - - :param configuration_setting: The ConfigurationSetting to be added (if not exists) \ - or updated (if exists) to the service - :type configuration_setting: ~azure.appconfiguration.ConfigurationSetting - :param match_condition: The match condition to use upon the etag - :type match_condition: ~azure.core.MatchConditions - :keyword etag: Check if the ConfigurationSetting is changed. \ - Will use the value from param configuration_setting if not set. - :paramtype etag: str or None - :return: The ConfigurationSetting returned from the service - :rtype: ~azure.appconfiguration.ConfigurationSetting - :raises: :class:`~azure.appconfiguration.ResourceReadOnlyError`, \ - :class:`~azure.core.exceptions.HttpResponseError`, \ - :class:`~azure.core.exceptions.ClientAuthenticationError`, \ - :class:`~azure.core.exceptions.ResourceModifiedError`, \ - :class:`~azure.core.exceptions.ResourceNotModifiedError`, \ - :class:`~azure.core.exceptions.ResourceNotFoundError`, \ - :class:`~azure.core.exceptions.ResourceExistsError` - - Example - - .. code-block:: python - - config_setting = ConfigurationSetting( - key="MyKey", - label="MyLabel", - value="my set value", - content_type="my set content type", - tags={"my set tag": "my set tag value"} - ) - returned_config_setting = client.set_configuration_setting(config_setting) - """ - key_value = configuration_setting._to_generated() - error_map: Dict[int, Any] = {409: ResourceReadOnlyError} - if match_condition == MatchConditions.IfNotModified: - error_map.update({412: ResourceModifiedError}) - if match_condition == MatchConditions.IfModified: - error_map.update({412: ResourceNotModifiedError}) - if match_condition == MatchConditions.IfPresent: - error_map.update({412: ResourceNotFoundError}) - if match_condition == MatchConditions.IfMissing: - error_map.update({412: ResourceExistsError}) - - key_value_set = self._impl.put_key_value( - entity=key_value, - key=key_value.key, # type: ignore - label=key_value.label, - if_match=prep_if_match(configuration_setting.etag, match_condition), - if_none_match=prep_if_none_match(etag or configuration_setting.etag, match_condition), - error_map=error_map, - **kwargs, - ) - return ConfigurationSetting._from_generated(key_value_set) - - @distributed_trace - def delete_configuration_setting( # pylint:disable=delete-operation-wrong-return-type - self, - key: str, - label: Optional[str] = None, - *, - etag: Optional[str] = None, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any, - ) -> Union[None, ConfigurationSetting]: - """Delete a ConfigurationSetting if it exists - - :param key: Key used to identify the ConfigurationSetting - :type key: str - :param label: Label used to identify the ConfigurationSetting. Default is `None`. - :type label: str or None - :keyword etag: Check if the ConfigurationSetting is changed. Set None to skip checking etag - :paramtype etag: str or None - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The deleted ConfigurationSetting returned from the service, or None if it doesn't exist. - :rtype: ~azure.appconfiguration.ConfigurationSetting - :raises: :class:`~azure.appconfiguration.ResourceReadOnlyError`, \ - :class:`~azure.core.exceptions.HttpResponseError`, \ - :class:`~azure.core.exceptions.ClientAuthenticationError`, \ - :class:`~azure.core.exceptions.ResourceModifiedError`, \ - :class:`~azure.core.exceptions.ResourceNotModifiedError`, \ - :class:`~azure.core.exceptions.ResourceNotFoundError`, \ - :class:`~azure.core.exceptions.ResourceExistsError` - - Example - - .. code-block:: python - - deleted_config_setting = client.delete_configuration_setting( - key="MyKey", label="MyLabel" - ) - """ - error_map: Dict[int, Any] = {409: ResourceReadOnlyError} - if match_condition == MatchConditions.IfNotModified: - error_map.update({412: ResourceModifiedError}) - if match_condition == MatchConditions.IfModified: - error_map.update({412: ResourceNotModifiedError}) - if match_condition == MatchConditions.IfPresent: - error_map.update({412: ResourceNotFoundError}) - if match_condition == MatchConditions.IfMissing: - error_map.update({412: ResourceExistsError}) - - key_value_deleted = self._impl.delete_key_value( - key=key, - label=label, - if_match=prep_if_match(etag, match_condition), - error_map=error_map, - **kwargs, - ) - if key_value_deleted: - return ConfigurationSetting._from_generated(key_value_deleted) - return None - - @distributed_trace - def list_revisions( - self, - key_filter: Optional[str] = None, - label_filter: Optional[str] = None, - *, - tags_filter: Optional[List[str]] = None, - accept_datetime: Optional[Union[datetime, str]] = None, - fields: Optional[List[Union[str, ConfigurationSettingFields]]] = None, - **kwargs: Any, - ) -> ItemPaged[ConfigurationSetting]: - """ - Find the ConfigurationSetting revision history, optionally filtered by key, label, tags and accept_datetime. - For more information about supported filters, see - https://learn.microsoft.com/azure/azure-app-configuration/rest-api-revisions?pivots=v23-11#supported-filters. - - :param key_filter: Filter results based on their keys. '*' can be used as wildcard in the beginning or end - of the filter. - :type key_filter: str or None - :param label_filter: Filter results based on their label. '*' can be used as wildcard in the beginning or end - of the filter. - :type label_filter: str or None - :keyword tags_filter: Filter results based on their tags. - :paramtype tags_filter: list[str] or None - :keyword accept_datetime: Retrieve ConfigurationSetting that existed at this datetime - :paramtype accept_datetime: ~datetime.datetime or str or None - :keyword fields: Specify which fields to include in the results. If not specified, will include all fields. - Available fields see :class:`~azure.appconfiguration.ConfigurationSettingFields`. - :paramtype fields: list[str] or list[~azure.appconfiguration.ConfigurationSettingFields] or None - :return: An iterator of :class:`~azure.appconfiguration.ConfigurationSetting` - :rtype: ~azure.core.paging.ItemPaged[~azure.appconfiguration.ConfigurationSetting] - :raises: :class:`~azure.core.exceptions.HttpResponseError`, \ - :class:`~azure.core.exceptions.ClientAuthenticationError` - - Example - - .. code-block:: python - - from datetime import datetime, timedelta - - accept_datetime = datetime.utcnow() + timedelta(days=-1) - - all_revisions = client.list_revisions() - for item in all_revisions: - pass # do something - - filtered_revisions = client.list_revisions( - label_filter="Labe*", key_filter="Ke*", accept_datetime=str(accept_datetime) - ) - for item in filtered_revisions: - pass # do something - """ - if isinstance(accept_datetime, datetime): - accept_datetime = str(accept_datetime) - if fields: - fields = ["locked" if x == "read_only" else x for x in fields] - - return self._impl.get_revisions( # type: ignore[return-value] - label=label_filter, - key=key_filter, - accept_datetime=accept_datetime, - select=fields, - tags=tags_filter, - cls=lambda objs: [ConfigurationSetting._from_generated(x) for x in objs], - **kwargs, - ) - - @distributed_trace - def set_read_only( - self, - configuration_setting: ConfigurationSetting, - read_only: bool = True, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any, - ) -> ConfigurationSetting: - """Set a configuration setting read only - - :param configuration_setting: The ConfigurationSetting to be set read only - :type configuration_setting: ~azure.appconfiguration.ConfigurationSetting - :param read_only: Set the read only setting if true, else clear the read only setting - :type read_only: bool - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The ConfigurationSetting returned from the service - :rtype: ~azure.appconfiguration.ConfigurationSetting - :raises: :class:`~azure.core.exceptions.HttpResponseError`, \ - :class:`~azure.core.exceptions.ClientAuthenticationError`, \ - :class:`~azure.core.exceptions.ResourceNotFoundError` - - Example - - .. code-block:: python - - config_setting = client.get_configuration_setting( - key="MyKey", label="MyLabel" - ) - - read_only_config_setting = client.set_read_only(config_setting) - read_only_config_setting = client.set_read_only(config_setting, read_only=False) - """ - error_map: Dict[int, Any] = {} - if match_condition == MatchConditions.IfNotModified: - error_map.update({412: ResourceModifiedError}) - if match_condition == MatchConditions.IfModified: - error_map.update({412: ResourceNotModifiedError}) - if match_condition == MatchConditions.IfPresent: - error_map.update({412: ResourceNotFoundError}) - if match_condition == MatchConditions.IfMissing: - error_map.update({412: ResourceExistsError}) - - if read_only: - key_value = self._impl.put_lock( - key=configuration_setting.key, - label=configuration_setting.label, - if_match=prep_if_match(configuration_setting.etag, match_condition), - if_none_match=prep_if_none_match(configuration_setting.etag, match_condition), - error_map=error_map, - **kwargs, - ) - else: - key_value = self._impl.delete_lock( - key=configuration_setting.key, - label=configuration_setting.label, - if_match=prep_if_match(configuration_setting.etag, match_condition), - if_none_match=prep_if_none_match(configuration_setting.etag, match_condition), - error_map=error_map, - **kwargs, - ) - return ConfigurationSetting._from_generated(key_value) - - @distributed_trace - def list_labels( - self, - *, - name: Optional[str] = None, - after: Optional[str] = None, - accept_datetime: Optional[Union[datetime, str]] = None, - fields: Optional[List[Union[str, LabelFields]]] = None, - **kwargs: Any, - ) -> ItemPaged[ConfigurationSettingLabel]: - """Gets a list of labels. - - :keyword name: A filter for the name of the returned labels. '*' can be used as wildcard - in the beginning or end of the filter. For more information about supported filters, see - https://learn.microsoft.com/azure/azure-app-configuration/rest-api-labels?pivots=v23-11#supported-filters. - :paramtype name: str or None - :keyword after: Instructs the server to return elements that appear after the element referred to - by the specified token. - :paramtype after: str or None - :keyword accept_datetime: Requests the server to respond with the state of the resource at the - specified time. - :paramtype accept_datetime: ~datetime.datetime or str or None - :keyword fields: Specify which fields to include in the results. If not specified, will include all fields. - Available fields see :class:`~azure.appconfiguration.LabelFields`. - :paramtype fields: list[str] or list[~azure.appconfiguration.LabelFields] or None - :return: An iterator of labels. - :rtype: ~azure.core.paging.ItemPaged[~azure.appconfiguration.ConfigurationSettingLabel] - :raises: :class:`~azure.core.exceptions.HttpResponseError` - """ - if isinstance(accept_datetime, datetime): - accept_datetime = str(accept_datetime) - return self._impl.get_labels( # type: ignore[return-value] - name=name, - after=after, - accept_datetime=accept_datetime, - select=fields, - cls=lambda objs: [ConfigurationSettingLabel(name=x.name) for x in objs], - **kwargs, - ) - - @distributed_trace - def begin_create_snapshot( - self, - name: str, - filters: List[ConfigurationSettingsFilter], - *, - composition_type: Optional[Union[str, SnapshotComposition]] = None, - retention_period: Optional[int] = None, - tags: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> LROPoller[ConfigurationSnapshot]: - """Create a snapshot of the configuration settings. - - :param name: The name of the configuration snapshot to create. - :type name: str - :param filters: A list of filters used to filter the configuration settings by key field and label field - included in the configuration snapshot. - :type filters: list[~azure.appconfiguration.ConfigurationSettingsFilter] - :keyword composition_type: The composition type describes how the key-values within the configuration - snapshot are composed. Known values are: "key" and "key_label". The "key" composition type - ensures there are no two key-values containing the same key. The 'key_label' composition type ensures - there are no two key-values containing the same key and label. - :paramtype composition_type: str or ~azure.appconfiguration.SnapshotComposition or None - :keyword retention_period: The amount of time, in seconds, that a configuration snapshot will remain in the - archived state before expiring. This property is only writable during the creation of a configuration - snapshot. If not specified, will set to 2592000(30 days). If specified, should be - in range 3600(1 hour) to 7776000(90 days). - :paramtype retention_period: int or None - :keyword tags: The tags of the configuration snapshot. - :paramtype tags: dict[str, str] or None - :return: A poller for create configuration snapshot operation. Call `result()` on this object to wait for the - operation to complete and get the created snapshot. - :rtype: ~azure.core.polling.LROPoller[~azure.appconfiguration.ConfigurationSnapshot] - :raises: :class:`~azure.core.exceptions.HttpResponseError` - """ - snapshot = ConfigurationSnapshot( - filters=filters, composition_type=composition_type, retention_period=retention_period, tags=tags - ) - return cast( - LROPoller[ConfigurationSnapshot], - self._impl.begin_create_snapshot( - name=name, entity=snapshot._to_generated(), cls=ConfigurationSnapshot._from_deserialized, **kwargs - ), - ) - - @distributed_trace - def archive_snapshot( - self, - name: str, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - etag: Optional[str] = None, - **kwargs: Any, - ) -> ConfigurationSnapshot: - """Archive a configuration setting snapshot. It will update the status of a snapshot from "ready" to "archived". - The retention period will start to count, the snapshot will expire when the entire retention period elapses. - - :param name: The name of the configuration setting snapshot to archive. - :type name: str - :keyword match_condition: The match condition to use upon the etag. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword etag: Check if the ConfigurationSnapshot is changed. Set None to skip checking etag. - :paramtype etag: str or None - :return: The ConfigurationSnapshot returned from the service. - :rtype: ~azure.appconfiguration.ConfigurationSnapshot - :raises: :class:`~azure.core.exceptions.HttpResponseError` - """ - error_map: Dict[int, Any] = {} - if match_condition == MatchConditions.IfNotModified: - error_map.update({412: ResourceModifiedError}) - if match_condition == MatchConditions.IfModified: - error_map.update({412: ResourceNotModifiedError}) - if match_condition == MatchConditions.IfPresent: - error_map.update({412: ResourceNotFoundError}) - if match_condition == MatchConditions.IfMissing: - error_map.update({412: ResourceExistsError}) - generated_snapshot = self._impl.update_snapshot( - name=name, - entity=SnapshotUpdateParameters(status=SnapshotStatus.ARCHIVED), - if_match=prep_if_match(etag, match_condition), - if_none_match=prep_if_none_match(etag, match_condition), - error_map=error_map, - **kwargs, - ) - return ConfigurationSnapshot._from_generated(generated_snapshot) - - @distributed_trace - def recover_snapshot( - self, - name: str, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - etag: Optional[str] = None, - **kwargs: Any, - ) -> ConfigurationSnapshot: - """Recover a configuration setting snapshot. It will update the status of a snapshot from "archived" to "ready". - - :param name: The name of the configuration setting snapshot to recover. - :type name: str - :keyword match_condition: The match condition to use upon the etag. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword etag: Check if the ConfigurationSnapshot is changed. Set None to skip checking etag. - :paramtype etag: str or None - :return: The ConfigurationSnapshot returned from the service. - :rtype: ~azure.appconfiguration.ConfigurationSnapshot - :raises: :class:`~azure.core.exceptions.HttpResponseError` - """ - error_map: Dict[int, Any] = {} - if match_condition == MatchConditions.IfNotModified: - error_map.update({412: ResourceModifiedError}) - if match_condition == MatchConditions.IfModified: - error_map.update({412: ResourceNotModifiedError}) - if match_condition == MatchConditions.IfPresent: - error_map.update({412: ResourceNotFoundError}) - if match_condition == MatchConditions.IfMissing: - error_map.update({412: ResourceExistsError}) - generated_snapshot = self._impl.update_snapshot( - name=name, - entity=SnapshotUpdateParameters(status=SnapshotStatus.READY), - if_match=prep_if_match(etag, match_condition), - if_none_match=prep_if_none_match(etag, match_condition), - error_map=error_map, - **kwargs, - ) - return ConfigurationSnapshot._from_generated(generated_snapshot) - - @distributed_trace - def get_snapshot( - self, name: str, *, fields: Optional[List[Union[str, SnapshotFields]]] = None, **kwargs: Any - ) -> ConfigurationSnapshot: - """Get a configuration setting snapshot. - - :param name: The name of the configuration setting snapshot to retrieve. - :type name: str - :keyword fields: Specify which fields to include in the results. If not specified, will include all fields. - Available fields see :class:`~azure.appconfiguration.SnapshotFields`. - :paramtype fields: list[str] or list[~azure.appconfiguration.SnapshotFields] or None - :return: The ConfigurationSnapshot returned from the service. - :rtype: ~azure.appconfiguration.ConfigurationSnapshot - :raises: :class:`~azure.core.exceptions.HttpResponseError` - """ - generated_snapshot = self._impl.get_snapshot( - name=name, if_match=None, if_none_match=None, select=fields, **kwargs - ) - return ConfigurationSnapshot._from_generated(generated_snapshot) - - @distributed_trace - def list_snapshots( - self, - *, - name: Optional[str] = None, - fields: Optional[List[Union[str, SnapshotFields]]] = None, - status: Optional[List[Union[str, SnapshotStatus]]] = None, - **kwargs: Any, - ) -> ItemPaged[ConfigurationSnapshot]: - """List the configuration setting snapshots stored in the configuration service, optionally filtered by - snapshot name, snapshot status and fields to present in return. - - :keyword name: Filter results based on snapshot name. - :paramtype name: str or None - :keyword fields: Specify which fields to include in the results. If not specified, will include all fields. - Available fields see :class:`~azure.appconfiguration.SnapshotFields`. - :paramtype fields: list[str] or list[~azure.appconfiguration.SnapshotFields] or None - :keyword status: Filter results based on snapshot keys. Available status see - :class:`~azure.appconfiguration.SnapshotStatus`. - :paramtype status: list[str] or list[~azure.appconfiguration.SnapshotStatus] or None - :return: An iterator of :class:`~azure.appconfiguration.ConfigurationSnapshot` - :rtype: ~azure.core.paging.ItemPaged[~azure.appconfiguration.ConfigurationSnapshot] - :raises: :class:`~azure.core.exceptions.HttpResponseError` - """ - return self._impl.get_snapshots( # type: ignore[return-value] - name=name, - select=fields, - status=status, - cls=lambda objs: [ConfigurationSnapshot._from_generated(x) for x in objs], - **kwargs, - ) - - def update_sync_token(self, token: str) -> None: - """Add a sync token to the internal list of tokens. - - :param str token: The sync token to be added to the internal list of tokens - """ - if not self._sync_token_policy: - raise AttributeError( - "Client has no sync token policy, possibly because it was not provided during instantiation." - ) - self._sync_token_policy.add_token(token) - - def close(self) -> None: - """Close all connections made by the client""" - self._impl._client.close() - - def __enter__(self) -> "AzureAppConfigurationClient": - self._impl.__enter__() - return self - - def __exit__(self, *args: Any) -> None: - self._impl.__exit__(*args) diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_azure_appconfiguration_error.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_azure_appconfiguration_error.py deleted file mode 100644 index da2c96acf2c0..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_azure_appconfiguration_error.py +++ /dev/null @@ -1,14 +0,0 @@ -# ------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ------------------------------------------------------------------------- -from azure.core.exceptions import HttpResponseError - - -class ResourceReadOnlyError(HttpResponseError): - """An error response with status code 409 - - The key is read-only. - - To allow modification unlock it first.""" diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_azure_appconfiguration_requests.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_azure_appconfiguration_requests.py deleted file mode 100644 index c96c85f66420..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_azure_appconfiguration_requests.py +++ /dev/null @@ -1,79 +0,0 @@ -# ------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ------------------------------------------------------------------------- - -import hashlib -import base64 -import hmac -from azure.core.credentials import AzureKeyCredential -from azure.core.pipeline.policies import HTTPPolicy -from ._utils import get_current_utc_time - - -class AppConfigRequestsCredentialsPolicy(HTTPPolicy): - """Implementation of request-oauthlib except and retry logic.""" - - def __init__(self, credential: AzureKeyCredential, endpoint: str, id_credential: str): - super(AppConfigRequestsCredentialsPolicy, self).__init__() - self._credential = credential - self._host = str(endpoint[8:]) - self._id_credential = id_credential - - def _signed_request(self, request): - verb = request.http_request.method.upper() - - # Get the path and query from url, which looks like https://host/path/query - query_url = str(request.http_request.url[len(self._host) + 8 :]) - # Need URL() to get a correct encoded key value, from "%2A" to "*", when transport is in type AioHttpTransport. - # There's a similar scenario in azure-storage-blob, the check logic is from there. - try: - from yarl import URL - from azure.core.pipeline.transport import ( # pylint:disable=non-abstract-transport-import,no-name-in-module - AioHttpTransport, - ) - - if ( - isinstance(request.context.transport, AioHttpTransport) - or isinstance(getattr(request.context.transport, "_transport", None), AioHttpTransport) - or isinstance( - getattr(getattr(request.context.transport, "_transport", None), "_transport", None), - AioHttpTransport, - ) - ): - query_url = str(URL(query_url)) - except (ImportError, TypeError): - pass - signed_headers = "x-ms-date;host;x-ms-content-sha256" - - utc_now = get_current_utc_time() - if request.http_request.body is None: - request.http_request.body = "" - content_digest = hashlib.sha256((request.http_request.body.encode("utf-8"))).digest() - content_hash = base64.b64encode(content_digest).decode("utf-8") - - string_to_sign = verb + "\n" + query_url + "\n" + utc_now + ";" + self._host + ";" + content_hash - - decoded_secret = base64.b64decode(self._credential.key) - digest = hmac.new(decoded_secret, string_to_sign.encode("utf-8"), hashlib.sha256).digest() - signature = base64.b64encode(digest).decode("utf-8") - - signature_header = { - "x-ms-date": utc_now, - "x-ms-content-sha256": content_hash, - "Authorization": "HMAC-SHA256 Credential=" - + self._id_credential - + "&SignedHeaders=" - + signed_headers - + "&Signature=" - + signature, - } - - request.http_request.headers.update(signature_header) - - return request - - def send(self, request): - self._signed_request(request) - return self.next.send(request) diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/_azure_app_configuration.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_client.py similarity index 68% rename from sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/_azure_app_configuration.py rename to sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_client.py index e1381a3726f7..e1bab02c1961 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/_azure_app_configuration.py +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_client.py @@ -2,12 +2,12 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Optional +from typing import Any, TYPE_CHECKING, Union from typing_extensions import Self from azure.core import PipelineClient @@ -15,36 +15,33 @@ from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse -from . import models as _models -from ._configuration import AzureAppConfigurationConfiguration +from ._configuration import AzureAppConfigurationClientConfiguration +from ._operations import AzureAppConfigurationClientOperationsMixin from ._serialization import Deserializer, Serializer -from .operations import AzureAppConfigurationOperationsMixin +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential -class AzureAppConfiguration(AzureAppConfigurationOperationsMixin): # pylint: disable=client-accepts-api-version-keyword - """AzureAppConfiguration. - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.AzureKeyCredential - :param endpoint: The endpoint of the App Configuration instance to send requests to. Required. +class AzureAppConfigurationClient(AzureAppConfigurationClientOperationsMixin): + """Azure App Configuration REST API. + + :param endpoint: Required. :type endpoint: str - :param sync_token: Used to guarantee real-time consistency between requests. Default value is - None. - :type sync_token: str - :keyword api_version: Api Version. Default value is "2023-11-01". Note that overriding this - default value may result in unsupported behavior. + :param credential: Credential used to authenticate requests to the service. Is either a + AzureKeyCredential type or a TokenCredential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is "2023-11-01". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ - def __init__( - self, credential: AzureKeyCredential, endpoint: str, sync_token: Optional[str] = None, **kwargs: Any - ) -> None: + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: _endpoint = "{endpoint}" - self._config = AzureAppConfigurationConfiguration( - credential=credential, endpoint=endpoint, sync_token=sync_token, **kwargs - ) + self._config = AzureAppConfigurationClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -64,18 +61,17 @@ def __init__( ] self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = client._send_request(request) + >>> response = client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/_configuration.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_configuration.py similarity index 60% rename from sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/_configuration.py rename to sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_configuration.py index 7d10ceaec124..c45954a5ab89 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/_configuration.py +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_configuration.py @@ -2,54 +2,61 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional +from typing import Any, TYPE_CHECKING, Union from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies -VERSION = "unknown" +from ._version import VERSION +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential -class AzureAppConfigurationConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long - """Configuration for AzureAppConfiguration. + +class AzureAppConfigurationClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for AzureAppConfigurationClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.AzureKeyCredential - :param endpoint: The endpoint of the App Configuration instance to send requests to. Required. + :param endpoint: Required. :type endpoint: str - :param sync_token: Used to guarantee real-time consistency between requests. Default value is - None. - :type sync_token: str - :keyword api_version: Api Version. Default value is "2023-11-01". Note that overriding this - default value may result in unsupported behavior. + :param credential: Credential used to authenticate requests to the service. Is either a + AzureKeyCredential type or a TokenCredential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is "2023-11-01". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, credential: AzureKeyCredential, endpoint: str, sync_token: Optional[str] = None, **kwargs: Any - ) -> None: + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: api_version: str = kwargs.pop("api_version", "2023-11-01") - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") - self.credential = credential self.endpoint = endpoint - self.sync_token = sync_token + self.credential = credential self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://azconfig.io/.default"]) kwargs.setdefault("sdk_moniker", "appconfiguration/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "Connection String", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + def _configure(self, **kwargs: Any) -> None: self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) @@ -61,6 +68,4 @@ def _configure(self, **kwargs: Any) -> None: self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AzureKeyCredentialPolicy( - self.credential, "Connection String", **kwargs - ) + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_constants.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_constants.py deleted file mode 100644 index 1f7f465d51d2..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_constants.py +++ /dev/null @@ -1,11 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -FILTER_TIME_WINDOW = "Microsoft.TimeWindow" - -FILTER_PERCENTAGE = "Microsoft.Percentage" - -FILTER_TARGETING = "Microsoft.Targeting" diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/_patch.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/_patch.py deleted file mode 100644 index 0ac530adf35d..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/_patch.py +++ /dev/null @@ -1,84 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - - -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List, Optional, Any, Union -from azure.core.credentials import AzureKeyCredential, TokenCredential - -from ._azure_app_configuration import AzureAppConfiguration as AzureAppConfigurationGenerated -from ._configuration import AzureAppConfigurationConfiguration as AzureAppConfigurationConfigurationGenerated - - -class AzureAppConfiguration(AzureAppConfigurationGenerated): - """AzureAppConfiguration. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential or ~azure.core.credentials.AzureKeyCredential - :param endpoint: The endpoint of the App Configuration instance to send requests to. Required. - :type endpoint: str - :param sync_token: Used to guarantee real-time consistency between requests. Default value is - None. - :type sync_token: str - :keyword api_version: Api Version. Default value is "2023-11-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - """ - - def __init__( - self, - credential: Union[TokenCredential, AzureKeyCredential], - endpoint: str, - sync_token: Optional[str] = None, - **kwargs: Any - ) -> None: - super().__init__(credential, endpoint, sync_token=sync_token, **kwargs) - - -class AzureAppConfigurationConfiguration(AzureAppConfigurationConfigurationGenerated): - """Configuration for AzureAppConfiguration. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential or ~azure.core.credentials.AzureKeyCredential - :param endpoint: The endpoint of the App Configuration instance to send requests to. Required. - :type endpoint: str - :param sync_token: Used to guarantee real-time consistency between requests. Default value is - None. - :type sync_token: str - :keyword api_version: Api Version. Default value is "2023-11-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: Union[TokenCredential, AzureKeyCredential], - endpoint: str, - sync_token: Optional[str] = None, - **kwargs: Any - ) -> None: - super().__init__(credential, endpoint, sync_token=sync_token, **kwargs) - - -__all__: List[str] = [ - "AzureAppConfiguration" -] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/_vendor.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/_vendor.py deleted file mode 100644 index a7cb430b9c7d..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/_vendor.py +++ /dev/null @@ -1,26 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from abc import ABC -from typing import TYPE_CHECKING - -from ._configuration import AzureAppConfigurationConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core import PipelineClient - - from ._serialization import Deserializer, Serializer - - -class AzureAppConfigurationMixinABC(ABC): - """DO NOT use this class. It is for internal typing use only.""" - - _client: "PipelineClient" - _config: AzureAppConfigurationConfiguration - _serialize: "Serializer" - _deserialize: "Deserializer" diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/_patch.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/_patch.py deleted file mode 100644 index fc560bc2d2ef..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/_patch.py +++ /dev/null @@ -1,85 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - - -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List, Optional, Any, Union -from azure.core.credentials import AzureKeyCredential -from azure.core.credentials_async import AsyncTokenCredential - -from ._azure_app_configuration import AzureAppConfiguration as AzureAppConfigurationGenerated -from ._configuration import AzureAppConfigurationConfiguration as AzureAppConfigurationConfigurationGenerated - - -class AzureAppConfiguration(AzureAppConfigurationGenerated): - """AzureAppConfiguration. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential or ~azure.core.credentials.AzureKeyCredential - :param endpoint: The endpoint of the App Configuration instance to send requests to. Required. - :type endpoint: str - :param sync_token: Used to guarantee real-time consistency between requests. Default value is - None. - :type sync_token: str - :keyword api_version: Api Version. Default value is "2023-11-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - """ - - def __init__( - self, - credential: Union[AsyncTokenCredential, AzureKeyCredential], - endpoint: str, - sync_token: Optional[str] = None, - **kwargs: Any - ) -> None: - super().__init__(credential, endpoint, sync_token=sync_token, **kwargs) - - -class AzureAppConfigurationConfiguration(AzureAppConfigurationConfigurationGenerated): - """Configuration for AzureAppConfiguration. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential or ~azure.core.credentials.AzureKeyCredential - :param endpoint: The endpoint of the App Configuration instance to send requests to. Required. - :type endpoint: str - :param sync_token: Used to guarantee real-time consistency between requests. Default value is - None. - :type sync_token: str - :keyword api_version: Api Version. Default value is "2023-11-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - credential: Union[AsyncTokenCredential, AzureKeyCredential], - endpoint: str, - sync_token: Optional[str] = None, - **kwargs: Any - ) -> None: - super().__init__(credential, endpoint, sync_token=sync_token, **kwargs) - - -__all__: List[str] = [ - "AzureAppConfiguration" -] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/_vendor.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/_vendor.py deleted file mode 100644 index 203a80e19af4..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/_vendor.py +++ /dev/null @@ -1,26 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from abc import ABC -from typing import TYPE_CHECKING - -from ._configuration import AzureAppConfigurationConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core import AsyncPipelineClient - - from .._serialization import Deserializer, Serializer - - -class AzureAppConfigurationMixinABC(ABC): - """DO NOT use this class. It is for internal typing use only.""" - - _client: "AsyncPipelineClient" - _config: AzureAppConfigurationConfiguration - _serialize: "Serializer" - _deserialize: "Deserializer" diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/operations/__init__.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/operations/__init__.py deleted file mode 100644 index 374ce030aec3..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/operations/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._azure_app_configuration_operations import AzureAppConfigurationOperationsMixin - -from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "AzureAppConfigurationOperationsMixin", -] -__all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/operations/_patch.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/operations/_patch.py deleted file mode 100644 index 54701280e208..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/operations/_patch.py +++ /dev/null @@ -1,169 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - - -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -import urllib.parse -from typing import Any, AsyncIterable, List, Optional, Union -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from ._azure_app_configuration_operations import ( - AzureAppConfigurationOperationsMixin as AzureAppConfigOpGenerated, - ClsType, - build_get_key_values_request, -) -from ... import models as _models - - -class AzureAppConfigurationOperationsMixin(AzureAppConfigOpGenerated): - @distributed_trace_async - async def get_key_values_in_one_page( - self, - key: Optional[str] = None, - label: Optional[str] = None, - after: Optional[str] = None, - accept_datetime: Optional[str] = None, - select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - tags: Optional[List[str]] = None, - continuation_token: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.KeyValue"]: - """Gets a list of key-values in one page. - - Gets a list of key-values in one page. - - :param key: A filter used to match keys. Default value is None. - :type key: str - :param label: A filter used to match labels. Default value is None. - :type label: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param select: Used to select what fields are present in the returned resource(s). Default - value is None. - :type select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param tags: A filter used to query by tags. Default value is None. - :type tags: list[str] - :param str continuation_token: An opaque continuation token. - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either KeyValue or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.appconfiguration.models.KeyValue] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KeyValueListResult] = kwargs.pop("cls", None) - - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_get_key_values_request( - key=key, - label=label, - after=after, - accept_datetime=accept_datetime, - select=select, - if_match=if_match, - if_none_match=if_none_match, - tags=tags, - sync_token=self._config.sync_token, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - else: - # make call to next link with the client's api-version - - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - _request = prepare_request(continuation_token) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error) - response_headers = response.headers - deserialized = self._deserialize("KeyValueListResult", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) - return deserialized - - -__all__: List[str] = [ - "AzureAppConfigurationOperationsMixin" -] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/models/__init__.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/models/__init__.py deleted file mode 100644 index c5b1e0ff92fd..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/models/__init__.py +++ /dev/null @@ -1,57 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._models_py3 import Error -from ._models_py3 import ErrorDetail -from ._models_py3 import InnerError -from ._models_py3 import Key -from ._models_py3 import KeyListResult -from ._models_py3 import KeyValue -from ._models_py3 import KeyValueFilter -from ._models_py3 import KeyValueListResult -from ._models_py3 import Label -from ._models_py3 import LabelListResult -from ._models_py3 import OperationDetails -from ._models_py3 import Snapshot -from ._models_py3 import SnapshotListResult -from ._models_py3 import SnapshotUpdateParameters - -from ._azure_app_configuration_enums import ConfigurationSettingFields -from ._azure_app_configuration_enums import LabelFields -from ._azure_app_configuration_enums import SnapshotComposition -from ._azure_app_configuration_enums import SnapshotFields -from ._azure_app_configuration_enums import SnapshotStatus -from ._azure_app_configuration_enums import State -from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "Error", - "ErrorDetail", - "InnerError", - "Key", - "KeyListResult", - "KeyValue", - "KeyValueFilter", - "KeyValueListResult", - "Label", - "LabelListResult", - "OperationDetails", - "Snapshot", - "SnapshotListResult", - "SnapshotUpdateParameters", - "ConfigurationSettingFields", - "LabelFields", - "SnapshotComposition", - "SnapshotFields", - "SnapshotStatus", - "State", -] -__all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/models/_models_py3.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/models/_models_py3.py deleted file mode 100644 index 95f255795c4b..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/models/_models_py3.py +++ /dev/null @@ -1,615 +0,0 @@ -# coding=utf-8 -# pylint: disable=too-many-lines -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -import datetime -from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union - -from .. import _serialization - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from .. import models as _models - - -class Error(_serialization.Model): - """Azure App Configuration error object. - - :ivar type: The type of the error. - :vartype type: str - :ivar title: A brief summary of the error. - :vartype title: str - :ivar name: The name of the parameter that resulted in the error. - :vartype name: str - :ivar detail: A detailed description of the error. - :vartype detail: str - :ivar status: The HTTP status code that the error maps to. - :vartype status: int - """ - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "title": {"key": "title", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "detail": {"key": "detail", "type": "str"}, - "status": {"key": "status", "type": "int"}, - } - - def __init__( - self, - *, - type: Optional[str] = None, - title: Optional[str] = None, - name: Optional[str] = None, - detail: Optional[str] = None, - status: Optional[int] = None, - **kwargs: Any - ) -> None: - """ - :keyword type: The type of the error. - :paramtype type: str - :keyword title: A brief summary of the error. - :paramtype title: str - :keyword name: The name of the parameter that resulted in the error. - :paramtype name: str - :keyword detail: A detailed description of the error. - :paramtype detail: str - :keyword status: The HTTP status code that the error maps to. - :paramtype status: int - """ - super().__init__(**kwargs) - self.type = type - self.title = title - self.name = name - self.detail = detail - self.status = status - - -class ErrorDetail(_serialization.Model): - """The details of an error. - - All required parameters must be populated in order to send to server. - - :ivar code: One of a server-defined set of error codes. Required. - :vartype code: str - :ivar message: A human-readable representation of the error. Required. - :vartype message: str - :ivar details: An array of details about specific errors that led to this reported error. - :vartype details: list[~azure.appconfiguration.models.ErrorDetail] - :ivar innererror: An object containing more specific information than the current object about - the error. - :vartype innererror: ~azure.appconfiguration.models.InnerError - """ - - _validation = { - "code": {"required": True}, - "message": {"required": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDetail]"}, - "innererror": {"key": "innererror", "type": "InnerError"}, - } - - def __init__( - self, - *, - code: str, - message: str, - details: Optional[List["_models.ErrorDetail"]] = None, - innererror: Optional["_models.InnerError"] = None, - **kwargs: Any - ) -> None: - """ - :keyword code: One of a server-defined set of error codes. Required. - :paramtype code: str - :keyword message: A human-readable representation of the error. Required. - :paramtype message: str - :keyword details: An array of details about specific errors that led to this reported error. - :paramtype details: list[~azure.appconfiguration.models.ErrorDetail] - :keyword innererror: An object containing more specific information than the current object - about the error. - :paramtype innererror: ~azure.appconfiguration.models.InnerError - """ - super().__init__(**kwargs) - self.code = code - self.message = message - self.details = details - self.innererror = innererror - - -class InnerError(_serialization.Model): - """An object containing specific information about an error. - - :ivar code: One of a server-defined set of error codes. - :vartype code: str - :ivar innererror: An object containing more specific information than the current object about - the error. - :vartype innererror: ~azure.appconfiguration.models.InnerError - """ - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "innererror": {"key": "innererror", "type": "InnerError"}, - } - - def __init__( - self, *, code: Optional[str] = None, innererror: Optional["_models.InnerError"] = None, **kwargs: Any - ) -> None: - """ - :keyword code: One of a server-defined set of error codes. - :paramtype code: str - :keyword innererror: An object containing more specific information than the current object - about the error. - :paramtype innererror: ~azure.appconfiguration.models.InnerError - """ - super().__init__(**kwargs) - self.code = code - self.innererror = innererror - - -class Key(_serialization.Model): - """Key. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the key. - :vartype name: str - """ - - _validation = { - "name": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.name = None - - -class KeyListResult(_serialization.Model): - """The result of a list request. - - :ivar items: The collection value. - :vartype items: list[~azure.appconfiguration.models.Key] - :ivar next_link: The URI that can be used to request the next set of paged results. - :vartype next_link: str - """ - - _attribute_map = { - "items": {"key": "items", "type": "[Key]"}, - "next_link": {"key": "@nextLink", "type": "str"}, - } - - def __init__( - self, *, items: Optional[List["_models.Key"]] = None, next_link: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword items: The collection value. - :paramtype items: list[~azure.appconfiguration.models.Key] - :keyword next_link: The URI that can be used to request the next set of paged results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.items = items - self.next_link = next_link - - -class KeyValue(_serialization.Model): - """KeyValue. - - :ivar key: The key of the key-value. - :vartype key: str - :ivar label: The label the key-value belongs to. - :vartype label: str - :ivar content_type: The content type of the value stored within the key-value. - :vartype content_type: str - :ivar value: The value of the key-value. - :vartype value: str - :ivar last_modified: A date representing the last time the key-value was modified. - :vartype last_modified: ~datetime.datetime - :ivar tags: The tags of the key-value. - :vartype tags: dict[str, str] - :ivar locked: Indicates whether the key-value is locked. - :vartype locked: bool - :ivar etag: A value representing the current state of the resource. - :vartype etag: str - """ - - _attribute_map = { - "key": {"key": "key", "type": "str"}, - "label": {"key": "label", "type": "str"}, - "content_type": {"key": "content_type", "type": "str"}, - "value": {"key": "value", "type": "str"}, - "last_modified": {"key": "last_modified", "type": "iso-8601"}, - "tags": {"key": "tags", "type": "{str}"}, - "locked": {"key": "locked", "type": "bool"}, - "etag": {"key": "etag", "type": "str"}, - } - - def __init__( - self, - *, - key: Optional[str] = None, - label: Optional[str] = None, - content_type: Optional[str] = None, - value: Optional[str] = None, - last_modified: Optional[datetime.datetime] = None, - tags: Optional[Dict[str, str]] = None, - locked: Optional[bool] = None, - etag: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword key: The key of the key-value. - :paramtype key: str - :keyword label: The label the key-value belongs to. - :paramtype label: str - :keyword content_type: The content type of the value stored within the key-value. - :paramtype content_type: str - :keyword value: The value of the key-value. - :paramtype value: str - :keyword last_modified: A date representing the last time the key-value was modified. - :paramtype last_modified: ~datetime.datetime - :keyword tags: The tags of the key-value. - :paramtype tags: dict[str, str] - :keyword locked: Indicates whether the key-value is locked. - :paramtype locked: bool - :keyword etag: A value representing the current state of the resource. - :paramtype etag: str - """ - super().__init__(**kwargs) - self.key = key - self.label = label - self.content_type = content_type - self.value = value - self.last_modified = last_modified - self.tags = tags - self.locked = locked - self.etag = etag - - -class KeyValueFilter(_serialization.Model): - """Enables filtering of key-values. Syntax reference: - https://aka.ms/azconfig/docs/restapisnapshots. - - All required parameters must be populated in order to send to server. - - :ivar key: Filters key-values by their key field. Required. - :vartype key: str - :ivar label: Filters key-values by their label field. - :vartype label: str - :ivar tags: Filters key-values by their tags field. - :vartype tags: list[str] - """ - - _validation = { - "key": {"required": True}, - "tags": {"unique": True}, - } - - _attribute_map = { - "key": {"key": "key", "type": "str"}, - "label": {"key": "label", "type": "str"}, - "tags": {"key": "tags", "type": "[str]"}, - } - - def __init__( - self, *, key: str, label: Optional[str] = None, tags: Optional[List[str]] = None, **kwargs: Any - ) -> None: - """ - :keyword key: Filters key-values by their key field. Required. - :paramtype key: str - :keyword label: Filters key-values by their label field. - :paramtype label: str - :keyword tags: Filters key-values by their tags field. - :paramtype tags: list[str] - """ - super().__init__(**kwargs) - self.key = key - self.label = label - self.tags = tags - - -class KeyValueListResult(_serialization.Model): - """The result of a list request. - - :ivar items: The collection value. - :vartype items: list[~azure.appconfiguration.models.KeyValue] - :ivar etag: An identifier representing the returned state of the resource. - :vartype etag: str - :ivar next_link: The URI that can be used to request the next set of paged results. - :vartype next_link: str - """ - - _attribute_map = { - "items": {"key": "items", "type": "[KeyValue]"}, - "etag": {"key": "etag", "type": "str"}, - "next_link": {"key": "@nextLink", "type": "str"}, - } - - def __init__( - self, - *, - items: Optional[List["_models.KeyValue"]] = None, - etag: Optional[str] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword items: The collection value. - :paramtype items: list[~azure.appconfiguration.models.KeyValue] - :keyword etag: An identifier representing the returned state of the resource. - :paramtype etag: str - :keyword next_link: The URI that can be used to request the next set of paged results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.items = items - self.etag = etag - self.next_link = next_link - - -class Label(_serialization.Model): - """Label. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the label. - :vartype name: str - """ - - _validation = { - "name": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.name = None - - -class LabelListResult(_serialization.Model): - """The result of a list request. - - :ivar items: The collection value. - :vartype items: list[~azure.appconfiguration.models.Label] - :ivar next_link: The URI that can be used to request the next set of paged results. - :vartype next_link: str - """ - - _attribute_map = { - "items": {"key": "items", "type": "[Label]"}, - "next_link": {"key": "@nextLink", "type": "str"}, - } - - def __init__( - self, *, items: Optional[List["_models.Label"]] = None, next_link: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword items: The collection value. - :paramtype items: list[~azure.appconfiguration.models.Label] - :keyword next_link: The URI that can be used to request the next set of paged results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.items = items - self.next_link = next_link - - -class OperationDetails(_serialization.Model): - """Details of a long running operation. - - All required parameters must be populated in order to send to server. - - :ivar id: The unique id of the operation. Required. - :vartype id: str - :ivar status: The current status of the operation. Required. Known values are: "NotStarted", - "Running", "Succeeded", "Failed", and "Canceled". - :vartype status: str or ~azure.appconfiguration.models.State - :ivar error: An error, available when the status is ``Failed``\\ , describing why the operation - failed. - :vartype error: ~azure.appconfiguration.models.ErrorDetail - """ - - _validation = { - "id": {"required": True}, - "status": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "error": {"key": "error", "type": "ErrorDetail"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Union[str, "_models.State"], - error: Optional["_models.ErrorDetail"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: The unique id of the operation. Required. - :paramtype id: str - :keyword status: The current status of the operation. Required. Known values are: "NotStarted", - "Running", "Succeeded", "Failed", and "Canceled". - :paramtype status: str or ~azure.appconfiguration.models.State - :keyword error: An error, available when the status is ``Failed``\\ , describing why the - operation failed. - :paramtype error: ~azure.appconfiguration.models.ErrorDetail - """ - super().__init__(**kwargs) - self.id = id - self.status = status - self.error = error - - -class Snapshot(_serialization.Model): # pylint: disable=too-many-instance-attributes - """Snapshot. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the snapshot. - :vartype name: str - :ivar status: The current status of the snapshot. Known values are: "provisioning", "ready", - "archived", and "failed". - :vartype status: str or ~azure.appconfiguration.models.SnapshotStatus - :ivar filters: A list of filters used to filter the key-values included in the snapshot. - Required. - :vartype filters: list[~azure.appconfiguration.models.KeyValueFilter] - :ivar composition_type: The composition type describes how the key-values within the snapshot - are composed. The 'key' composition type ensures there are no two key-values containing the - same key. The 'key_label' composition type ensures there are no two key-values containing the - same key and label. Known values are: "key" and "key_label". - :vartype composition_type: str or ~azure.appconfiguration.models.SnapshotComposition - :ivar created: The time that the snapshot was created. - :vartype created: ~datetime.datetime - :ivar expires: The time that the snapshot will expire. - :vartype expires: ~datetime.datetime - :ivar retention_period: The amount of time, in seconds, that a snapshot will remain in the - archived state before expiring. This property is only writable during the creation of a - snapshot. If not specified, the default lifetime of key-value revisions will be used. - :vartype retention_period: int - :ivar size: The size in bytes of the snapshot. - :vartype size: int - :ivar items_count: The amount of key-values in the snapshot. - :vartype items_count: int - :ivar tags: The tags of the snapshot. - :vartype tags: dict[str, str] - :ivar etag: A value representing the current state of the snapshot. - :vartype etag: str - """ - - _validation = { - "name": {"readonly": True}, - "status": {"readonly": True}, - "filters": {"required": True, "max_items": 3, "min_items": 1}, - "created": {"readonly": True}, - "expires": {"readonly": True}, - "retention_period": {"maximum": 7776000, "minimum": 3600}, - "size": {"readonly": True}, - "items_count": {"readonly": True}, - "etag": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "filters": {"key": "filters", "type": "[KeyValueFilter]"}, - "composition_type": {"key": "composition_type", "type": "str"}, - "created": {"key": "created", "type": "iso-8601"}, - "expires": {"key": "expires", "type": "iso-8601"}, - "retention_period": {"key": "retention_period", "type": "int"}, - "size": {"key": "size", "type": "int"}, - "items_count": {"key": "items_count", "type": "int"}, - "tags": {"key": "tags", "type": "{str}"}, - "etag": {"key": "etag", "type": "str"}, - } - - def __init__( - self, - *, - filters: List["_models.KeyValueFilter"], - composition_type: Optional[Union[str, "_models.SnapshotComposition"]] = None, - retention_period: Optional[int] = None, - tags: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword filters: A list of filters used to filter the key-values included in the snapshot. - Required. - :paramtype filters: list[~azure.appconfiguration.models.KeyValueFilter] - :keyword composition_type: The composition type describes how the key-values within the - snapshot are composed. The 'key' composition type ensures there are no two key-values - containing the same key. The 'key_label' composition type ensures there are no two key-values - containing the same key and label. Known values are: "key" and "key_label". - :paramtype composition_type: str or ~azure.appconfiguration.models.SnapshotComposition - :keyword retention_period: The amount of time, in seconds, that a snapshot will remain in the - archived state before expiring. This property is only writable during the creation of a - snapshot. If not specified, the default lifetime of key-value revisions will be used. - :paramtype retention_period: int - :keyword tags: The tags of the snapshot. - :paramtype tags: dict[str, str] - """ - super().__init__(**kwargs) - self.name = None - self.status = None - self.filters = filters - self.composition_type = composition_type - self.created = None - self.expires = None - self.retention_period = retention_period - self.size = None - self.items_count = None - self.tags = tags - self.etag = None - - -class SnapshotListResult(_serialization.Model): - """The result of a snapshot list request. - - :ivar items: The collection value. - :vartype items: list[~azure.appconfiguration.models.Snapshot] - :ivar next_link: The URI that can be used to request the next set of paged results. - :vartype next_link: str - """ - - _attribute_map = { - "items": {"key": "items", "type": "[Snapshot]"}, - "next_link": {"key": "@nextLink", "type": "str"}, - } - - def __init__( - self, *, items: Optional[List["_models.Snapshot"]] = None, next_link: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword items: The collection value. - :paramtype items: list[~azure.appconfiguration.models.Snapshot] - :keyword next_link: The URI that can be used to request the next set of paged results. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.items = items - self.next_link = next_link - - -class SnapshotUpdateParameters(_serialization.Model): - """Parameters used to update a snapshot. - - :ivar status: The desired status of the snapshot. Known values are: "provisioning", "ready", - "archived", and "failed". - :vartype status: str or ~azure.appconfiguration.models.SnapshotStatus - """ - - _attribute_map = { - "status": {"key": "status", "type": "str"}, - } - - def __init__(self, *, status: Optional[Union[str, "_models.SnapshotStatus"]] = None, **kwargs: Any) -> None: - """ - :keyword status: The desired status of the snapshot. Known values are: "provisioning", "ready", - "archived", and "failed". - :paramtype status: str or ~azure.appconfiguration.models.SnapshotStatus - """ - super().__init__(**kwargs) - self.status = status diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/operations/__init__.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/operations/__init__.py deleted file mode 100644 index 374ce030aec3..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/operations/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._azure_app_configuration_operations import AzureAppConfigurationOperationsMixin - -from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "AzureAppConfigurationOperationsMixin", -] -__all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/operations/_patch.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/operations/_patch.py deleted file mode 100644 index 1d0a27bce7a4..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/operations/_patch.py +++ /dev/null @@ -1,173 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - - -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -import urllib.parse -from typing import Any, Iterable, List, Optional, Union -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from ._azure_app_configuration_operations import ( - AzureAppConfigurationOperationsMixin as AzureAppConfigOpGenerated, - ClsType, - build_get_key_values_request, -) -from .. import models as _models - - -class AzureAppConfigurationOperationsMixin(AzureAppConfigOpGenerated): - @distributed_trace - def get_key_values_in_one_page( - self, - key: Optional[str] = None, - label: Optional[str] = None, - after: Optional[str] = None, - accept_datetime: Optional[str] = None, - select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - tags: Optional[List[str]] = None, - continuation_token: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.KeyValue"]: - """Gets a list of key-values in one page. - - Gets a list of key-values in one page. - - :param key: A filter used to match keys. Default value is None. - :type key: str - :param label: A filter used to match labels. Default value is None. - :type label: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param select: Used to select what fields are present in the returned resource(s). Default - value is None. - :type select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] - :param snapshot: A filter used get key-values for a snapshot. The value should be the name of - the snapshot. Not valid when used with 'key' and 'label' filters. Default value is None. - :type snapshot: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param tags: A filter used to query by tags. Default value is None. - :type tags: list[str] - :param str continuation_token: An opaque continuation token. - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either KeyValue or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.appconfiguration.models.KeyValue] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KeyValueListResult] = kwargs.pop("cls", None) - - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_get_key_values_request( - key=key, - label=label, - after=after, - accept_datetime=accept_datetime, - select=select, - if_match=if_match, - if_none_match=if_none_match, - tags=tags, - sync_token=self._config.sync_token, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - else: - # make call to next link with the client's api-version - - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" - return _request - - _request = prepare_request(continuation_token) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error) - response_headers = response.headers - deserialized = self._deserialize("KeyValueListResult", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) - return deserialized - - -__all__: List[str] = [ - "AzureAppConfigurationOperationsMixin" -] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/py.typed b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_model_base.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_model_base.py new file mode 100644 index 000000000000..e6a2730f9276 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_model_base.py @@ -0,0 +1,1159 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from typing_extensions import Self +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): # pylint: disable=unsubscriptable-object + def __init__(self, data: typing.Dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> typing.Tuple[str, typing.Any]: + return self._data.popitem() + + def clear(self) -> None: + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field( + attr_to_rest_field: typing.Dict[str, "_RestField"], rest_name: str +) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: typing.Set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass = { + rest_field._rest_name: rest_field._default + for rest_field in self._attr_to_rest_field.values() + if rest_field._default is not _UNSET + } + if args: # pylint: disable=too-many-nested-blocks + if isinstance(args[0], ET.Element): + existed_attr_keys = [] + model_meta = getattr(self, "_xml", {}) + + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + if prop_meta.get("itemsName"): + xml_name = prop_meta.get("itemsName") + xml_ns = prop_meta.get("itemNs") + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = args[0].findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + continue + + # text element is primitive type + if prop_meta.get("text", False): + if args[0].text is not None: + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = args[0].find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in args[0]: + if e.tag not in existed_attr_keys: + dict_to_pass[e.tag] = _convert_element(e) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + super().__init__(dict_to_pass) + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: typing.Dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) # pylint: disable=no-value-for-parameter + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: typing.Dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: typing.List[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: typing.List[typing.Any]) -> typing.List[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + if annotation._name == "Dict": # pyright: ignore + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + if annotation._name in ["List", "Set", "Tuple", "Sequence"]: # pyright: ignore + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value) + except ValueError: + # for unknown value, return raw value + return value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[typing.List[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[typing.Dict[str, typing.Any]] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + + @property + def _class_type(self) -> typing.Any: + return getattr(self._type, "args", [None])[0] + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + item = obj.get(self._rest_name) + if item is None: + return item + if self._is_model: + return item + return _deserialize(self._type, _serialize(item, self._format), rf=self) + + def __set__(self, obj: Model, value) -> None: + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[typing.List[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[typing.Dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[typing.List[str]] = None, + xml: typing.Optional[typing.Dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[typing.Dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, typing.List[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + wrapped_element = _create_xml_element( + model_meta.get("name", o.__class__.__name__), + model_meta.get("prefix"), + model_meta.get("ns"), + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # if no ns for prop, use model's + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + xml_name = prop_meta.get("name", k) + if prop_meta.get("ns"): + ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore + xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore + # attribute should be primitive type + wrapped_element.set(xml_name, _get_primitive_type_value(v)) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": parent_meta.get("ns") if parent_meta else None, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": parent_meta.get("itemsNs", parent_meta.get("ns")), + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[typing.Dict[str, typing.Any]], +) -> ET.Element: + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _create_xml_element(tag, prefix=None, ns=None): + if prefix and ns: + ET.register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: typing.Dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: typing.List[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_models.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_models.py deleted file mode 100644 index a0df4eeaec18..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_models.py +++ /dev/null @@ -1,653 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -import json -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, cast, Callable - -from azure.core.async_paging import AsyncList -from azure.core.rest import HttpResponse -from azure.core.paging import PageIterator -from azure.core.async_paging import AsyncPageIterator -from ._generated._serialization import Model -from ._generated.models import ( - KeyValue, - KeyValueFilter, - Snapshot as GeneratedConfigurationSnapshot, - SnapshotStatus, - SnapshotComposition, -) - - -class ConfigurationSetting(Model): - """A setting, defined by a unique combination of a key and label.""" - - value: str - """The value of the configuration setting.""" - etag: str - """A value representing the current state of the resource.""" - key: str - """The key of the configuration setting.""" - label: str - """The label of the configuration setting.""" - content_type: Optional[str] - """The content_type of the configuration setting.""" - last_modified: datetime - """A date representing the last time the key-value was modified.""" - read_only: bool - """Indicates whether the key-value is locked.""" - tags: Dict[str, str] - """The tags assigned to the configuration setting.""" - - _attribute_map = { - "etag": {"key": "etag", "type": "str"}, - "key": {"key": "key", "type": "str"}, - "label": {"key": "label", "type": "str"}, - "content_type": {"key": "content_type", "type": "str"}, - "value": {"key": "value", "type": "str"}, - "last_modified": {"key": "last_modified", "type": "iso-8601"}, - "read_only": {"key": "read_only", "type": "bool"}, - "tags": {"key": "tags", "type": "{str}"}, - } - - kind = "Generic" - content_type = None - - def __init__(self, **kwargs: Any) -> None: - super(ConfigurationSetting, self).__init__(**kwargs) - self.key = kwargs.get("key", None) - self.label = kwargs.get("label", None) - self.value = kwargs.get("value", None) - self.etag = kwargs.get("etag", None) - self.content_type = kwargs.get("content_type", None) - self.last_modified = kwargs.get("last_modified", None) - self.read_only = kwargs.get("read_only", None) - self.tags = kwargs.get("tags", {}) - - @classmethod - def _from_generated(cls, key_value: KeyValue) -> "ConfigurationSetting": - # pylint:disable=protected-access - if key_value.content_type is not None: - try: - if key_value.content_type.startswith( - FeatureFlagConfigurationSetting._feature_flag_content_type - ) and key_value.key.startswith( # type: ignore - FeatureFlagConfigurationSetting._key_prefix - ): - config_setting = FeatureFlagConfigurationSetting._from_generated(key_value) - if key_value.value: - config_setting.value = key_value.value - return config_setting - if key_value.content_type.startswith( - SecretReferenceConfigurationSetting._secret_reference_content_type - ): - return SecretReferenceConfigurationSetting._from_generated(key_value) - except (KeyError, AttributeError): - pass - - return cls( - key=key_value.key, - label=key_value.label, - value=key_value.value, - content_type=key_value.content_type, - last_modified=key_value.last_modified, - tags=key_value.tags, - read_only=key_value.locked, - etag=key_value.etag, - ) - - def _to_generated(self) -> KeyValue: - return KeyValue( - key=self.key, - label=self.label, - value=self.value, - content_type=self.content_type, - last_modified=self.last_modified, - tags=self.tags, - locked=self.read_only, - etag=self.etag, - ) - - -class FeatureFlagConfigurationSetting(ConfigurationSetting): # pylint: disable=too-many-instance-attributes - """A configuration setting that stores a feature flag value.""" - - etag: str - """A value representing the current state of the resource.""" - feature_id: str - """The identity of the configuration setting.""" - key: str - """The key of the configuration setting.""" - enabled: bool - """The value indicating whether the feature flag is enabled. A feature is OFF if enabled is false. - If enabled is true, then the feature is ON if there are no conditions or if all conditions are satisfied.""" - filters: Optional[List[Dict[str, Any]]] - """Filters that must run on the client and be evaluated as true for the feature - to be considered enabled.""" - label: str - """The label used to group this configuration setting with others.""" - display_name: str - """The name for the feature to use for display rather than the ID.""" - description: str - """The description of the feature.""" - content_type: str - """The content_type of the configuration setting.""" - last_modified: datetime - """A date representing the last time the key-value was modified.""" - read_only: bool - """Indicates whether the key-value is locked.""" - tags: Dict[str, str] - """The tags assigned to the configuration setting.""" - - _attribute_map = { - "etag": {"key": "etag", "type": "str"}, - "feature_id": {"key": "feature_id", "type": "str"}, - "label": {"key": "label", "type": "str"}, - "content_type": {"key": "_feature_flag_content_type", "type": "str"}, - "value": {"key": "value", "type": "str"}, - "last_modified": {"key": "last_modified", "type": "iso-8601"}, - "read_only": {"key": "read_only", "type": "bool"}, - "tags": {"key": "tags", "type": "{str}"}, - } - _key_prefix = ".appconfig.featureflag/" - _feature_flag_content_type = "application/vnd.microsoft.appconfig.ff+json;charset=utf-8" - kind = "FeatureFlag" - - def __init__( # pylint: disable=super-init-not-called - self, - feature_id: str, - *, - enabled: bool = False, - filters: Optional[List[Dict[str, Any]]] = None, - **kwargs: Any, - ) -> None: - """ - :param feature_id: The identity of the configuration setting. - :type feature_id: str - :keyword enabled: The value indicating whether the feature flag is enabled. - A feature is OFF if enabled is false. If enabled is true, then the feature is ON - if there are no conditions or if all conditions are satisfied. Default value of this property is False. - :paramtype enabled: bool - :keyword filters: Filters that must run on the client and be evaluated as true for the feature - to be considered enabled. - :paramtype filters: list[dict[str, Any]] or None - """ - if "value" in kwargs: - raise TypeError("Unexpected keyword argument, do not provide 'value' as a keyword-arg") - self.feature_id = feature_id - self.key = kwargs.get("key", None) or (self._key_prefix + self.feature_id) - self.label = kwargs.get("label", None) - self.content_type = kwargs.get("content_type", self._feature_flag_content_type) - self.last_modified = kwargs.get("last_modified", None) - self.tags = kwargs.get("tags", {}) - self.read_only = kwargs.get("read_only", None) - self.etag = kwargs.get("etag", None) - self.description = kwargs.get("description", None) - self.display_name = kwargs.get("display_name", None) - self.filters = [] if filters is None else filters - self.enabled = enabled - self._value = json.dumps( - {"id": self.feature_id, "enabled": self.enabled, "conditions": {"client_filters": self.filters}} - ) - - @property - def value(self) -> str: - """The value of the configuration setting. - - :rtype: str - """ - try: - temp = json.loads(self._value) - temp["id"] = self.feature_id - temp["enabled"] = self.enabled - temp["display_name"] = self.display_name - temp["description"] = self.description - if "conditions" not in temp.keys(): - temp["conditions"] = {} - temp["conditions"]["client_filters"] = self.filters - self._value = json.dumps(temp) - return self._value - except (json.JSONDecodeError, ValueError): - return self._value - - @value.setter - def value(self, new_value: str) -> None: - try: - temp = json.loads(new_value) - temp["id"] = self.feature_id - self._value = json.dumps(temp) - self.enabled = temp.get("enabled", False) - self.display_name = temp.get("display_name", None) - self.description = temp.get("description", None) - self.filters = None - conditions = temp.get("conditions", None) - if conditions: - self.filters = conditions.get("client_filters", None) - except (json.JSONDecodeError, ValueError): - self._value = new_value - self.enabled = False - self.filters = None - - @classmethod - def _from_generated(cls, key_value: KeyValue) -> "FeatureFlagConfigurationSetting": - enabled = False - filters = None - display_name = None - description = None - feature_id = None - try: - temp = json.loads(key_value.value) # type: ignore - if isinstance(temp, dict): - enabled = temp.get("enabled", False) - display_name = temp.get("display_name") - description = temp.get("description") - feature_id = temp.get("id") - - if "conditions" in temp.keys(): - filters = temp["conditions"].get("client_filters") - except (ValueError, json.JSONDecodeError): - pass - - return cls( - feature_id=feature_id, # type: ignore - key=key_value.key, - label=key_value.label, - content_type=key_value.content_type, - last_modified=key_value.last_modified, - tags=key_value.tags, - read_only=key_value.locked, - etag=key_value.etag, - enabled=enabled, - filters=filters, - display_name=display_name, - description=description, - ) - - def _to_generated(self) -> KeyValue: - return KeyValue( - key=self.key, - label=self.label, - value=self.value, - content_type=self.content_type, - last_modified=self.last_modified, - tags=self.tags, - locked=self.read_only, - etag=self.etag, - ) - - -class SecretReferenceConfigurationSetting(ConfigurationSetting): - """A configuration value that references a configuration setting secret.""" - - etag: str - """A value representing the current state of the resource.""" - key: str - """The key of the configuration setting.""" - secret_id: Optional[str] - """The identity of the configuration setting.""" - label: str - """The label used to group this configuration setting with others.""" - content_type: str - """The content_type of the configuration setting.""" - last_modified: datetime - """A date representing the last time the key-value was modified.""" - read_only: bool - """Indicates whether the key-value is locked.""" - tags: Dict[str, str] - """The tags assigned to the configuration setting.""" - - _attribute_map = { - "etag": {"key": "etag", "type": "str"}, - "key": {"key": "key", "type": "str"}, - "label": {"key": "label", "type": "str"}, - "content_type": {"key": "content_type", "type": "str"}, - "value": {"key": "value", "type": "str"}, - "last_modified": {"key": "last_modified", "type": "iso-8601"}, - "read_only": {"key": "read_only", "type": "bool"}, - "tags": {"key": "tags", "type": "{str}"}, - } - _secret_reference_content_type = "application/vnd.microsoft.appconfig.keyvaultref+json;charset=utf-8" - kind = "SecretReference" - - def __init__(self, key: str, secret_id: str, **kwargs: Any) -> None: # pylint: disable=super-init-not-called - """ - :param key: The key of the configuration setting. - :type key: str - :param secret_id: The identity of the configuration setting. - :type secret_id: str - """ - if "value" in kwargs: - raise TypeError("Unexpected keyword argument, do not provide 'value' as a keyword-arg") - self.key = key - self.label = kwargs.pop("label", None) - self.content_type = kwargs.get("content_type", self._secret_reference_content_type) - self.etag = kwargs.get("etag", None) - self.last_modified = kwargs.get("last_modified", None) - self.read_only = kwargs.get("read_only", None) - self.tags = kwargs.get("tags", {}) - self.secret_id = secret_id - self._value = json.dumps({"uri": secret_id}) - - @property - def value(self) -> str: - """The value of the configuration setting. - - :rtype: str - """ - try: - temp = json.loads(self._value) - temp["uri"] = self.secret_id - self._value = json.dumps(temp) - return self._value - except (json.JSONDecodeError, ValueError): - return self._value - - @value.setter - def value(self, new_value: str) -> None: - try: - temp = json.loads(new_value) - self._value = new_value - self.secret_id = temp.get("uri") - except (json.JSONDecodeError, ValueError): - self._value = new_value - self.secret_id = None - - @classmethod - def _from_generated(cls, key_value: KeyValue) -> "SecretReferenceConfigurationSetting": - secret_uri = None - try: - temp = json.loads(key_value.value) # type: ignore - secret_uri = temp.get("uri") - if not secret_uri: - secret_uri = temp.get("secret_uri") - except (ValueError, json.JSONDecodeError): - pass - - return cls( - key=key_value.key, # type: ignore - label=key_value.label, - secret_id=secret_uri, # type: ignore - last_modified=key_value.last_modified, - tags=key_value.tags, - read_only=key_value.locked, - etag=key_value.etag, - ) - - def _to_generated(self) -> KeyValue: - return KeyValue( - key=self.key, - label=self.label, - value=self.value, - content_type=self.content_type, - last_modified=self.last_modified, - tags=self.tags, - locked=self.read_only, - etag=self.etag, - ) - - -class ConfigurationSettingsFilter: - """Enables filtering of configuration settings.""" - - key: str - """Filters configuration settings by their key field. Required.""" - label: Optional[str] - """Filters configuration settings by their label field.""" - tags: Optional[List[str]] - """Filters key-values by their tags field.""" - - def __init__(self, *, key: str, label: Optional[str] = None, tags: Optional[List[str]] = None) -> None: - """ - :keyword key: Filters configuration settings by their key field. Required. - :paramtype key: str - :keyword label: Filters configuration settings by their label field. - :paramtype label: str or None - :keyword tags: Filters key-values by their tags field. - :paramtype tags: list[str] or None - """ - self.key = key - self.label = label - self.tags = tags - - -class ConfigurationSnapshot: # pylint: disable=too-many-instance-attributes - """A point-in-time snapshot of configuration settings.""" - - name: Optional[str] - """The name of the configuration snapshot.""" - status: Optional[Union[str, SnapshotStatus]] - """The current status of the snapshot. Known values are: "provisioning", "ready", - "archived", and "failed".""" - filters: List[ConfigurationSettingsFilter] - """A list of filters used to filter the key-values included in the configuration snapshot. Required.""" - composition_type: Optional[Union[str, SnapshotComposition]] - """The composition type describes how the key-values within the configuration snapshot - are composed. The 'key' composition type ensures there are no two key-values containing the - same key. The 'key_label' composition type ensures there are no two key-values containing the - same key and label. Known values are: "key" and "key_label".""" - created: Optional[datetime] - """The time that the configuration snapshot was created.""" - expires: Optional[datetime] - """The time that the configuration snapshot will expire.""" - retention_period: Optional[int] - """The amount of time, in seconds, that a configuration snapshot will remain in the - archived state before expiring. This property is only writable during the creation of a configuration - snapshot. If not specified, the default lifetime of key-value revisions will be used.""" - size: Optional[int] - """The size in bytes of the configuration snapshot.""" - items_count: Optional[int] - """The amount of key-values in the configuration snapshot.""" - tags: Optional[Dict[str, str]] - """The tags of the configuration snapshot.""" - etag: Optional[str] - """A value representing the current state of the configuration snapshot.""" - - def __init__( - self, - filters: List[ConfigurationSettingsFilter], - *, - composition_type: Optional[Union[str, SnapshotComposition]] = None, - retention_period: Optional[int] = None, - tags: Optional[Dict[str, str]] = None, - ) -> None: - """ - :param filters: A list of filters used to filter the key-values included in the configuration snapshot. - Required. - :type filters: list[~azure.appconfiguration.ConfigurationSettingsFilter] - :keyword composition_type: The composition type describes how the key-values within the configuration - snapshot are composed. The 'key' composition type ensures there are no two key-values - containing the same key. The 'key_label' composition type ensures there are no two key-values - containing the same key and label. Known values are: "key" and "key_label". - :paramtype composition_type: str or None - :keyword retention_period: The amount of time, in seconds, that a configuration snapshot will remain in the - archived state before expiring. This property is only writable during the creation of a configuration - snapshot. If not specified, the default lifetime of key-value revisions will be used. - :paramtype retention_period: int or None - :keyword tags: The tags of the configuration snapshot. - :paramtype tags: dict[str, str] or None - """ - self.name = None - self.status = None - self.filters = filters - self.composition_type = composition_type - self.created = None - self.expires = None - self.retention_period = retention_period - self.size = None - self.items_count = None - self.tags = tags - self.etag = None - - @classmethod - def _from_generated(cls, generated: GeneratedConfigurationSnapshot) -> "ConfigurationSnapshot": - if generated is None: - return generated - - filters = [] - if generated.filters: - for config_setting_filter in generated.filters: - filters.append( - ConfigurationSettingsFilter( - key=config_setting_filter.key, - label=config_setting_filter.label, - tags=config_setting_filter.tags, - ) - ) - snapshot = cls( - filters=filters, - composition_type=cast(SnapshotComposition, generated.composition_type), - retention_period=generated.retention_period, - tags=generated.tags, - ) - snapshot.name = generated.name - snapshot.status = generated.status - snapshot.created = generated.created - snapshot.expires = generated.expires - snapshot.size = generated.size - snapshot.items_count = generated.items_count - snapshot.etag = generated.etag - - return snapshot - - @classmethod - def _from_deserialized( - cls, - response: HttpResponse, # pylint:disable=unused-argument - deserialized: GeneratedConfigurationSnapshot, - response_headers: Dict, # pylint:disable=unused-argument - ) -> "ConfigurationSnapshot": - if deserialized is None: - return deserialized - filters = [] - if deserialized.filters: - for config_setting_filter in deserialized.filters: - filters.append( - ConfigurationSettingsFilter( - key=config_setting_filter.key, - label=config_setting_filter.label, - tags=config_setting_filter.tags, - ) - ) - snapshot = cls( - filters=filters, - composition_type=cast(SnapshotComposition, deserialized.composition_type), - retention_period=deserialized.retention_period, - tags=deserialized.tags, - ) - snapshot.name = deserialized.name - snapshot.status = deserialized.status - snapshot.created = deserialized.created - snapshot.expires = deserialized.expires - snapshot.size = deserialized.size - snapshot.items_count = deserialized.items_count - snapshot.etag = deserialized.etag - - return snapshot - - def _to_generated(self) -> GeneratedConfigurationSnapshot: - config_setting_filters = [] - for kv_filter in self.filters: - config_setting_filters.append(KeyValueFilter(key=kv_filter.key, label=kv_filter.label, tags=kv_filter.tags)) - return GeneratedConfigurationSnapshot( - filters=config_setting_filters, - composition_type=self.composition_type, - retention_period=self.retention_period, - tags=self.tags, - ) - - -class ConfigurationSettingLabel: - """The label info of a configuration setting.""" - - name: Optional[str] - """The name of the ConfigurationSetting label.""" - - def __init__(self, *, name: Optional[str] = None) -> None: - """ - :keyword name: The configuration setting label name. - :paramtype composition_type: str or None - """ - self.name = name - - -def _return_deserialized_and_headers(_, deserialized, response_headers): - return deserialized, response_headers - - -class ConfigurationSettingPropertiesPaged(PageIterator): - """An iterable of ConfigurationSetting properties.""" - - etag: str - """The etag of current page.""" - - def __init__(self, command: Callable, **kwargs: Any): - super(ConfigurationSettingPropertiesPaged, self).__init__( - self._get_next_cb, - self._extract_data_cb, - continuation_token=kwargs.get("continuation_token"), - ) - self._command = command - self._key = kwargs.get("key") - self._label = kwargs.get("label") - self._accept_datetime = kwargs.get("accept_datetime") - self._select = kwargs.get("select") - self._tags = kwargs.get("tags") - self._deserializer = lambda objs: [ - ConfigurationSetting._from_generated(x) for x in objs # pylint:disable=protected-access - ] - - def _get_next_cb(self, continuation_token, **kwargs): - return self._command( - key=self._key, - label=self._label, - accept_datetime=self._accept_datetime, - select=self._select, - tags=self._tags, - continuation_token=continuation_token, - cls=kwargs.pop("cls", None) or _return_deserialized_and_headers, - ) - - def _extract_data_cb(self, get_next_return): - deserialized, response_headers = get_next_return - self.etag = response_headers.pop("ETag") - return deserialized.next_link or None, iter(self._deserializer(deserialized.items)) - - -class ConfigurationSettingPropertiesPagedAsync(AsyncPageIterator): - """An iterable of ConfigurationSetting properties.""" - - etag: str - """The etag of current page.""" - - def __init__(self, command: Callable, **kwargs: Any): - super(ConfigurationSettingPropertiesPagedAsync, self).__init__( - self._get_next_cb, - self._extract_data_cb, - continuation_token=kwargs.get("continuation_token"), - ) - self._command = command - self._key = kwargs.get("key") - self._label = kwargs.get("label") - self._accept_datetime = kwargs.get("accept_datetime") - self._select = kwargs.get("select") - self._tags = kwargs.get("tags") - self._deserializer = lambda objs: [ - ConfigurationSetting._from_generated(x) for x in objs # pylint:disable=protected-access - ] - - async def _get_next_cb(self, continuation_token, **kwargs): - return await self._command( - key=self._key, - label=self._label, - accept_datetime=self._accept_datetime, - select=self._select, - tags=self._tags, - continuation_token=continuation_token, - cls=kwargs.pop("cls", None) or _return_deserialized_and_headers, - ) - - async def _extract_data_cb(self, get_next_return): - deserialized, response_headers = get_next_return - self.etag = response_headers.pop("ETag") - return deserialized.next_link or None, AsyncList(self._deserializer(deserialized.items)) diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/__init__.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_operations/__init__.py similarity index 56% rename from sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/__init__.py rename to sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_operations/__init__.py index 75469c2e980c..a90b04c612d7 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/__init__.py +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_operations/__init__.py @@ -2,22 +2,24 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._azure_app_configuration import AzureAppConfiguration +from typing import TYPE_CHECKING -try: - from ._patch import __all__ as _patch_all +if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] + +from ._operations import AzureAppConfigurationClientOperationsMixin # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AzureAppConfiguration", + "AzureAppConfigurationClientOperationsMixin", ] -__all__.extend([p for p in _patch_all if p not in __all__]) - +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/operations/_azure_app_configuration_operations.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_operations/_operations.py similarity index 62% rename from sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/operations/_azure_app_configuration_operations.py rename to sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_operations/_operations.py index 9bb8f1696458..99a83486f47a 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/operations/_azure_app_configuration_operations.py +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_operations/_operations.py @@ -1,20 +1,23 @@ -# pylint: disable=too-many-lines,too-many-statements +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase +import json import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, List, Optional, Type, TypeVar, Union, cast, overload +from typing import Any, Callable, Dict, IO, Iterable, Iterator, List, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import MatchConditions from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, + ResourceModifiedError, ResourceNotFoundError, ResourceNotModifiedError, StreamClosedError, @@ -30,13 +33,15 @@ from azure.core.utils import case_insensitive_dict from .. import models as _models +from .._model_base import SdkJSONEncoder, _deserialize from .._serialization import Serializer -from .._vendor import AzureAppConfigurationMixinABC +from .._vendor import AzureAppConfigurationClientMixinABC, prep_if_match, prep_if_none_match if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -44,27 +49,27 @@ _SERIALIZER.client_side_validation = False -def build_get_keys_request( +def build_azure_app_configuration_get_keys_request( # pylint: disable=name-too-long *, name: Optional[str] = None, after: Optional[str] = None, - accept_datetime: Optional[str] = None, sync_token: Optional[str] = None, + accept_datetime: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) - accept = _headers.pop("Accept", "application/vnd.microsoft.appconfig.keyset+json, application/problem+json") + accept = _headers.pop("Accept", None) # Construct URL - _url = kwargs.pop("template_url", "/keys") + _url = "/keys" # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if name is not None: _params["name"] = _SERIALIZER.query("name", name, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if after is not None: _params["After"] = _SERIALIZER.query("after", after, "str") @@ -73,30 +78,33 @@ def build_get_keys_request( _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") if accept_datetime is not None: _headers["Accept-Datetime"] = _SERIALIZER.header("accept_datetime", accept_datetime, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if accept is not None: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_check_keys_request( +def build_azure_app_configuration_check_keys_request( # pylint: disable=name-too-long *, name: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, - sync_token: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/keys") + _url = "/keys" # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if name is not None: _params["name"] = _SERIALIZER.query("name", name, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if after is not None: _params["After"] = _SERIALIZER.query("after", after, "str") @@ -105,39 +113,40 @@ def build_check_keys_request( _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") if accept_datetime is not None: _headers["Accept-Datetime"] = _SERIALIZER.header("accept_datetime", accept_datetime, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_key_values_request( +def build_azure_app_configuration_get_key_values_request( # pylint: disable=name-too-long *, key: Optional[str] = None, label: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, snapshot: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, tags: Optional[List[str]] = None, - sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) - accept = _headers.pop("Accept", "application/vnd.microsoft.appconfig.kvset+json, application/problem+json") + accept = _headers.pop("Accept", None) # Construct URL - _url = kwargs.pop("template_url", "/kv") + _url = "/kv" # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if key is not None: _params["key"] = _SERIALIZER.query("key", key, "str") if label is not None: _params["label"] = _SERIALIZER.query("label", label, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if after is not None: _params["After"] = _SERIALIZER.query("after", after, "str") if select is not None: @@ -152,42 +161,47 @@ def build_get_key_values_request( _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") if accept_datetime is not None: _headers["Accept-Datetime"] = _SERIALIZER.header("accept_datetime", accept_datetime, "str") + if accept is not None: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) if if_none_match is not None: _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_check_key_values_request( +def build_azure_app_configuration_check_key_values_request( # pylint: disable=name-too-long *, key: Optional[str] = None, label: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, snapshot: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, tags: Optional[List[str]] = None, - sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/kv") + _url = "/kv" # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if key is not None: _params["key"] = _SERIALIZER.query("key", key, "str") if label is not None: _params["label"] = _SERIALIZER.query("label", label, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if after is not None: _params["After"] = _SERIALIZER.query("after", after, "str") if select is not None: @@ -202,33 +216,36 @@ def build_check_key_values_request( _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") if accept_datetime is not None: _headers["Accept-Datetime"] = _SERIALIZER.header("accept_datetime", accept_datetime, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) if if_none_match is not None: _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_key_value_request( +def build_azure_app_configuration_get_key_value_request( # pylint: disable=name-too-long key: str, *, label: Optional[str] = None, - accept_datetime: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, sync_token: Optional[str] = None, + accept_datetime: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) - accept = _headers.pop("Accept", "application/vnd.microsoft.appconfig.kv+json, application/problem+json") + accept = _headers.pop("Accept", None) # Construct URL - _url = kwargs.pop("template_url", "/kv/{key}") + _url = "/kv/{key}" path_format_arguments = { "key": _SERIALIZER.url("key", key, "str"), } @@ -236,9 +253,9 @@ def build_get_key_value_request( _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if label is not None: _params["label"] = _SERIALIZER.query("label", label, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if select is not None: _params["$Select"] = _SERIALIZER.query("select", select, "[str]", div=",") @@ -247,33 +264,36 @@ def build_get_key_value_request( _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") if accept_datetime is not None: _headers["Accept-Datetime"] = _SERIALIZER.header("accept_datetime", accept_datetime, "str") + if accept is not None: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) if if_none_match is not None: _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_put_key_value_request( +def build_azure_app_configuration_put_key_value_request( # pylint: disable=name-too-long key: str, *, label: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/vnd.microsoft.appconfig.kv+json, application/problem+json") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) + accept = _headers.pop("Accept", None) # Construct URL - _url = kwargs.pop("template_url", "/kv/{key}") + _url = "/kv/{key}" path_format_arguments = { "key": _SERIALIZER.url("key", key, "str"), } @@ -281,40 +301,44 @@ def build_put_key_value_request( _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if label is not None: _params["label"] = _SERIALIZER.query("label", label, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") if sync_token is not None: _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") + if accept is not None: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) if if_none_match is not None: _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_key_value_request( +def build_azure_app_configuration_delete_key_value_request( # pylint: disable=name-too-long key: str, *, label: Optional[str] = None, - if_match: Optional[str] = None, sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) - accept = _headers.pop("Accept", "application/vnd.microsoft.appconfig.kv+json, application/problem+json") + accept = _headers.pop("Accept", None) # Construct URL - _url = kwargs.pop("template_url", "/kv/{key}") + _url = "/kv/{key}" path_format_arguments = { "key": _SERIALIZER.url("key", key, "str"), } @@ -322,37 +346,44 @@ def build_delete_key_value_request( _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if label is not None: _params["label"] = _SERIALIZER.query("label", label, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if sync_token is not None: _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") + if accept is not None: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_none_match = prep_if_none_match(etag, match_condition) + if if_none_match is not None: + _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_check_key_value_request( +def build_azure_app_configuration_check_key_value_request( # pylint: disable=name-too-long key: str, *, label: Optional[str] = None, + sync_token: Optional[str] = None, accept_datetime: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, - sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/kv/{key}") + _url = "/kv/{key}" path_format_arguments = { "key": _SERIALIZER.url("key", key, "str"), } @@ -360,9 +391,9 @@ def build_check_key_value_request( _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if label is not None: _params["label"] = _SERIALIZER.query("label", label, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if select is not None: _params["$Select"] = _SERIALIZER.query("select", select, "[str]", div=",") @@ -371,15 +402,18 @@ def build_check_key_value_request( _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") if accept_datetime is not None: _headers["Accept-Datetime"] = _SERIALIZER.header("accept_datetime", accept_datetime, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) if if_none_match is not None: _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_snapshots_request( +def build_azure_app_configuration_get_snapshots_request( # pylint: disable=name-too-long *, name: Optional[str] = None, after: Optional[str] = None, @@ -392,15 +426,15 @@ def build_get_snapshots_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) - accept = _headers.pop("Accept", "application/vnd.microsoft.appconfig.snapshotset+json, application/problem+json") + accept = _headers.pop("Accept", None) # Construct URL - _url = kwargs.pop("template_url", "/snapshots") + _url = "/snapshots" # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if name is not None: _params["name"] = _SERIALIZER.query("name", name, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if after is not None: _params["After"] = _SERIALIZER.query("after", after, "str") if select is not None: @@ -411,20 +445,23 @@ def build_get_snapshots_request( # Construct headers if sync_token is not None: _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if accept is not None: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_check_snapshots_request( - *, after: Optional[str] = None, sync_token: Optional[str] = None, **kwargs: Any +def build_azure_app_configuration_check_snapshots_request( # pylint: disable=name-too-long + *, sync_token: Optional[str] = None, after: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/snapshots") + _url = "/snapshots" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -434,27 +471,28 @@ def build_check_snapshots_request( # Construct headers if sync_token is not None: _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_snapshot_request( +def build_azure_app_configuration_get_snapshot_request( # pylint: disable=name-too-long name: str, *, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, select: Optional[List[Union[str, _models.SnapshotFields]]] = None, sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) - accept = _headers.pop("Accept", "application/vnd.microsoft.appconfig.snapshot+json, application/problem+json") + accept = _headers.pop("Accept", None) # Construct URL - _url = kwargs.pop("template_url", "/snapshots/{name}") + _url = "/snapshots/{name}" path_format_arguments = { "name": _SERIALIZER.url("name", name, "str"), } @@ -469,27 +507,54 @@ def build_get_snapshot_request( # Construct headers if sync_token is not None: _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") + if accept is not None: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) if if_none_match is not None: _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_create_snapshot_request(name: str, *, sync_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: +def build_azure_app_configuration_get_operation_details_request( # pylint: disable=name-too-long + *, snapshot: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/operations" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["snapshot"] = _SERIALIZER.query("snapshot", snapshot, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_azure_app_configuration_create_snapshot_request( # pylint: disable=name-too-long + name: str, *, sync_token: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/vnd.microsoft.appconfig.snapshot+json, application/problem+json") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) + accept = _headers.pop("Accept", None) # Construct URL - _url = kwargs.pop("template_url", "/snapshots/{name}") + _url = "/snapshots/{name}" path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str", max_length=256), + "name": _SERIALIZER.url("name", name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -498,32 +563,33 @@ def build_create_snapshot_request(name: str, *, sync_token: Optional[str] = None _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if sync_token is not None: - _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if sync_token is not None: + _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") + if accept is not None: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_update_snapshot_request( +def build_azure_app_configuration_update_snapshot_request( # pylint: disable=name-too-long name: str, *, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/vnd.microsoft.appconfig.snapshot+json, application/problem+json") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) + accept = _headers.pop("Accept", None) # Construct URL - _url = kwargs.pop("template_url", "/snapshots/{name}") + _url = "/snapshots/{name}" path_format_arguments = { "name": _SERIALIZER.url("name", name, "str"), } @@ -534,33 +600,38 @@ def build_update_snapshot_request( _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") if sync_token is not None: _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") + if accept is not None: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) if if_none_match is not None: _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_check_snapshot_request( +def build_azure_app_configuration_check_snapshot_request( # pylint: disable=name-too-long name: str, *, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/snapshots/{name}") + _url = "/snapshots/{name}" path_format_arguments = { "name": _SERIALIZER.url("name", name, "str"), } @@ -573,36 +644,39 @@ def build_check_snapshot_request( # Construct headers if sync_token is not None: _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) if if_none_match is not None: _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_labels_request( +def build_azure_app_configuration_get_labels_request( # pylint: disable=name-too-long *, name: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.LabelFields]]] = None, - sync_token: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) - accept = _headers.pop("Accept", "application/vnd.microsoft.appconfig.labelset+json, application/problem+json") + accept = _headers.pop("Accept", None) # Construct URL - _url = kwargs.pop("template_url", "/labels") + _url = "/labels" # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if name is not None: _params["name"] = _SERIALIZER.query("name", name, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if after is not None: _params["After"] = _SERIALIZER.query("after", after, "str") if select is not None: @@ -613,31 +687,34 @@ def build_get_labels_request( _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") if accept_datetime is not None: _headers["Accept-Datetime"] = _SERIALIZER.header("accept_datetime", accept_datetime, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if accept is not None: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_check_labels_request( +def build_azure_app_configuration_check_labels_request( # pylint: disable=name-too-long *, name: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.LabelFields]]] = None, - sync_token: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/labels") + _url = "/labels" # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if name is not None: _params["name"] = _SERIALIZER.query("name", name, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if after is not None: _params["After"] = _SERIALIZER.query("after", after, "str") if select is not None: @@ -648,27 +725,28 @@ def build_check_labels_request( _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") if accept_datetime is not None: _headers["Accept-Datetime"] = _SERIALIZER.header("accept_datetime", accept_datetime, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) -def build_put_lock_request( +def build_azure_app_configuration_put_lock_request( # pylint: disable=name-too-long key: str, *, label: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) - accept = _headers.pop("Accept", "application/vnd.microsoft.appconfig.kv+json, application/problem+json") + accept = _headers.pop("Accept", None) # Construct URL - _url = kwargs.pop("template_url", "/locks/{key}") + _url = "/locks/{key}" path_format_arguments = { "key": _SERIALIZER.url("key", key, "str"), } @@ -676,39 +754,42 @@ def build_put_lock_request( _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if label is not None: _params["label"] = _SERIALIZER.query("label", label, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if sync_token is not None: _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") + if accept is not None: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) if if_none_match is not None: _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_lock_request( +def build_azure_app_configuration_delete_lock_request( # pylint: disable=name-too-long key: str, *, label: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) - accept = _headers.pop("Accept", "application/vnd.microsoft.appconfig.kv+json, application/problem+json") + accept = _headers.pop("Accept", None) # Construct URL - _url = kwargs.pop("template_url", "/locks/{key}") + _url = "/locks/{key}" path_format_arguments = { "key": _SERIALIZER.url("key", key, "str"), } @@ -716,48 +797,51 @@ def build_delete_lock_request( _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if label is not None: _params["label"] = _SERIALIZER.query("label", label, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if sync_token is not None: _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") + if accept is not None: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") + if_none_match = prep_if_none_match(etag, match_condition) if if_none_match is not None: _headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_revisions_request( +def build_azure_app_configuration_get_revisions_request( # pylint: disable=name-too-long *, key: Optional[str] = None, label: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, tags: Optional[List[str]] = None, - sync_token: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) - accept = _headers.pop("Accept", "application/vnd.microsoft.appconfig.kvset+json, application/problem+json") + accept = _headers.pop("Accept", None) # Construct URL - _url = kwargs.pop("template_url", "/revisions") + _url = "/revisions" # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if key is not None: _params["key"] = _SERIALIZER.query("key", key, "str") if label is not None: _params["label"] = _SERIALIZER.query("label", label, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if after is not None: _params["After"] = _SERIALIZER.query("after", after, "str") if select is not None: @@ -770,35 +854,38 @@ def build_get_revisions_request( _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") if accept_datetime is not None: _headers["Accept-Datetime"] = _SERIALIZER.header("accept_datetime", accept_datetime, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if accept is not None: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_check_revisions_request( +def build_azure_app_configuration_check_revisions_request( # pylint: disable=name-too-long *, key: Optional[str] = None, label: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, tags: Optional[List[str]] = None, - sync_token: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/revisions") + _url = "/revisions" # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if key is not None: _params["key"] = _SERIALIZER.query("key", key, "str") if label is not None: _params["label"] = _SERIALIZER.query("label", label, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if after is not None: _params["After"] = _SERIALIZER.query("after", after, "str") if select is not None: @@ -811,37 +898,22 @@ def build_check_revisions_request( _headers["Sync-Token"] = _SERIALIZER.header("sync_token", sync_token, "str") if accept_datetime is not None: _headers["Accept-Datetime"] = _SERIALIZER.header("accept_datetime", accept_datetime, "str") - - return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_operation_details_request(*, snapshot: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/operations") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["snapshot"] = _SERIALIZER.query("snapshot", snapshot, "str") - - # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) -class AzureAppConfigurationOperationsMixin(AzureAppConfigurationMixinABC): # pylint: disable=too-many-public-methods +class AzureAppConfigurationClientOperationsMixin( # pylint: disable=too-many-public-methods,name-too-long + AzureAppConfigurationClientMixinABC +): @distributed_trace def get_keys( self, + *, name: Optional[str] = None, after: Optional[str] = None, + sync_token: Optional[str] = None, accept_datetime: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Key"]: @@ -849,25 +921,28 @@ def get_keys( Gets a list of keys. - :param name: A filter for the name of the returned keys. Default value is None. - :type name: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :return: An iterator like instance of either Key or the result of cls(response) + :keyword name: A filter for the name of the returned keys. Default value is None. + :paramtype name: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :return: An iterator like instance of Key :rtype: ~azure.core.paging.ItemPaged[~azure.appconfiguration.models.Key] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KeyListResult] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Key]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -878,12 +953,12 @@ def get_keys( def prepare_request(next_link=None): if not next_link: - _request = build_get_keys_request( + _request = build_azure_app_configuration_get_keys_request( name=name, after=after, + sync_token=sync_token, accept_datetime=accept_datetime, - sync_token=self._config.sync_token, - api_version=api_version, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -913,15 +988,15 @@ def prepare_request(next_link=None): ), } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" + return _request def extract_data(pipeline_response): - deserialized = self._deserialize("KeyListResult", pipeline_response) - list_of_elem = deserialized.items + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.Key], deserialized["items"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) + return deserialized.get("@nextLink") or None, iter(list_of_elem) def get_next(next_link=None): _request = prepare_request(next_link) @@ -934,7 +1009,7 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -942,30 +1017,36 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def check_keys( # pylint: disable=inconsistent-return-statements + def check_keys( self, + *, name: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, **kwargs: Any - ) -> None: + ) -> bool: """Requests the headers and status of the given resource. Requests the headers and status of the given resource. - :param name: A filter for the name of the returned keys. Default value is None. - :type name: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :return: None or the result of cls(response) - :rtype: None + :keyword name: A filter for the name of the returned keys. Default value is None. + :paramtype name: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -974,17 +1055,16 @@ def check_keys( # pylint: disable=inconsistent-return-statements error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_check_keys_request( + _request = build_azure_app_configuration_check_keys_request( name=name, + sync_token=sync_token, after=after, accept_datetime=accept_datetime, - sync_token=self._config.sync_token, - api_version=api_version, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1002,92 +1082,104 @@ def check_keys( # pylint: disable=inconsistent-return-statements if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) if cls: return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace def get_key_values( self, + *, key: Optional[str] = None, label: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, snapshot: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, tags: Optional[List[str]] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> Iterable["_models.KeyValue"]: """Gets a list of key-values. Gets a list of key-values. - :param key: A filter used to match keys. Syntax reference: + :keyword key: A filter used to match keys. Syntax reference: https://aka.ms/azconfig/docs/keyvaluefiltering. Default value is None. - :type key: str - :param label: A filter used to match labels. Syntax reference: + :paramtype key: str + :keyword label: A filter used to match labels. Syntax reference: https://aka.ms/azconfig/docs/keyvaluefiltering. Default value is None. - :type label: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param select: Used to select what fields are present in the returned resource(s). Default + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] - :param snapshot: A filter used get key-values for a snapshot. The value should be the name of + :paramtype select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] + :keyword snapshot: A filter used get key-values for a snapshot. The value should be the name of the snapshot. Not valid when used with 'key' and 'label' filters. Default value is None. - :type snapshot: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param tags: A filter used to query by tags. Syntax reference: + :paramtype snapshot: str + :keyword tags: A filter used to query by tags. Syntax reference: https://aka.ms/azconfig/docs/keyvaluefiltering. Default value is None. - :type tags: list[str] - :return: An iterator like instance of either KeyValue or the result of cls(response) + :paramtype tags: list[str] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: An iterator like instance of KeyValue :rtype: ~azure.core.paging.ItemPaged[~azure.appconfiguration.models.KeyValue] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KeyValueListResult] = kwargs.pop("cls", None) + cls: ClsType[List[_models.KeyValue]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: - _request = build_get_key_values_request( + _request = build_azure_app_configuration_get_key_values_request( key=key, label=label, + sync_token=sync_token, after=after, accept_datetime=accept_datetime, select=select, snapshot=snapshot, - if_match=if_match, - if_none_match=if_none_match, tags=tags, - sync_token=self._config.sync_token, - api_version=api_version, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1117,15 +1209,15 @@ def prepare_request(next_link=None): ), } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" + return _request def extract_data(pipeline_response): - deserialized = self._deserialize("KeyValueListResult", pipeline_response) - list_of_elem = deserialized.items + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.KeyValue], deserialized["items"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) + return deserialized.get("@nextLink") or None, iter(list_of_elem) def get_next(next_link=None): _request = prepare_request(next_link) @@ -1138,7 +1230,7 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -1146,80 +1238,90 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def check_key_values( # pylint: disable=inconsistent-return-statements + def check_key_values( self, + *, key: Optional[str] = None, label: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, snapshot: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, tags: Optional[List[str]] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> None: + ) -> bool: """Requests the headers and status of the given resource. Requests the headers and status of the given resource. - :param key: A filter used to match keys. Syntax reference: + :keyword key: A filter used to match keys. Syntax reference: https://aka.ms/azconfig/docs/keyvaluefiltering. Default value is None. - :type key: str - :param label: A filter used to match labels. Syntax reference: + :paramtype key: str + :keyword label: A filter used to match labels. Syntax reference: https://aka.ms/azconfig/docs/keyvaluefiltering. Default value is None. - :type label: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param select: Used to select what fields are present in the returned resource(s). Default + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] - :param snapshot: A filter used get key-values for a snapshot. Not valid when used with 'key' + :paramtype select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] + :keyword snapshot: A filter used get key-values for a snapshot. Not valid when used with 'key' and 'label' filters. Default value is None. - :type snapshot: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param tags: A filter used to query by tags. Syntax reference: + :paramtype snapshot: str + :keyword tags: A filter used to query by tags. Syntax reference: https://aka.ms/azconfig/docs/keyvaluefiltering. Default value is None. - :type tags: list[str] - :return: None or the result of cls(response) - :rtype: None + :paramtype tags: list[str] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_check_key_values_request( + _request = build_azure_app_configuration_check_key_values_request( key=key, label=label, + sync_token=sync_token, after=after, accept_datetime=accept_datetime, select=select, snapshot=snapshot, - if_match=if_match, - if_none_match=if_none_match, tags=tags, - sync_token=self._config.sync_token, - api_version=api_version, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1237,7 +1339,8 @@ def check_key_values( # pylint: disable=inconsistent-return-statements if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) @@ -1245,65 +1348,76 @@ def check_key_values( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace def get_key_value( self, key: str, + *, label: Optional[str] = None, - accept_datetime: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, + sync_token: Optional[str] = None, + accept_datetime: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.KeyValue: """Gets a single key-value. Gets a single key-value. - :param key: The key of the key-value to retrieve. Required. + :param key: The key of the key-value. Required. :type key: str - :param label: The label of the key-value to retrieve. Default value is None. - :type label: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param select: Used to select what fields are present in the returned resource(s). Default + :keyword label: The label of the key-value to retrieve. Default value is None. + :paramtype label: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] - :return: KeyValue or the result of cls(response) + :paramtype select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KeyValue. The KeyValue is compatible with MutableMapping :rtype: ~azure.appconfiguration.models.KeyValue :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.KeyValue] = kwargs.pop("cls", None) - _request = build_get_key_value_request( + _request = build_azure_app_configuration_get_key_value_request( key=key, label=label, - accept_datetime=accept_datetime, - if_match=if_match, - if_none_match=if_none_match, select=select, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + accept_datetime=accept_datetime, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1312,7 +1426,7 @@ def get_key_value( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1320,15 +1434,27 @@ def get_key_value( response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("KeyValue", pipeline_response.http_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.KeyValue, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -1336,88 +1462,55 @@ def get_key_value( return deserialized # type: ignore @overload - def put_key_value( + def _put_key_value( self, key: str, - label: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, entity: Optional[_models.KeyValue] = None, *, - content_type: str = "application/json", + content_type: str, + label: Optional[str] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models.KeyValue: - """Creates a key-value. - - Creates a key-value. - - :param key: The key of the key-value to create. Required. - :type key: str - :param label: The label of the key-value to create. Default value is None. - :type label: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param entity: The key-value to create. Default value is None. - :type entity: ~azure.appconfiguration.models.KeyValue - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KeyValue or the result of cls(response) - :rtype: ~azure.appconfiguration.models.KeyValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models.KeyValue: ... @overload - def put_key_value( + def _put_key_value( self, key: str, + entity: Optional[JSON] = None, + *, + content_type: str, label: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models.KeyValue: ... + @overload + def _put_key_value( + self, + key: str, entity: Optional[IO[bytes]] = None, *, - content_type: str = "application/json", + content_type: str, + label: Optional[str] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models.KeyValue: - """Creates a key-value. - - Creates a key-value. - - :param key: The key of the key-value to create. Required. - :type key: str - :param label: The label of the key-value to create. Default value is None. - :type label: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param entity: The key-value to create. Default value is None. - :type entity: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Known values are: 'application/*+json', 'application/json', 'application/json-patch+json', - 'application/vnd.microsoft.appconfig.kv+json', - 'application/vnd.microsoft.appconfig.kvset+json', 'text/json'. Default value is - "application/json". - :paramtype content_type: str - :return: KeyValue or the result of cls(response) - :rtype: ~azure.appconfiguration.models.KeyValue - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models.KeyValue: ... @distributed_trace - def put_key_value( + def _put_key_value( self, key: str, + entity: Optional[Union[_models.KeyValue, JSON, IO[bytes]]] = None, + *, label: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - entity: Optional[Union[_models.KeyValue, IO[bytes]]] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.KeyValue: """Creates a key-value. @@ -1426,56 +1519,61 @@ def put_key_value( :param key: The key of the key-value to create. Required. :type key: str - :param label: The label of the key-value to create. Default value is None. - :type label: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param entity: The key-value to create. Is either a KeyValue type or a IO[bytes] type. Default - value is None. - :type entity: ~azure.appconfiguration.models.KeyValue or IO[bytes] - :return: KeyValue or the result of cls(response) + :param entity: The key-value to create. Is one of the following types: KeyValue, JSON, + IO[bytes] Default value is None. + :type entity: ~azure.appconfiguration.models.KeyValue or JSON or IO[bytes] + :keyword label: The label of the key-value to create. Default value is None. + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KeyValue. The KeyValue is compatible with MutableMapping :rtype: ~azure.appconfiguration.models.KeyValue :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.KeyValue] = kwargs.pop("cls", None) content_type = content_type or "application/json" - _json = None _content = None if isinstance(entity, (IOBase, bytes)): _content = entity else: if entity is not None: - _json = self._serialize.body(entity, "KeyValue") + _content = json.dumps(entity, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: - _json = None + _content = None - _request = build_put_key_value_request( + _request = build_azure_app_configuration_put_key_value_request( key=key, label=label, - if_match=if_match, - if_none_match=if_none_match, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + etag=etag, + match_condition=match_condition, content_type=content_type, - json=_json, + api_version=self._config.api_version, content=_content, headers=_headers, params=_params, @@ -1485,7 +1583,7 @@ def put_key_value( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1493,15 +1591,24 @@ def put_key_value( response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("KeyValue", pipeline_response.http_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.KeyValue, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -1510,7 +1617,14 @@ def put_key_value( @distributed_trace def delete_key_value( - self, key: str, label: Optional[str] = None, if_match: Optional[str] = None, **kwargs: Any + self, + key: str, + *, + label: Optional[str] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any ) -> Optional[_models.KeyValue]: """Deletes a key-value. @@ -1518,35 +1632,46 @@ def delete_key_value( :param key: The key of the key-value to delete. Required. :type key: str - :param label: The label of the key-value to delete. Default value is None. - :type label: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :return: KeyValue or None or the result of cls(response) + :keyword label: The label of the key-value to delete. Default value is None. + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KeyValue or None. The KeyValue is compatible with MutableMapping :rtype: ~azure.appconfiguration.models.KeyValue or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[Optional[_models.KeyValue]] = kwargs.pop("cls", None) - _request = build_delete_key_value_request( + _request = build_azure_app_configuration_delete_key_value_request( key=key, label=label, - if_match=if_match, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1555,7 +1680,7 @@ def delete_key_value( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1563,8 +1688,13 @@ def delete_key_value( response = pipeline_response.http_response if response.status_code not in [200, 204]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) deserialized = None @@ -1572,8 +1702,12 @@ def delete_key_value( if response.status_code == 200: response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("KeyValue", pipeline_response.http_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.KeyValue, response.json()) if response.status_code == 204: response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) @@ -1584,63 +1718,73 @@ def delete_key_value( return deserialized # type: ignore @distributed_trace - def check_key_value( # pylint: disable=inconsistent-return-statements + def check_key_value( self, key: str, + *, label: Optional[str] = None, + sync_token: Optional[str] = None, accept_datetime: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> None: + ) -> bool: """Requests the headers and status of the given resource. Requests the headers and status of the given resource. :param key: The key of the key-value to retrieve. Required. :type key: str - :param label: The label of the key-value to retrieve. Default value is None. - :type label: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param select: Used to select what fields are present in the returned resource(s). Default + :keyword label: The label of the key-value to retrieve. Default value is None. + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] - :return: None or the result of cls(response) - :rtype: None + :paramtype select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_check_key_value_request( + _request = build_azure_app_configuration_check_key_value_request( key=key, label=label, + sync_token=sync_token, accept_datetime=accept_datetime, - if_match=if_match, - if_none_match=if_none_match, select=select, - sync_token=self._config.sync_token, - api_version=api_version, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1658,7 +1802,8 @@ def check_key_value( # pylint: disable=inconsistent-return-statements if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) @@ -1666,42 +1811,47 @@ def check_key_value( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace def get_snapshots( self, + *, name: Optional[str] = None, after: Optional[str] = None, select: Optional[List[Union[str, _models.SnapshotFields]]] = None, status: Optional[List[Union[str, _models.SnapshotStatus]]] = None, + sync_token: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.Snapshot"]: """Gets a list of key-value snapshots. Gets a list of key-value snapshots. - :param name: A filter for the name of the returned snapshots. Default value is None. - :type name: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param select: Used to select what fields are present in the returned resource(s). Default + :keyword name: A filter for the name of the returned snapshots. Default value is None. + :paramtype name: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.SnapshotFields] - :param status: Used to filter returned snapshots by their status property. Default value is + :paramtype select: list[str or ~azure.appconfiguration.models.SnapshotFields] + :keyword status: Used to filter returned snapshots by their status property. Default value is + None. + :paramtype status: list[str or ~azure.appconfiguration.models.SnapshotStatus] + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is None. - :type status: list[str or ~azure.appconfiguration.models.SnapshotStatus] - :return: An iterator like instance of either Snapshot or the result of cls(response) + :paramtype sync_token: str + :return: An iterator like instance of Snapshot :rtype: ~azure.core.paging.ItemPaged[~azure.appconfiguration.models.Snapshot] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SnapshotListResult] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Snapshot]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1712,13 +1862,13 @@ def get_snapshots( def prepare_request(next_link=None): if not next_link: - _request = build_get_snapshots_request( + _request = build_azure_app_configuration_get_snapshots_request( name=name, after=after, select=select, status=status, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1748,15 +1898,15 @@ def prepare_request(next_link=None): ), } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" + return _request def extract_data(pipeline_response): - deserialized = self._deserialize("SnapshotListResult", pipeline_response) - list_of_elem = deserialized.items + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.Snapshot], deserialized["items"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) + return deserialized.get("@nextLink") or None, iter(list_of_elem) def get_next(next_link=None): _request = prepare_request(next_link) @@ -1769,7 +1919,7 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -1777,21 +1927,22 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def check_snapshots( # pylint: disable=inconsistent-return-statements - self, after: Optional[str] = None, **kwargs: Any - ) -> None: + def check_snapshots(self, *, sync_token: Optional[str] = None, after: Optional[str] = None, **kwargs: Any) -> bool: """Requests the headers and status of the given resource. Requests the headers and status of the given resource. - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :return: None or the result of cls(response) - :rtype: None + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1800,15 +1951,14 @@ def check_snapshots( # pylint: disable=inconsistent-return-statements error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_check_snapshots_request( + _request = build_azure_app_configuration_check_snapshots_request( + sync_token=sync_token, after=after, - sync_token=self._config.sync_token, - api_version=api_version, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1826,63 +1976,74 @@ def check_snapshots( # pylint: disable=inconsistent-return-statements if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) if cls: return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace def get_snapshot( self, name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, + *, select: Optional[List[Union[str, _models.SnapshotFields]]] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.Snapshot: """Gets a single key-value snapshot. Gets a single key-value snapshot. - :param name: The name of the key-value snapshot to retrieve. Required. + :param name: The name of the snapshot. Required. :type name: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param select: Used to select what fields are present in the returned resource(s). Default + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.SnapshotFields] - :return: Snapshot or the result of cls(response) + :paramtype select: list[str or ~azure.appconfiguration.models.SnapshotFields] + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: Snapshot. The Snapshot is compatible with MutableMapping :rtype: ~azure.appconfiguration.models.Snapshot :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Snapshot] = kwargs.pop("cls", None) - _request = build_get_snapshot_request( + _request = build_azure_app_configuration_get_snapshot_request( name=name, - if_match=if_match, - if_none_match=if_none_match, select=select, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1891,7 +2052,7 @@ def get_snapshot( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1899,26 +2060,106 @@ def get_snapshot( response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) response_headers["Link"] = self._deserialize("str", response.headers.get("Link")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("Snapshot", pipeline_response.http_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.Snapshot, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore + @distributed_trace + def get_operation_details(self, *, snapshot: str, **kwargs: Any) -> _models.OperationDetails: + """Gets the state of a long running operation. + + Gets the state of a long running operation. + + :keyword snapshot: Snapshot identifier for the long running operation. Required. + :paramtype snapshot: str + :return: OperationDetails. The OperationDetails is compatible with MutableMapping + :rtype: ~azure.appconfiguration.models.OperationDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) + + _request = build_azure_app_configuration_get_operation_details_request( + snapshot=snapshot, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.OperationDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + def _create_snapshot_initial( - self, name: str, entity: Union[_models.Snapshot, IO[bytes]], **kwargs: Any + self, + name: str, + entity: Union[_models.Snapshot, JSON, IO[bytes]], + *, + sync_token: Optional[str] = None, + **kwargs: Any ) -> Iterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1927,26 +2168,23 @@ def _create_snapshot_initial( error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" - _json = None _content = None if isinstance(entity, (IOBase, bytes)): _content = entity else: - _json = self._serialize.body(entity, "Snapshot") + _content = json.dumps(entity, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_create_snapshot_request( + _request = build_azure_app_configuration_create_snapshot_request( name=name, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, content_type=content_type, - json=_json, + api_version=self._config.api_version, content=_content, headers=_headers, params=_params, @@ -1956,7 +2194,6 @@ def _create_snapshot_initial( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs @@ -1970,7 +2207,7 @@ def _create_snapshot_initial( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1978,8 +2215,9 @@ def _create_snapshot_initial( response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) response_headers["Link"] = self._deserialize("str", response.headers.get("Link")) response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -1988,7 +2226,7 @@ def _create_snapshot_initial( @overload def begin_create_snapshot( - self, name: str, entity: _models.Snapshot, *, content_type: str = "application/json", **kwargs: Any + self, name: str, entity: _models.Snapshot, *, content_type: str, sync_token: Optional[str] = None, **kwargs: Any ) -> LROPoller[_models.Snapshot]: """Creates a key-value snapshot. @@ -1999,16 +2237,44 @@ def begin_create_snapshot( :param entity: The key-value snapshot to create. Required. :type entity: ~azure.appconfiguration.models.Snapshot :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". + Required. :paramtype content_type: str - :return: An instance of LROPoller that returns either Snapshot or the result of cls(response) + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :return: An instance of LROPoller that returns Snapshot. The Snapshot is compatible with + MutableMapping :rtype: ~azure.core.polling.LROPoller[~azure.appconfiguration.models.Snapshot] :raises ~azure.core.exceptions.HttpResponseError: """ @overload def begin_create_snapshot( - self, name: str, entity: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + self, name: str, entity: JSON, *, content_type: str, sync_token: Optional[str] = None, **kwargs: Any + ) -> LROPoller[_models.Snapshot]: + """Creates a key-value snapshot. + + Creates a key-value snapshot. + + :param name: The name of the key-value snapshot to create. Required. + :type name: str + :param entity: The key-value snapshot to create. Required. + :type entity: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Required. + :paramtype content_type: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :return: An instance of LROPoller that returns Snapshot. The Snapshot is compatible with + MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.appconfiguration.models.Snapshot] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_snapshot( + self, name: str, entity: IO[bytes], *, content_type: str, sync_token: Optional[str] = None, **kwargs: Any ) -> LROPoller[_models.Snapshot]: """Creates a key-value snapshot. @@ -2019,17 +2285,26 @@ def begin_create_snapshot( :param entity: The key-value snapshot to create. Required. :type entity: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Known values are: 'application/json', 'application/vnd.microsoft.appconfig.snapshot+json'. - Default value is "application/json". + Known values are: 'application/vnd.microsoft.appconfig.snapshot+json', 'application/json'. + Required. :paramtype content_type: str - :return: An instance of LROPoller that returns either Snapshot or the result of cls(response) + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :return: An instance of LROPoller that returns Snapshot. The Snapshot is compatible with + MutableMapping :rtype: ~azure.core.polling.LROPoller[~azure.appconfiguration.models.Snapshot] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def begin_create_snapshot( - self, name: str, entity: Union[_models.Snapshot, IO[bytes]], **kwargs: Any + self, + name: str, + entity: Union[_models.Snapshot, JSON, IO[bytes]], + *, + sync_token: Optional[str] = None, + **kwargs: Any ) -> LROPoller[_models.Snapshot]: """Creates a key-value snapshot. @@ -2037,17 +2312,20 @@ def begin_create_snapshot( :param name: The name of the key-value snapshot to create. Required. :type name: str - :param entity: The key-value snapshot to create. Is either a Snapshot type or a IO[bytes] type. - Required. - :type entity: ~azure.appconfiguration.models.Snapshot or IO[bytes] - :return: An instance of LROPoller that returns either Snapshot or the result of cls(response) + :param entity: The key-value snapshot to create. Is one of the following types: Snapshot, JSON, + IO[bytes] Required. + :type entity: ~azure.appconfiguration.models.Snapshot or JSON or IO[bytes] + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :return: An instance of LROPoller that returns Snapshot. The Snapshot is compatible with + MutableMapping :rtype: ~azure.core.polling.LROPoller[~azure.appconfiguration.models.Snapshot] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Snapshot] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -2057,7 +2335,7 @@ def begin_create_snapshot( raw_result = self._create_snapshot_initial( name=name, entity=entity, - api_version=api_version, + sync_token=sync_token, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, @@ -2076,8 +2354,9 @@ def get_long_running_output(pipeline_response): response_headers["Operation-Location"] = self._deserialize( "str", response.headers.get("Operation-Location") ) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("Snapshot", pipeline_response.http_response) + deserialized = _deserialize(_models.Snapshot, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized @@ -2106,79 +2385,51 @@ def get_long_running_output(pipeline_response): ) @overload - def update_snapshot( + def _update_snapshot( self, name: str, - entity: _models.SnapshotUpdateParameters, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, + entity: _models._models.SnapshotUpdateParameters, *, - content_type: str = "application/json", + content_type: str, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models.Snapshot: - """Updates the state of a key-value snapshot. - - Updates the state of a key-value snapshot. - - :param name: The name of the key-value snapshot to update. Required. - :type name: str - :param entity: The parameters used to update the snapshot. Required. - :type entity: ~azure.appconfiguration.models.SnapshotUpdateParameters - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Snapshot or the result of cls(response) - :rtype: ~azure.appconfiguration.models.Snapshot - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models.Snapshot: ... + @overload + def _update_snapshot( + self, + name: str, + entity: JSON, + *, + content_type: str, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models.Snapshot: ... @overload - def update_snapshot( + def _update_snapshot( self, name: str, entity: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, *, - content_type: str = "application/json", + content_type: str, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models.Snapshot: - """Updates the state of a key-value snapshot. - - Updates the state of a key-value snapshot. - - :param name: The name of the key-value snapshot to update. Required. - :type name: str - :param entity: The parameters used to update the snapshot. Required. - :type entity: IO[bytes] - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Known values are: 'application/json', 'application/merge-patch+json'. Default value is - "application/json". - :paramtype content_type: str - :return: Snapshot or the result of cls(response) - :rtype: ~azure.appconfiguration.models.Snapshot - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models.Snapshot: ... @distributed_trace - def update_snapshot( + def _update_snapshot( self, name: str, - entity: Union[_models.SnapshotUpdateParameters, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, + entity: Union[_models._models.SnapshotUpdateParameters, JSON, IO[bytes]], + *, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.Snapshot: """Updates the state of a key-value snapshot. @@ -2187,50 +2438,56 @@ def update_snapshot( :param name: The name of the key-value snapshot to update. Required. :type name: str - :param entity: The parameters used to update the snapshot. Is either a SnapshotUpdateParameters - type or a IO[bytes] type. Required. - :type entity: ~azure.appconfiguration.models.SnapshotUpdateParameters or IO[bytes] - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :return: Snapshot or the result of cls(response) + :param entity: The parameters used to update the snapshot. Is one of the following types: + SnapshotUpdateParameters, JSON, IO[bytes] Required. + :type entity: ~azure.appconfiguration.models._models.SnapshotUpdateParameters or JSON or + IO[bytes] + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: Snapshot. The Snapshot is compatible with MutableMapping :rtype: ~azure.appconfiguration.models.Snapshot :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Snapshot] = kwargs.pop("cls", None) content_type = content_type or "application/json" - _json = None _content = None if isinstance(entity, (IOBase, bytes)): _content = entity else: - _json = self._serialize.body(entity, "SnapshotUpdateParameters") + _content = json.dumps(entity, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_update_snapshot_request( + _request = build_azure_app_configuration_update_snapshot_request( name=name, - if_match=if_match, - if_none_match=if_none_match, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + etag=etag, + match_condition=match_condition, content_type=content_type, - json=_json, + api_version=self._config.api_version, content=_content, headers=_headers, params=_params, @@ -2240,7 +2497,7 @@ def update_snapshot( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2248,16 +2505,25 @@ def update_snapshot( response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) response_headers["Link"] = self._deserialize("str", response.headers.get("Link")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("Snapshot", pipeline_response.http_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.Snapshot, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -2265,45 +2531,58 @@ def update_snapshot( return deserialized # type: ignore @distributed_trace - def check_snapshot( # pylint: disable=inconsistent-return-statements - self, name: str, if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any - ) -> None: + def check_snapshot( + self, + name: str, + *, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> bool: """Requests the headers and status of the given resource. Requests the headers and status of the given resource. :param name: The name of the key-value snapshot to check. Required. :type name: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :return: None or the result of cls(response) - :rtype: None + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_check_snapshot_request( + _request = build_azure_app_configuration_check_snapshot_request( name=name, - if_match=if_match, - if_none_match=if_none_match, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -2321,7 +2600,8 @@ def check_snapshot( # pylint: disable=inconsistent-return-statements if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) @@ -2330,11 +2610,14 @@ def check_snapshot( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace def get_labels( self, + *, name: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.LabelFields]]] = None, @@ -2344,28 +2627,31 @@ def get_labels( Gets a list of labels. - :param name: A filter for the name of the returned labels. Default value is None. - :type name: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param select: Used to select what fields are present in the returned resource(s). Default + :keyword name: A filter for the name of the returned labels. Default value is None. + :paramtype name: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.LabelFields] - :return: An iterator like instance of either Label or the result of cls(response) + :paramtype select: list[str or ~azure.appconfiguration.models.LabelFields] + :return: An iterator like instance of Label :rtype: ~azure.core.paging.ItemPaged[~azure.appconfiguration.models.Label] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.LabelListResult] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Label]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2376,13 +2662,13 @@ def get_labels( def prepare_request(next_link=None): if not next_link: - _request = build_get_labels_request( + _request = build_azure_app_configuration_get_labels_request( name=name, + sync_token=sync_token, after=after, accept_datetime=accept_datetime, select=select, - sync_token=self._config.sync_token, - api_version=api_version, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -2412,15 +2698,15 @@ def prepare_request(next_link=None): ), } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" + return _request def extract_data(pipeline_response): - deserialized = self._deserialize("LabelListResult", pipeline_response) - list_of_elem = deserialized.items + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.Label], deserialized["items"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) + return deserialized.get("@nextLink") or None, iter(list_of_elem) def get_next(next_link=None): _request = prepare_request(next_link) @@ -2433,7 +2719,7 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -2441,34 +2727,40 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def check_labels( # pylint: disable=inconsistent-return-statements + def check_labels( self, + *, name: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.LabelFields]]] = None, **kwargs: Any - ) -> None: + ) -> bool: """Requests the headers and status of the given resource. Requests the headers and status of the given resource. - :param name: A filter for the name of the returned labels. Default value is None. - :type name: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param select: Used to select what fields are present in the returned resource(s). Default + :keyword name: A filter for the name of the returned labels. Default value is None. + :paramtype name: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.LabelFields] - :return: None or the result of cls(response) - :rtype: None + :paramtype select: list[str or ~azure.appconfiguration.models.LabelFields] + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2477,18 +2769,17 @@ def check_labels( # pylint: disable=inconsistent-return-statements error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_check_labels_request( + _request = build_azure_app_configuration_check_labels_request( name=name, + sync_token=sync_token, after=after, accept_datetime=accept_datetime, select=select, - sync_token=self._config.sync_token, - api_version=api_version, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -2506,21 +2797,25 @@ def check_labels( # pylint: disable=inconsistent-return-statements if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) if cls: return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace def put_lock( self, key: str, + *, label: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.KeyValue: """Locks a key-value. @@ -2529,39 +2824,46 @@ def put_lock( :param key: The key of the key-value to lock. Required. :type key: str - :param label: The label, if any, of the key-value to lock. Default value is None. - :type label: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :return: KeyValue or the result of cls(response) + :keyword label: The label, if any, of the key-value to lock. Default value is None. + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KeyValue. The KeyValue is compatible with MutableMapping :rtype: ~azure.appconfiguration.models.KeyValue :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.KeyValue] = kwargs.pop("cls", None) - _request = build_put_lock_request( + _request = build_azure_app_configuration_put_lock_request( key=key, label=label, - if_match=if_match, - if_none_match=if_none_match, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -2570,7 +2872,7 @@ def put_lock( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2578,15 +2880,24 @@ def put_lock( response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("KeyValue", pipeline_response.http_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.KeyValue, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -2597,9 +2908,11 @@ def put_lock( def delete_lock( self, key: str, + *, label: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.KeyValue: """Unlocks a key-value. @@ -2608,39 +2921,46 @@ def delete_lock( :param key: The key of the key-value to unlock. Required. :type key: str - :param label: The label, if any, of the key-value to unlock. Default value is None. - :type label: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :return: KeyValue or the result of cls(response) + :keyword label: The label, if any, of the key-value to unlock. Default value is None. + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KeyValue. The KeyValue is compatible with MutableMapping :rtype: ~azure.appconfiguration.models.KeyValue :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.KeyValue] = kwargs.pop("cls", None) - _request = build_delete_lock_request( + _request = build_azure_app_configuration_delete_lock_request( key=key, label=label, - if_match=if_match, - if_none_match=if_none_match, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -2649,7 +2969,7 @@ def delete_lock( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2657,15 +2977,24 @@ def delete_lock( response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("KeyValue", pipeline_response.http_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.KeyValue, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -2675,8 +3004,10 @@ def delete_lock( @distributed_trace def get_revisions( self, + *, key: Optional[str] = None, label: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, @@ -2687,35 +3018,38 @@ def get_revisions( Gets a list of key-value revisions. - :param key: A filter used to match keys. Syntax reference: + :keyword key: A filter used to match keys. Syntax reference: https://aka.ms/azconfig/docs/restapirevisions. Default value is None. - :type key: str - :param label: A filter used to match labels. Syntax reference: + :paramtype key: str + :keyword label: A filter used to match labels. Syntax reference: https://aka.ms/azconfig/docs/restapirevisions. Default value is None. - :type label: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param select: Used to select what fields are present in the returned resource(s). Default + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] - :param tags: A filter used to query by tags. Syntax reference: + :paramtype select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] + :keyword tags: A filter used to query by tags. Syntax reference: https://aka.ms/azconfig/docs/restapirevisions. Default value is None. - :type tags: list[str] - :return: An iterator like instance of either KeyValue or the result of cls(response) + :paramtype tags: list[str] + :return: An iterator like instance of KeyValue :rtype: ~azure.core.paging.ItemPaged[~azure.appconfiguration.models.KeyValue] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KeyValueListResult] = kwargs.pop("cls", None) + cls: ClsType[List[_models.KeyValue]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2726,15 +3060,15 @@ def get_revisions( def prepare_request(next_link=None): if not next_link: - _request = build_get_revisions_request( + _request = build_azure_app_configuration_get_revisions_request( key=key, label=label, + sync_token=sync_token, after=after, accept_datetime=accept_datetime, select=select, tags=tags, - sync_token=self._config.sync_token, - api_version=api_version, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -2764,15 +3098,15 @@ def prepare_request(next_link=None): ), } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" + return _request def extract_data(pipeline_response): - deserialized = self._deserialize("KeyValueListResult", pipeline_response) - list_of_elem = deserialized.items + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.KeyValue], deserialized["items"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) + return deserialized.get("@nextLink") or None, iter(list_of_elem) def get_next(next_link=None): _request = prepare_request(next_link) @@ -2785,7 +3119,7 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -2793,43 +3127,49 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def check_revisions( # pylint: disable=inconsistent-return-statements + def check_revisions( self, + *, key: Optional[str] = None, label: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, tags: Optional[List[str]] = None, **kwargs: Any - ) -> None: + ) -> bool: """Requests the headers and status of the given resource. Requests the headers and status of the given resource. - :param key: A filter used to match keys. Syntax reference: + :keyword key: A filter used to match keys. Syntax reference: https://aka.ms/azconfig/docs/restapirevisions. Default value is None. - :type key: str - :param label: A filter used to match labels. Syntax reference: + :paramtype key: str + :keyword label: A filter used to match labels. Syntax reference: https://aka.ms/azconfig/docs/restapirevisions. Default value is None. - :type label: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param select: Used to select what fields are present in the returned resource(s). Default + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] - :param tags: A filter used to query by tags. Syntax reference: + :paramtype select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] + :keyword tags: A filter used to query by tags. Syntax reference: https://aka.ms/azconfig/docs/restapirevisions. Default value is None. - :type tags: list[str] - :return: None or the result of cls(response) - :rtype: None + :paramtype tags: list[str] + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2838,20 +3178,19 @@ def check_revisions( # pylint: disable=inconsistent-return-statements error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_check_revisions_request( + _request = build_azure_app_configuration_check_revisions_request( key=key, label=label, + sync_token=sync_token, after=after, accept_datetime=accept_datetime, select=select, tags=tags, - sync_token=self._config.sync_token, - api_version=api_version, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -2869,7 +3208,8 @@ def check_revisions( # pylint: disable=inconsistent-return-statements if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) @@ -2877,59 +3217,4 @@ def check_revisions( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def get_operation_details(self, snapshot: str, **kwargs: Any) -> _models.OperationDetails: - """Gets the state of a long running operation. - - Gets the state of a long running operation. - - :param snapshot: Snapshot identifier for the long running operation. Required. - :type snapshot: str - :return: OperationDetails or the result of cls(response) - :rtype: ~azure.appconfiguration.models.OperationDetails - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) - - _request = build_get_operation_details_request( - snapshot=snapshot, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("OperationDetails", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + return 200 <= response.status_code <= 299 diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/models/_patch.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_operations/_patch.py similarity index 99% rename from sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/models/_patch.py rename to sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_operations/_patch.py index 5755fd181b3f..f7dd32510333 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/models/_patch.py +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_operations/_patch.py @@ -2,8 +2,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ - - """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_patch.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/_serialization.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_serialization.py similarity index 85% rename from sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/_serialization.py rename to sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_serialization.py index 8139854b97bb..ce17d1798ce7 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/_serialization.py +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_serialization.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. @@ -24,7 +25,6 @@ # # -------------------------------------------------------------------------- -# pylint: skip-file # pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode @@ -52,7 +52,6 @@ MutableMapping, Type, List, - Mapping, ) try: @@ -91,6 +90,8 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: :param data: Input, could be bytes or stream (will be decoded with UTF8) or text :type data: str or bytes or IO :param str content_type: The content type. + :return: The deserialized data. + :rtype: object """ if hasattr(data, "read"): # Assume a stream @@ -112,7 +113,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: try: return json.loads(data_as_str) except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) + raise DeserializationError("JSON is invalid: {}".format(err), err) from err elif "xml" in (content_type or []): try: @@ -155,6 +156,11 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], Use bytes and headers to NOT use any requests/aiohttp or whatever specific implementation. Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object """ # Try to use content-type from headers if available content_type = None @@ -184,15 +190,30 @@ class UTC(datetime.tzinfo): """Time Zone info for handling UTC""" def utcoffset(self, dt): - """UTF offset for UTC is 0.""" + """UTF offset for UTC is 0. + + :param datetime.datetime dt: The datetime + :returns: The offset + :rtype: datetime.timedelta + """ return datetime.timedelta(0) def tzname(self, dt): - """Timestamp representation.""" + """Timestamp representation. + + :param datetime.datetime dt: The datetime + :returns: The timestamp representation + :rtype: str + """ return "Z" def dst(self, dt): - """No daylight saving for UTC.""" + """No daylight saving for UTC. + + :param datetime.datetime dt: The datetime + :returns: The daylight saving time + :rtype: datetime.timedelta + """ return datetime.timedelta(hours=1) @@ -206,7 +227,7 @@ class _FixedOffset(datetime.tzinfo): # type: ignore :param datetime.timedelta offset: offset in timedelta format """ - def __init__(self, offset): + def __init__(self, offset) -> None: self.__offset = offset def utcoffset(self, dt): @@ -235,24 +256,26 @@ def __getinitargs__(self): _FLATTEN = re.compile(r"(? None: self.additional_properties: Optional[Dict[str, Any]] = {} - for k in kwargs: + for k in kwargs: # pylint: disable=consider-using-dict-items if k not in self._attribute_map: _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) elif k in self._validation and self._validation[k].get("readonly", False): @@ -300,13 +330,23 @@ def __init__(self, **kwargs: Any) -> None: setattr(self, k, kwargs[k]) def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ return not self.__eq__(other) def __str__(self) -> str: @@ -326,7 +366,11 @@ def is_xml_model(cls) -> bool: @classmethod def _create_xml_node(cls): - """Create XML node.""" + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ try: xml_map = cls._xml_map # type: ignore except AttributeError: @@ -346,7 +390,9 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) def as_dict( self, @@ -380,12 +426,15 @@ def my_key_transformer(key, attr_desc, value): If you want XML serialization, you can pass the kwargs is_xml=True. + :param bool keep_readonly: If you want to serialize the readonly attributes :param function key_transformer: A key transformer function. :returns: A dict JSON compatible object :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) @classmethod def _infer_class_models(cls): @@ -395,7 +444,7 @@ def _infer_class_models(cls): client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} if cls.__name__ not in client_models: raise ValueError("Not Autorest generated code") - except Exception: + except Exception: # pylint: disable=broad-exception-caught # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. client_models = {cls.__name__: cls} return client_models @@ -408,6 +457,7 @@ def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = N :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model :raises: DeserializationError if something went wrong + :rtype: ModelType """ deserializer = Deserializer(cls._infer_class_models()) return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @@ -426,9 +476,11 @@ def from_dict( and last_rest_key_case_insensitive_extractor) :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model :raises: DeserializationError if something went wrong + :rtype: ModelType """ deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = ( # type: ignore @@ -448,21 +500,25 @@ def _flatten_subtype(cls, key, objects): return {} result = dict(cls._subtype_map[key]) for valuetype in cls._subtype_map[key].values(): - result.update(objects[valuetype]._flatten_subtype(key, objects)) + result.update(objects[valuetype]._flatten_subtype(key, objects)) # pylint: disable=protected-access return result @classmethod def _classify(cls, response, objects): """Check the class _subtype_map for any child classes. We want to ignore any inherited _subtype_maps. - Remove the polymorphic key from the initial data. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class """ for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): subtype_value = None if not isinstance(response, ET.Element): rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) else: subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) if subtype_value: @@ -501,11 +557,13 @@ def _decode_attribute_map_key(key): inside the received data. :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str """ return key.replace("\\.", ".") -class Serializer(object): +class Serializer(object): # pylint: disable=too-many-public-methods """Request object model serializer.""" basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -540,7 +598,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, type]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -560,13 +618,16 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None): self.key_transformer = full_restapi_key_transformer self.client_side_validation = True - def _serialize(self, target_obj, data_type=None, **kwargs): + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): """Serialize data into a string according to type. - :param target_obj: The data to be serialized. + :param object target_obj: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str, dict :raises: SerializationError if serialization fails. + :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) @@ -592,12 +653,14 @@ def _serialize(self, target_obj, data_type=None, **kwargs): serialized = {} if is_xml_model_serialization: - serialized = target_obj._create_xml_node() + serialized = target_obj._create_xml_node() # pylint: disable=protected-access try: - attributes = target_obj._attribute_map + attributes = target_obj._attribute_map # pylint: disable=protected-access for attr, attr_desc in attributes.items(): attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): continue if attr_name == "additional_properties" and attr_desc["key"] == "": @@ -633,7 +696,8 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if isinstance(new_attr, list): serialized.extend(new_attr) # type: ignore elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. if "name" not in getattr(orig_attr, "_xml_map", {}): splitted_tag = new_attr.tag.split("}") if len(splitted_tag) == 2: # Namespace @@ -664,17 +728,17 @@ def _serialize(self, target_obj, data_type=None, **kwargs): except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) raise SerializationError(msg) from err - else: - return serialized + return serialized def body(self, data, data_type, **kwargs): """Serialize data intended for a request body. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: dict :raises: SerializationError if serialization fails. :raises: ValueError if data is None + :returns: The serialized request body """ # Just in case this is a dict @@ -703,7 +767,7 @@ def body(self, data, data_type, **kwargs): attribute_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, ] - data = deserializer._deserialize(data_type, data) + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access except DeserializationError as err: raise SerializationError("Unable to build a model: " + str(err)) from err @@ -712,9 +776,11 @@ def body(self, data, data_type, **kwargs): def url(self, name, data, data_type, **kwargs): """Serialize data intended for a URL path. - :param data: The data to be serialized. + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str + :returns: The serialized URL path :raises: TypeError if serialization fails. :raises: ValueError if data is None """ @@ -728,21 +794,20 @@ def url(self, name, data, data_type, **kwargs): output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output def query(self, name, data, data_type, **kwargs): """Serialize data intended for a URL query. - :param data: The data to be serialized. + :param str name: The name of the query parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :keyword bool skip_quote: Whether to skip quote the serialized result. - Defaults to False. :rtype: str, list :raises: TypeError if serialization fails. :raises: ValueError if data is None + :returns: The serialized query parameter """ try: # Treat the list aside, since we don't want to encode the div separator @@ -759,19 +824,20 @@ def query(self, name, data, data_type, **kwargs): output = str(output) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def header(self, name, data, data_type, **kwargs): """Serialize data intended for a request header. - :param data: The data to be serialized. + :param str name: The name of the header. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str :raises: TypeError if serialization fails. :raises: ValueError if data is None + :returns: The serialized header """ try: if data_type in ["[str]"]: @@ -780,21 +846,20 @@ def header(self, name, data, data_type, **kwargs): output = self.serialize_data(data, data_type, **kwargs) if data_type == "bool": output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def serialize_data(self, data, data_type, **kwargs): """Serialize generic data according to supplied data type. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None :raises: AttributeError if required data is None. :raises: ValueError if data is None :raises: SerializationError if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list """ if data is None: raise ValueError("No value for given attribute") @@ -805,7 +870,7 @@ def serialize_data(self, data, data_type, **kwargs): if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) - elif data_type in self.serialize_type: + if data_type in self.serialize_type: return self.serialize_type[data_type](data, **kwargs) # If dependencies is empty, try with current data class @@ -821,11 +886,10 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." raise SerializationError(msg.format(data, data_type)) from err - else: - return self._serialize(data, **kwargs) + return self._serialize(data, **kwargs) @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) if custom_serializer: return custom_serializer @@ -841,23 +905,26 @@ def serialize_basic(cls, data, data_type, **kwargs): - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - is_xml bool : If set, use xml_basic_types_serializers - :param data: Object to be serialized. + :param obj data: Object to be serialized. :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec + return eval(data_type)(data) # nosec # pylint: disable=eval-used @classmethod def serialize_unicode(cls, data): """Special handling for serializing unicode strings in Py2. Encode to UTF-8 if unicode, otherwise handle as a str. - :param data: Object to be serialized. + :param str data: Object to be serialized. :rtype: str + :return: serialized object """ try: # If I received an enum, return its value return data.value @@ -871,8 +938,7 @@ def serialize_unicode(cls, data): return data except NameError: return str(data) - else: - return str(data) + return str(data) def serialize_iter(self, data, iter_type, div=None, **kwargs): """Serialize iterable. @@ -882,15 +948,13 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): serialization_ctxt['type'] should be same as data_type. - is_xml bool : If set, serialize as XML - :param list attr: Object to be serialized. + :param list data: Object to be serialized. :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. :param str div: If set, this str will be used to combine the elements in the iterable into a combined string. Default is 'None'. - :keyword bool do_quote: Whether to quote the serialized result of each iterable element. Defaults to False. :rtype: list, str + :return: serialized iterable """ if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") @@ -945,9 +1009,8 @@ def serialize_dict(self, attr, dict_type, **kwargs): :param dict attr: Object to be serialized. :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. :rtype: dict + :return: serialized dictionary """ serialization_ctxt = kwargs.get("serialization_ctxt", {}) serialized = {} @@ -971,7 +1034,7 @@ def serialize_dict(self, attr, dict_type, **kwargs): return serialized - def serialize_object(self, attr, **kwargs): + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Serialize a generic object. This will be handled as a dictionary. If object passed in is not a basic type (str, int, float, dict, list) it will simply be @@ -979,6 +1042,7 @@ def serialize_object(self, attr, **kwargs): :param dict attr: Object to be serialized. :rtype: dict or str + :return: serialized object """ if attr is None: return None @@ -1003,7 +1067,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_decimal(attr) # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): + if obj_type in self.dependencies.values() or isinstance(attr, Model): return self._serialize(attr) if obj_type == dict: @@ -1034,56 +1098,61 @@ def serialize_enum(attr, enum_obj=None): try: enum_obj(result) # type: ignore return result - except ValueError: + except ValueError as exc: for enum_value in enum_obj: # type: ignore if enum_value.value.lower() == str(attr).lower(): return enum_value.value error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) + raise SerializationError(error.format(attr, enum_obj)) from exc @staticmethod - def serialize_bytearray(attr, **kwargs): + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument """Serialize bytearray into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ return b64encode(attr).decode() @staticmethod - def serialize_base64(attr, **kwargs): + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument """Serialize str into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ encoded = b64encode(attr).decode("ascii") return encoded.strip("=").replace("+", "-").replace("/", "_") @staticmethod - def serialize_decimal(attr, **kwargs): + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument """Serialize Decimal object to float. - :param attr: Object to be serialized. + :param decimal attr: Object to be serialized. :rtype: float + :return: serialized decimal """ return float(attr) @staticmethod - def serialize_long(attr, **kwargs): + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument """Serialize long (Py2) or int (Py3). - :param attr: Object to be serialized. + :param int attr: Object to be serialized. :rtype: int/long + :return: serialized long """ return _long_type(attr) @staticmethod - def serialize_date(attr, **kwargs): + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument """Serialize Date object into ISO-8601 formatted string. :param Date attr: Object to be serialized. :rtype: str + :return: serialized date """ if isinstance(attr, str): attr = isodate.parse_date(attr) @@ -1091,11 +1160,12 @@ def serialize_date(attr, **kwargs): return t @staticmethod - def serialize_time(attr, **kwargs): + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument """Serialize Time object into ISO-8601 formatted string. :param datetime.time attr: Object to be serialized. :rtype: str + :return: serialized time """ if isinstance(attr, str): attr = isodate.parse_time(attr) @@ -1105,30 +1175,32 @@ def serialize_time(attr, **kwargs): return t @staticmethod - def serialize_duration(attr, **kwargs): + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument """Serialize TimeDelta object into ISO-8601 formatted string. :param TimeDelta attr: Object to be serialized. :rtype: str + :return: serialized duration """ if isinstance(attr, str): attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) @staticmethod - def serialize_rfc(attr, **kwargs): + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. :param Datetime attr: Object to be serialized. :rtype: str :raises: TypeError if format invalid. + :return: serialized rfc """ try: if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( Serializer.days[utc.tm_wday], @@ -1141,12 +1213,13 @@ def serialize_rfc(attr, **kwargs): ) @staticmethod - def serialize_iso(attr, **kwargs): + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into ISO-8601 formatted string. :param Datetime attr: Object to be serialized. :rtype: str :raises: SerializationError if format invalid. + :return: serialized iso """ if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -1172,13 +1245,14 @@ def serialize_iso(attr, **kwargs): raise TypeError(msg) from err @staticmethod - def serialize_unix(attr, **kwargs): + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into IntTime format. This is represented as seconds. :param Datetime attr: Object to be serialized. :rtype: int :raises: SerializationError if format invalid + :return: serialied unix """ if isinstance(attr, int): return attr @@ -1186,11 +1260,11 @@ def serialize_unix(attr, **kwargs): if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc -def rest_key_extractor(attr, attr_desc, data): +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument key = attr_desc["key"] working_data = data @@ -1211,7 +1285,9 @@ def rest_key_extractor(attr, attr_desc, data): return working_data.get(key) -def rest_key_case_insensitive_extractor(attr, attr_desc, data): +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): key = attr_desc["key"] working_data = data @@ -1232,17 +1308,29 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): return attribute_key_case_insensitive_extractor(key, None, working_data) -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) return attribute_key_extractor(dict_keys[-1], None, data) -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument """Extract the attribute in "data" based on the last part of the JSON path key. This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) @@ -1279,7 +1367,7 @@ def _extract_name_from_internal_type(internal_type): return xml_name -def xml_key_extractor(attr, attr_desc, data): +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements if isinstance(data, dict): return None @@ -1331,22 +1419,21 @@ def xml_key_extractor(attr, attr_desc, data): if is_iter_type: if is_wrapped: return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list + return [] # not wrapped, assume empty list return None # Assume it's not there, maybe an optional node. # If is_iter_type and not wrapped, return all found children if is_iter_type: if not is_wrapped: return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( # pylint: disable=line-too-long + xml_name ) - return list(children[0]) # Might be empty list and that's ok. + ) + return list(children[0]) # Might be empty list and that's ok. # Here it's not a itertype, we should have found one element only or empty if len(children) > 1: @@ -1363,9 +1450,9 @@ class Deserializer(object): basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes: Optional[Mapping[str, type]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1403,11 +1490,12 @@ def __call__(self, target_obj, response_data, content_type=None): :param str content_type: Swagger "produces" if available. :raises: DeserializationError if deserialization fails. :return: Deserialized object. + :rtype: object """ data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) - def _deserialize(self, target_obj, data): + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements """Call the deserializer on a model. Data needs to be already deserialized as JSON or XML ElementTree @@ -1416,12 +1504,13 @@ def _deserialize(self, target_obj, data): :param object data: Object to deserialize. :raises: DeserializationError if deserialization fails. :return: Deserialized object. + :rtype: object """ # This is already a model, go recursive just in case if hasattr(data, "_attribute_map"): constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] try: - for attr, mapconfig in data._attribute_map.items(): + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access if attr in constants: continue value = getattr(data, attr) @@ -1440,13 +1529,13 @@ def _deserialize(self, target_obj, data): if isinstance(response, str): return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): + if isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) if data is None or data is CoreNull: return data try: - attributes = response._attribute_map # type: ignore + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access d_attrs = {} for attr, attr_desc in attributes.items(): # Check empty string. If it's not empty, someone has a real "additionalProperties"... @@ -1476,9 +1565,8 @@ def _deserialize(self, target_obj, data): except (AttributeError, TypeError, KeyError) as err: msg = "Unable to deserialize to object: " + class_name # type: ignore raise DeserializationError(msg) from err - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) def _build_additional_properties(self, attribute_map, data): if not self.additional_properties_detection: @@ -1505,6 +1593,8 @@ def _classify_target(self, target, data): :param str target: The target object type to deserialize to. :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple """ if target is None: return None, None @@ -1516,7 +1606,7 @@ def _classify_target(self, target, data): return target, target try: - target = target._classify(data, self.dependencies) # type: ignore + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access except AttributeError: pass # Target is not a Model, no classify return target, target.__class__.__name__ # type: ignore @@ -1531,10 +1621,12 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): :param str target_obj: The target object type to deserialize to. :param str/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object """ try: return self(target_obj, data, content_type=content_type) - except: + except: # pylint: disable=bare-except _LOGGER.debug( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) @@ -1552,10 +1644,12 @@ def _unpack_content(raw_data, content_type=None): If raw_data is something else, bypass all logic and return it directly. - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. :raises JSONDecodeError: If JSON is requested and parsing is impossible. :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. """ # Assume this is enough to detect a Pipeline Response without importing it context = getattr(raw_data, "context", {}) @@ -1579,14 +1673,21 @@ def _unpack_content(raw_data, content_type=None): def _instantiate_model(self, response, attrs, additional_properties=None): """Instantiate a response model passing in deserialized args. - :param response: The response model class. - :param d_attrs: The deserialized response attributes. + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. """ if callable(response): subtype = getattr(response, "_subtype_map", {}) try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] + readonly = [ + k for k, v in response._validation.items() if v.get("readonly") # pylint: disable=protected-access + ] + const = [ + k for k, v in response._validation.items() if v.get("constant") # pylint: disable=protected-access + ] kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} response_obj = response(**kwargs) for attr in readonly: @@ -1596,7 +1697,7 @@ def _instantiate_model(self, response, attrs, additional_properties=None): return response_obj except TypeError as err: msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) + raise DeserializationError(msg + str(err)) from err else: try: for attr, value in attrs.items(): @@ -1605,15 +1706,16 @@ def _instantiate_model(self, response, attrs, additional_properties=None): except Exception as exp: msg = "Unable to populate response model. " msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) + raise DeserializationError(msg) from exp - def deserialize_data(self, data, data_type): + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements """Process data for deserialization according to data type. :param str data: The response string to be deserialized. :param str data_type: The type to deserialize to. :raises: DeserializationError if deserialization fails. :return: Deserialized object. + :rtype: object """ if data is None: return data @@ -1627,7 +1729,11 @@ def deserialize_data(self, data, data_type): if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): return data - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: return None data_val = self.deserialize_type[data_type](data) @@ -1647,14 +1753,14 @@ def deserialize_data(self, data, data_type): msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) raise DeserializationError(msg) from err - else: - return self._deserialize(obj_type, data) + return self._deserialize(obj_type, data) def deserialize_iter(self, attr, iter_type): """Deserialize an iterable. :param list attr: Iterable to be deserialized. :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. :rtype: list """ if attr is None: @@ -1671,6 +1777,7 @@ def deserialize_dict(self, attr, dict_type): :param dict/list attr: Dictionary to be deserialized. Also accepts a list of key, value pairs. :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. :rtype: dict """ if isinstance(attr, list): @@ -1681,11 +1788,12 @@ def deserialize_dict(self, attr, dict_type): attr = {el.tag: el.text for el in attr} return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - def deserialize_object(self, attr, **kwargs): + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Deserialize a generic object. This will be handled as a dictionary. :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. :rtype: dict :raises: TypeError if non-builtin datatype encountered. """ @@ -1720,11 +1828,10 @@ def deserialize_object(self, attr, **kwargs): pass return deserialized - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) - def deserialize_basic(self, attr, data_type): + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements """Deserialize basic builtin data type from string. Will attempt to convert to str, int, float and bool. This function will also accept '1', '0', 'true' and 'false' as @@ -1732,6 +1839,7 @@ def deserialize_basic(self, attr, data_type): :param str attr: response string to be deserialized. :param str data_type: deserialization data type. + :return: Deserialized basic type. :rtype: str, int, float or bool :raises: TypeError if string format is not valid. """ @@ -1743,24 +1851,23 @@ def deserialize_basic(self, attr, data_type): if data_type == "str": # None or '', node is empty string. return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, str): + if isinstance(attr, str): if attr.lower() in ["true", "1"]: return True - elif attr.lower() in ["false", "0"]: + if attr.lower() in ["false", "0"]: return False raise TypeError("Invalid boolean value: {}".format(attr)) if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec + return eval(data_type)(attr) # nosec # pylint: disable=eval-used @staticmethod def deserialize_unicode(data): @@ -1768,6 +1875,7 @@ def deserialize_unicode(data): as a string. :param str data: response string to be deserialized. + :return: Deserialized string. :rtype: str or unicode """ # We might be here because we have an enum modeled as string, @@ -1781,8 +1889,7 @@ def deserialize_unicode(data): return data except NameError: return str(data) - else: - return str(data) + return str(data) @staticmethod def deserialize_enum(data, enum_obj): @@ -1794,6 +1901,7 @@ def deserialize_enum(data, enum_obj): :param str data: Response string to be deserialized. If this value is None or invalid it will be returned as-is. :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. :rtype: Enum """ if isinstance(data, enum_obj) or data is None: @@ -1804,9 +1912,9 @@ def deserialize_enum(data, enum_obj): # Workaround. We might consider remove it in the future. try: return list(enum_obj.__members__.values())[data] - except IndexError: + except IndexError as exc: error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) + raise DeserializationError(error.format(data, enum_obj)) from exc try: return enum_obj(str(data)) except ValueError: @@ -1822,6 +1930,7 @@ def deserialize_bytearray(attr): """Deserialize string into bytearray. :param str attr: response string to be deserialized. + :return: Deserialized bytearray :rtype: bytearray :raises: TypeError if string format invalid. """ @@ -1834,6 +1943,7 @@ def deserialize_base64(attr): """Deserialize base64 encoded string into string. :param str attr: response string to be deserialized. + :return: Deserialized base64 string :rtype: bytearray :raises: TypeError if string format invalid. """ @@ -1849,8 +1959,9 @@ def deserialize_decimal(attr): """Deserialize string into Decimal object. :param str attr: response string to be deserialized. - :rtype: Decimal + :return: Deserialized decimal :raises: DeserializationError if string format invalid. + :rtype: decimal """ if isinstance(attr, ET.Element): attr = attr.text @@ -1865,6 +1976,7 @@ def deserialize_long(attr): """Deserialize string into long (Py2) or int (Py3). :param str attr: response string to be deserialized. + :return: Deserialized int :rtype: long or int :raises: ValueError if string format invalid. """ @@ -1877,6 +1989,7 @@ def deserialize_duration(attr): """Deserialize ISO-8601 formatted string into TimeDelta object. :param str attr: response string to be deserialized. + :return: Deserialized duration :rtype: TimeDelta :raises: DeserializationError if string format invalid. """ @@ -1887,14 +2000,14 @@ def deserialize_duration(attr): except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." raise DeserializationError(msg) from err - else: - return duration + return duration @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. :param str attr: response string to be deserialized. + :return: Deserialized date :rtype: Date :raises: DeserializationError if string format invalid. """ @@ -1910,6 +2023,7 @@ def deserialize_time(attr): """Deserialize ISO-8601 formatted string into time object. :param str attr: response string to be deserialized. + :return: Deserialized time :rtype: datetime.time :raises: DeserializationError if string format invalid. """ @@ -1924,6 +2038,7 @@ def deserialize_rfc(attr): """Deserialize RFC-1123 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime :rtype: Datetime :raises: DeserializationError if string format invalid. """ @@ -1939,14 +2054,14 @@ def deserialize_rfc(attr): except ValueError as err: msg = "Cannot deserialize to rfc datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj @staticmethod def deserialize_iso(attr): """Deserialize ISO-8601 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime :rtype: Datetime :raises: DeserializationError if string format invalid. """ @@ -1976,8 +2091,7 @@ def deserialize_iso(attr): except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj @staticmethod def deserialize_unix(attr): @@ -1985,6 +2099,7 @@ def deserialize_unix(attr): This is represented as seconds. :param int attr: Object to be serialized. + :return: Deserialized datetime :rtype: Datetime :raises: DeserializationError if format invalid """ @@ -1996,5 +2111,4 @@ def deserialize_unix(attr): except ValueError as err: msg = "Cannot deserialize to unix datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_sync_token.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_sync_token.py deleted file mode 100644 index c1ab0d8e8541..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_sync_token.py +++ /dev/null @@ -1,116 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from typing import Any, Dict, Optional -from threading import Lock -from azure.core.pipeline import PipelineRequest, PipelineResponse -from azure.core.pipeline.policies import SansIOHTTPPolicy - - -class SyncToken: - """The sync token structure - - :param str token_id: The id of sync token. - :param str value: The value of sync token. - :param int sequence_number: The sequence number of sync token. - """ - - def __init__(self, token_id, value, sequence_number): - self.token_id = token_id - self.value = value - self.sequence_number = sequence_number - - def __str__(self): - return f"{self.token_id}={self.value}" - - @classmethod - def from_sync_token_string(cls, sync_token): - try: - position = sync_token.index(";sn=") - sequence_number = int(sync_token[position + 4 :]) - id_value = sync_token[:position] - position = id_value.index("=") - token_id = id_value[:position] - value = id_value[position + 1 :] - return SyncToken(token_id, value, sequence_number) - except ValueError: - return None - - -class SyncTokenPolicy(SansIOHTTPPolicy): - """A simple policy that enable the given callback with the response. - - :keyword callback raw_response_hook: Callback function. Will be invoked on response. - """ - - def __init__(self, **kwargs: Any) -> None: # pylint: disable=unused-argument - self._sync_token_header = "Sync-Token" - self._sync_tokens: Dict[str, Any] = {} - self._lock = Lock() - - def on_request(self, request: PipelineRequest) -> None: - """This is executed before sending the request to the next policy. - :param request: The PipelineRequest object. - :type request: ~azure.core.pipeline.PipelineRequest - """ - with self._lock: - sync_token_header = ",".join(str(x) for x in self._sync_tokens.values()) - if sync_token_header: - request.http_request.headers.update({self._sync_token_header: sync_token_header}) - - def on_response(self, request: PipelineRequest, response: PipelineResponse) -> None: - """This is executed after the request comes back from the policy. - - :param request: The PipelineRequest object. - :type request: ~azure.core.pipeline.PipelineRequest - :param response: The PipelineResponse object. - :type response: ~azure.core.pipeline.PipelineResponse - """ - sync_token_header = response.http_response.headers.get(self._sync_token_header) - if not sync_token_header: - return - sync_token_strings = sync_token_header.split(",") - if not sync_token_strings: - return - for sync_token_string in sync_token_strings: - sync_token = SyncToken.from_sync_token_string(sync_token_string) - self._update_sync_token(sync_token) - - def add_token(self, full_raw_tokens: str) -> None: - raw_tokens = full_raw_tokens.split(",") - for raw_token in raw_tokens: - sync_token = SyncToken.from_sync_token_string(raw_token) - self._update_sync_token(sync_token) - - def _update_sync_token(self, sync_token: Optional[SyncToken]) -> None: - if not sync_token: - return - with self._lock: - existing_token = self._sync_tokens.get(sync_token.token_id, None) - if not existing_token: - self._sync_tokens[sync_token.token_id] = sync_token - return - if existing_token.sequence_number < sync_token.sequence_number: - self._sync_tokens[sync_token.token_id] = sync_token diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_utils.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_utils.py deleted file mode 100644 index 8a27e219faf9..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_utils.py +++ /dev/null @@ -1,91 +0,0 @@ -# ------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ------------------------------------------------------------------------- - -from datetime import datetime -from typing import Optional, Tuple, Dict, Any -from azure.core import MatchConditions - - -def quote_etag(etag: Optional[str]) -> Optional[str]: - if not etag or etag == "*": - return etag - if etag.startswith('"') and etag.endswith('"'): - return etag - if etag.startswith("'") and etag.endswith("'"): - return etag - return '"' + etag + '"' - - -def prep_if_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: - if match_condition == MatchConditions.IfNotModified: - if_match = quote_etag(etag) if etag else None - return if_match - if match_condition == MatchConditions.IfPresent: - return "*" - return None - - -def prep_if_none_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: - if match_condition == MatchConditions.IfModified: - if_none_match = quote_etag(etag) if etag else None - return if_none_match - if match_condition == MatchConditions.IfMissing: - return "*" - return None - - -def parse_connection_string(connection_string: str) -> Tuple[str, str, str]: - # connection_string looks like Endpoint=https://xxxxx;Id=xxxxx;Secret=xxxx - segments = connection_string.split(";") - if len(segments) != 3: - raise ValueError("Invalid connection string.") - - endpoint = "" - id_ = "" - secret = "" - for segment in segments: - segment = segment.strip() - if segment.startswith("Endpoint"): - endpoint = str(segment[17:]) - elif segment.startswith("Id"): - id_ = str(segment[3:]) - elif segment.startswith("Secret"): - secret = str(segment[7:]) - else: - raise ValueError("Invalid connection string.") - - if not endpoint or not id_ or not secret: - raise ValueError("Invalid connection string.") - - return endpoint, id_, secret - - -def get_current_utc_time() -> str: - return str(datetime.utcnow().strftime("%b, %d %Y %H:%M:%S.%f ")) + "GMT" - - -def get_key_filter(*args: Optional[str], **kwargs: Any) -> Tuple[Optional[str], Dict[str, Any]]: - key_filter = None - if len(args) > 0: - key_filter = args[0] - if "key_filter" in kwargs: - raise TypeError( - "AzureAppConfigurationClient.list_configuration_settings() got multiple values for argument " - "'key_filter'" - ) - return key_filter or kwargs.pop("key_filter", None), kwargs - - -def get_label_filter(*args: Optional[str], **kwargs: Any) -> Tuple[Optional[str], Dict[str, Any]]: - label_filter = None - if len(args) > 1: - label_filter = args[1] - if "label_filter" in kwargs: - raise TypeError( - "AzureAppConfigurationClient.list_configuration_settings() got multiple values for argument " - "'label_filter'" - ) - return label_filter or kwargs.pop("label_filter", None), kwargs diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_vendor.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_vendor.py new file mode 100644 index 000000000000..cd4cb43c3298 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_vendor.py @@ -0,0 +1,57 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import Optional, TYPE_CHECKING + +from azure.core import MatchConditions + +from ._configuration import AzureAppConfigurationClientConfiguration + +if TYPE_CHECKING: + from azure.core import PipelineClient + + from ._serialization import Deserializer, Serializer + + +class AzureAppConfigurationClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "PipelineClient" + _config: AzureAppConfigurationClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" + + +def quote_etag(etag: Optional[str]) -> Optional[str]: + if not etag or etag == "*": + return etag + if etag.startswith("W/"): + return etag + if etag.startswith('"') and etag.endswith('"'): + return etag + if etag.startswith("'") and etag.endswith("'"): + return etag + return '"' + etag + '"' + + +def prep_if_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfNotModified: + if_match = quote_etag(etag) if etag else None + return if_match + if match_condition == MatchConditions.IfPresent: + return "*" + return None + + +def prep_if_none_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfModified: + if_none_match = quote_etag(etag) if etag else None + return if_none_match + if match_condition == MatchConditions.IfMissing: + return "*" + return None diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_version.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_version.py index 9b3cbd9ff37d..be71c81bd282 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_version.py +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_version.py @@ -1,6 +1,9 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- -VERSION = "1.7.2" +VERSION = "1.0.0b1" diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/__init__.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/__init__.py index 243f403a5362..f63ec1343e47 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/__init__.py +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/__init__.py @@ -1,14 +1,29 @@ # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._azure_appconfiguration_client_async import AzureAppConfigurationClient +from typing import TYPE_CHECKING -__all__ = ["AzureAppConfigurationClient"] +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import AzureAppConfigurationClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureAppConfigurationClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_azure_appconfiguration_client_async.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_azure_appconfiguration_client_async.py deleted file mode 100644 index ea9fd28b22a1..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_azure_appconfiguration_client_async.py +++ /dev/null @@ -1,853 +0,0 @@ -# ------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ------------------------------------------------------------------------- -import functools -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, overload, cast -from azure.core import MatchConditions -from azure.core.async_paging import AsyncItemPaged -from azure.core.credentials import AzureKeyCredential -from azure.core.credentials_async import AsyncTokenCredential -from azure.core.pipeline.policies import AsyncBearerTokenCredentialPolicy -from azure.core.polling import AsyncLROPoller -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.exceptions import ( - ResourceExistsError, - ResourceModifiedError, - ResourceNotFoundError, - ResourceNotModifiedError, -) -from azure.core.rest import AsyncHttpResponse, HttpRequest -from ._sync_token_async import AsyncSyncTokenPolicy -from .._azure_appconfiguration_error import ResourceReadOnlyError -from .._azure_appconfiguration_requests import AppConfigRequestsCredentialsPolicy -from .._generated.aio import AzureAppConfiguration -from .._generated.models import ( - SnapshotUpdateParameters, - SnapshotStatus, - SnapshotFields, - SnapshotComposition, - LabelFields, - ConfigurationSettingFields, -) -from .._models import ( - ConfigurationSetting, - ConfigurationSettingPropertiesPagedAsync, - ConfigurationSettingsFilter, - ConfigurationSnapshot, - ConfigurationSettingLabel, -) -from .._utils import ( - prep_if_match, - prep_if_none_match, - get_key_filter, - get_label_filter, - parse_connection_string, -) - - -class AzureAppConfigurationClient: - """Represents a client that calls restful API of Azure App Configuration service. - - :param str base_url: Base url of the service. - :param credential: An object which can provide secrets for the app configuration service - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: Api Version. Default value is "2023-11-01". Note that overriding this default - value may result in unsupported behavior. - :paramtype api_version: str - - This is the async version of :class:`~azure.appconfiguration.AzureAppConfigurationClient` - - """ - - # pylint:disable=protected-access - def __init__(self, base_url: str, credential: AsyncTokenCredential, **kwargs: Any) -> None: - try: - if not base_url.lower().startswith("http"): - base_url = f"https://{base_url}" - except AttributeError as exc: - raise ValueError("Base URL must be a string.") from exc - - if not credential: - raise ValueError("Missing credential") - - credential_scopes = [f"{base_url.strip('/')}/.default"] - self._sync_token_policy = AsyncSyncTokenPolicy() - - if isinstance(credential, AzureKeyCredential): - id_credential = kwargs.pop("id_credential") - kwargs.update( - { - "authentication_policy": AppConfigRequestsCredentialsPolicy(credential, base_url, id_credential), - } - ) - elif hasattr(credential, "get_token"): # AsyncFakeCredential is not an instance of AsyncTokenCredential - kwargs.update( - { - "authentication_policy": AsyncBearerTokenCredentialPolicy(credential, *credential_scopes, **kwargs), - } - ) - else: - raise TypeError( - f"Unsupported credential: {type(credential)}. Use an instance of token credential from azure.identity" - ) - # mypy doesn't compare the credential type hint with the API surface in patch.py - self._impl = AzureAppConfiguration( - credential, base_url, per_call_policies=self._sync_token_policy, **kwargs # type: ignore[arg-type] - ) - - @classmethod - def from_connection_string(cls, connection_string: str, **kwargs: Any) -> "AzureAppConfigurationClient": - """Create AzureAppConfigurationClient from a Connection String. - This is the async version of :class:`~azure.appconfiguration.AzureAppConfigurationClient` - - :param str connection_string: Connection String - (one of the access keys of the Azure App Configuration resource) - used to access the Azure App Configuration. - :return: An AzureAppConfigurationClient authenticated with the connection string - :rtype: ~azure.appconfiguration.AzureAppConfigurationClient - - Example - - .. code-block:: python - - from azure.appconfiguration.aio import AzureAppConfigurationClient - - connection_str = "" - async_client = AzureAppConfigurationClient.from_connection_string(connection_str) - """ - endpoint, id_credential, secret = parse_connection_string(connection_string) - # AzureKeyCredential type is for internal use, it's not exposed in public API. - return cls( - credential=AzureKeyCredential(secret), # type: ignore[arg-type] - base_url=endpoint, - id_credential=id_credential, - **kwargs, - ) - - @distributed_trace_async - async def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> AsyncHttpResponse: - """Runs a network request using the client's existing pipeline. - - The request URL can be relative to the vault URL. The service API version used for the request is the same as - the client's unless otherwise specified. This method does not raise if the response is an error; to raise an - exception, call `raise_for_status()` on the returned response object. For more information about how to send - custom requests with this method, see https://aka.ms/azsdk/dpcodegen/python/send_request. - - :param request: The network request you want to make. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - return await self._impl._send_request(request, stream=stream, **kwargs) - - @overload - def list_configuration_settings( - self, - *, - key_filter: Optional[str] = None, - label_filter: Optional[str] = None, - tags_filter: Optional[List[str]] = None, - accept_datetime: Optional[Union[datetime, str]] = None, - fields: Optional[List[Union[str, ConfigurationSettingFields]]] = None, - **kwargs: Any, - ) -> AsyncItemPaged[ConfigurationSetting]: - """List the configuration settings stored in the configuration service, optionally filtered by - key, label, tags and accept_datetime. For more information about supported filters, see - https://learn.microsoft.com/azure/azure-app-configuration/rest-api-key-value?pivots=v23-11#supported-filters. - - :keyword key_filter: Filter results based on their keys. '*' can be used as wildcard in the beginning or end - of the filter. - :paramtype key_filter: str or None - :keyword label_filter: Filter results based on their label. '*' can be used as wildcard in the beginning or end - of the filter. - :paramtype label_filter: str or None - :keyword tags_filter: Filter results based on their tags. - :paramtype tags_filter: list[str] or None - :keyword accept_datetime: Retrieve ConfigurationSetting that existed at this datetime - :paramtype accept_datetime: ~datetime.datetime or str or None - :keyword fields: Specify which fields to include in the results. If not specified, will include all fields. - Available fields see :class:`~azure.appconfiguration.ConfigurationSettingFields`. - :paramtype fields: list[str] or list[~azure.appconfiguration.ConfigurationSettingFields] or None - :return: An async iterator of :class:`~azure.appconfiguration.ConfigurationSetting` - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.appconfiguration.ConfigurationSetting] - :raises: :class:`~azure.core.exceptions.HttpResponseError`, \ - :class:`~azure.core.exceptions.ClientAuthenticationError` - - Example - - .. code-block:: python - - from datetime import datetime, timedelta - - accept_datetime = datetime.utcnow() + timedelta(days=-1) - - all_listed = async_client.list_configuration_settings() - async for item in all_listed: - pass # do something - - filtered_listed = async_client.list_configuration_settings( - label_filter="Labe*", key_filter="Ke*", accept_datetime=str(accept_datetime) - ) - async for item in filtered_listed: - pass # do something - """ - - @overload - def list_configuration_settings( - self, - *, - snapshot_name: str, - fields: Optional[List[Union[str, ConfigurationSettingFields]]] = None, - **kwargs: Any, - ) -> AsyncItemPaged[ConfigurationSetting]: - """List the configuration settings stored under a snapshot in the configuration service, optionally filtered by - accept_datetime and fields to present in return. - - :keyword str snapshot_name: The snapshot name. - :keyword fields: Specify which fields to include in the results. If not specified, will include all fields. - Available fields see :class:`~azure.appconfiguration.ConfigurationSettingFields`. - :paramtype fields: list[str] or list[~azure.appconfiguration.ConfigurationSettingFields] or None - :return: An async iterator of :class:`~azure.appconfiguration.ConfigurationSetting` - :rtype: ~azure.core.paging.AsyncItemPaged[~azure.appconfiguration.ConfigurationSetting] - :raises: :class:`~azure.core.exceptions.HttpResponseError` - """ - - @distributed_trace - def list_configuration_settings(self, *args: Optional[str], **kwargs: Any) -> AsyncItemPaged[ConfigurationSetting]: - accept_datetime = kwargs.pop("accept_datetime", None) - if isinstance(accept_datetime, datetime): - accept_datetime = str(accept_datetime) - - select = kwargs.pop("fields", None) - if select: - select = ["locked" if x == "read_only" else x for x in select] - snapshot_name = kwargs.pop("snapshot_name", None) - - if snapshot_name is not None: - return self._impl.get_key_values( # type: ignore[return-value] - snapshot=snapshot_name, - accept_datetime=accept_datetime, - select=select, - cls=lambda objs: [ConfigurationSetting._from_generated(x) for x in objs], - **kwargs, - ) - tags = kwargs.pop("tags_filter", None) - key_filter, kwargs = get_key_filter(*args, **kwargs) - label_filter, kwargs = get_label_filter(*args, **kwargs) - command = functools.partial(self._impl.get_key_values_in_one_page, **kwargs) # type: ignore[attr-defined] - return AsyncItemPaged( - command, - key=key_filter, - label=label_filter, - accept_datetime=accept_datetime, - select=select, - tags=tags, - page_iterator_class=ConfigurationSettingPropertiesPagedAsync, - ) - - @distributed_trace_async - async def get_configuration_setting( - self, - key: str, - label: Optional[str] = None, - etag: Optional[str] = "*", - match_condition: MatchConditions = MatchConditions.Unconditionally, - *, - accept_datetime: Optional[Union[datetime, str]] = None, - **kwargs: Any, - ) -> Union[None, ConfigurationSetting]: - """Get the matched ConfigurationSetting from Azure App Configuration service - - :param key: Key of the ConfigurationSetting - :type key: str - :param label: Label used to identify the ConfigurationSetting. Default is `None`. - :type label: str or None - :param etag: Check if the ConfigurationSetting is changed. Set None to skip checking etag - :type etag: str or None - :param match_condition: The match condition to use upon the etag - :type match_condition: ~azure.core.MatchConditions - :keyword accept_datetime: Retrieve ConfigurationSetting that existed at this datetime - :paramtype accept_datetime: ~datetime.datetime or str or None - :return: The matched ConfigurationSetting object - :rtype: ~azure.appconfiguration.ConfigurationSetting or None - :raises: :class:`~azure.core.exceptions.HttpResponseError`, \ - :class:`~azure.core.exceptions.ClientAuthenticationError`, \ - :class:`~azure.core.exceptions.ResourceNotFoundError`, \ - :class:`~azure.core.exceptions.ResourceModifiedError`, \ - :class:`~azure.core.exceptions.ResourceExistsError` - - Example - - .. code-block:: python - - # in async function - fetched_config_setting = await async_client.get_configuration_setting( - key="MyKey", label="MyLabel" - ) - """ - if isinstance(accept_datetime, datetime): - accept_datetime = str(accept_datetime) - - error_map: Dict[int, Any] = {} - if match_condition == MatchConditions.IfNotModified: - error_map.update({412: ResourceModifiedError}) - if match_condition == MatchConditions.IfPresent: - error_map.update({412: ResourceNotFoundError}) - if match_condition == MatchConditions.IfMissing: - error_map.update({412: ResourceExistsError}) - - try: - key_value = await self._impl.get_key_value( - key=key, - label=label, - accept_datetime=accept_datetime, - if_match=prep_if_match(etag, match_condition), - if_none_match=prep_if_none_match(etag, match_condition), - error_map=error_map, - **kwargs, - ) - return ConfigurationSetting._from_generated(key_value) - except ResourceNotModifiedError: - return None - - @distributed_trace_async - async def add_configuration_setting( - self, configuration_setting: ConfigurationSetting, **kwargs: Any - ) -> ConfigurationSetting: - """Add a ConfigurationSetting instance into the Azure App Configuration service. - - :param configuration_setting: The ConfigurationSetting object to be added - :type configuration_setting: ~azure.appconfiguration.ConfigurationSetting - :return: The ConfigurationSetting object returned from the App Configuration service - :rtype: ~azure.appconfiguration.ConfigurationSetting - :raises: :class:`~azure.core.exceptions.HttpResponseError`, \ - :class:`~azure.core.exceptions.ClientAuthenticationError`, \ - :class:`~azure.core.exceptions.ResourceExistsError` - - Example - - .. code-block:: python - - # in async function - config_setting = ConfigurationSetting( - key="MyKey", - label="MyLabel", - value="my value", - content_type="my content type", - tags={"my tag": "my tag value"} - ) - added_config_setting = await async_client.add_configuration_setting(config_setting) - """ - key_value = configuration_setting._to_generated() - error_map = {412: ResourceExistsError} - - key_value_added = await self._impl.put_key_value( - entity=key_value, - key=key_value.key, # type: ignore - label=key_value.label, - if_none_match="*", - error_map=error_map, - **kwargs, - ) - return ConfigurationSetting._from_generated(key_value_added) - - @distributed_trace_async - async def set_configuration_setting( - self, - configuration_setting: ConfigurationSetting, - match_condition: MatchConditions = MatchConditions.Unconditionally, - *, - etag: Optional[str] = None, - **kwargs: Any, - ) -> ConfigurationSetting: - """Add or update a ConfigurationSetting. - If the configuration setting identified by key and label does not exist, this is a create. - Otherwise this is an update. - - :param configuration_setting: The ConfigurationSetting to be added (if not exists) - or updated (if exists) to the service - :type configuration_setting: ~azure.appconfiguration.ConfigurationSetting - :param match_condition: The match condition to use upon the etag - :type match_condition: ~azure.core.MatchConditions - :keyword etag: Check if the ConfigurationSetting is changed. \ - Will use the value from param configuration_setting if not set. - :paramtype etag: str or None - :return: The ConfigurationSetting returned from the service - :rtype: ~azure.appconfiguration.ConfigurationSetting - :raises: :class:`~azure.appconfiguration.ResourceReadOnlyError`, \ - :class:`~azure.core.exceptions.HttpResponseError`, \ - :class:`~azure.core.exceptions.ClientAuthenticationError`, \ - :class:`~azure.core.exceptions.ResourceModifiedError`, \ - :class:`~azure.core.exceptions.ResourceNotModifiedError`, \ - :class:`~azure.core.exceptions.ResourceNotFoundError`, \ - :class:`~azure.core.exceptions.ResourceExistsError` - - Example - - .. code-block:: python - - # in async function - config_setting = ConfigurationSetting( - key="MyKey", - label="MyLabel", - value="my set value", - content_type="my set content type", - tags={"my set tag": "my set tag value"} - ) - returned_config_setting = await async_client.set_configuration_setting(config_setting) - """ - key_value = configuration_setting._to_generated() - error_map: Dict[int, Any] = {409: ResourceReadOnlyError} - if match_condition == MatchConditions.IfNotModified: - error_map.update({412: ResourceModifiedError}) - if match_condition == MatchConditions.IfModified: - error_map.update({412: ResourceNotModifiedError}) - if match_condition == MatchConditions.IfPresent: - error_map.update({412: ResourceNotFoundError}) - if match_condition == MatchConditions.IfMissing: - error_map.update({412: ResourceExistsError}) - - key_value_set = await self._impl.put_key_value( - entity=key_value, - key=key_value.key, # type: ignore - label=key_value.label, - if_match=prep_if_match(configuration_setting.etag, match_condition), - if_none_match=prep_if_none_match(etag or configuration_setting.etag, match_condition), - error_map=error_map, - **kwargs, - ) - return ConfigurationSetting._from_generated(key_value_set) - - @distributed_trace_async - async def delete_configuration_setting( - self, - key: str, - label: Optional[str] = None, - *, - etag: Optional[str] = None, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any, - ) -> Union[None, ConfigurationSetting]: - """Delete a ConfigurationSetting if it exists - - :param key: Key used to identify the ConfigurationSetting - :type key: str - :param label: Label used to identify the ConfigurationSetting. Default is `None`. - :type label: str - :keyword etag: Check if the ConfigurationSetting is changed. Set None to skip checking etag - :paramtype etag: str or None - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The deleted ConfigurationSetting returned from the service, or None if it doesn't exist. - :rtype: ~azure.appconfiguration.ConfigurationSetting - :raises: :class:`~azure.appconfiguration.ResourceReadOnlyError`, \ - :class:`~azure.core.exceptions.HttpResponseError`, \ - :class:`~azure.core.exceptions.ClientAuthenticationError`, \ - :class:`~azure.core.exceptions.ResourceModifiedError`, \ - :class:`~azure.core.exceptions.ResourceNotModifiedError`, \ - :class:`~azure.core.exceptions.ResourceNotFoundError`, \ - :class:`~azure.core.exceptions.ResourceExistsError` - - Example - - .. code-block:: python - - # in async function - deleted_config_setting = await async_client.delete_configuration_setting( - key="MyKey", label="MyLabel" - ) - """ - error_map: Dict[int, Any] = {409: ResourceReadOnlyError} - if match_condition == MatchConditions.IfNotModified: - error_map.update({412: ResourceModifiedError}) - if match_condition == MatchConditions.IfModified: - error_map.update({412: ResourceNotModifiedError}) - if match_condition == MatchConditions.IfPresent: - error_map.update({412: ResourceNotFoundError}) - if match_condition == MatchConditions.IfMissing: - error_map.update({412: ResourceExistsError}) - - key_value_deleted = await self._impl.delete_key_value( - key=key, - label=label, - if_match=prep_if_match(etag, match_condition), - error_map=error_map, - **kwargs, - ) - if key_value_deleted: - return ConfigurationSetting._from_generated(key_value_deleted) - return None - - @distributed_trace - def list_revisions( - self, - key_filter: Optional[str] = None, - label_filter: Optional[str] = None, - *, - tags_filter: Optional[List[str]] = None, - accept_datetime: Optional[Union[datetime, str]] = None, - fields: Optional[List[Union[str, ConfigurationSettingFields]]] = None, - **kwargs: Any, - ) -> AsyncItemPaged[ConfigurationSetting]: - """ - Find the ConfigurationSetting revision history, optionally filtered by key, label, tags and accept_datetime. - For more information about supported filters, see - https://learn.microsoft.com/azure/azure-app-configuration/rest-api-revisions?pivots=v23-11#supported-filters. - - :param key_filter: Filter results based on their keys. '*' can be used as wildcard in the beginning or end - of the filter. - :type key_filter: str or None - :param label_filter: Filter results based on their label. '*' can be used as wildcard in the beginning or end - of the filter. - :type label_filter: str or None - :keyword tags_filter: Filter results based on their tags. - :paramtype tags_filter: list[str] or None - :keyword accept_datetime: Retrieve ConfigurationSetting that existed at this datetime - :paramtype accept_datetime: ~datetime.datetime or str or None - :keyword fields: Specify which fields to include in the results. If not specified, will include all fields. - Available fields see :class:`~azure.appconfiguration.ConfigurationSettingFields`. - :paramtype fields: list[str] or list[~azure.appconfiguration.ConfigurationSettingFields] or None - :return: An async iterator of :class:`~azure.appconfiguration.ConfigurationSetting` - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.appconfiguration.ConfigurationSetting] - :raises: :class:`~azure.core.exceptions.HttpResponseError`, \ - :class:`~azure.core.exceptions.ClientAuthenticationError` - - Example - - .. code-block:: python - - # in async function - from datetime import datetime, timedelta - - accept_datetime = datetime.utcnow() + timedelta(days=-1) - - all_revisions = async_client.list_revisions() - async for item in all_revisions: - pass # do something - - filtered_revisions = async_client.list_revisions( - label_filter="Labe*", key_filter="Ke*", accept_datetime=str(accept_datetime) - ) - async for item in filtered_revisions: - pass # do something - """ - if isinstance(accept_datetime, datetime): - accept_datetime = str(accept_datetime) - if fields: - fields = ["locked" if x == "read_only" else x for x in fields] - - return self._impl.get_revisions( # type: ignore[return-value] - label=label_filter, - key=key_filter, - accept_datetime=accept_datetime, - select=fields, - tags=tags_filter, - cls=lambda objs: [ConfigurationSetting._from_generated(x) for x in objs], - **kwargs, - ) - - @distributed_trace_async - async def set_read_only( - self, - configuration_setting: ConfigurationSetting, - read_only: bool = True, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - **kwargs: Any, - ) -> ConfigurationSetting: - """Set a configuration setting read only - - :param configuration_setting: The ConfigurationSetting to be set read only - :type configuration_setting: ~azure.appconfiguration.ConfigurationSetting - :param read_only: Set the read only setting if true, else clear the read only setting - :type read_only: bool - :keyword match_condition: The match condition to use upon the etag - :paramtype match_condition: ~azure.core.MatchConditions - :return: The ConfigurationSetting returned from the service - :rtype: ~azure.appconfiguration.ConfigurationSetting - :raises: :class:`~azure.core.exceptions.HttpResponseError`, \ - :class:`~azure.core.exceptions.ClientAuthenticationError`, \ - :class:`~azure.core.exceptions.ResourceNotFoundError` - - Example - - .. code-block:: python - - config_setting = await async_client.get_configuration_setting( - key="MyKey", label="MyLabel" - ) - - read_only_config_setting = await async_client.set_read_only(config_setting) - read_only_config_setting = await client.set_read_only(config_setting, read_only=False) - """ - error_map: Dict[int, Any] = {} - if match_condition == MatchConditions.IfNotModified: - error_map.update({412: ResourceModifiedError}) - if match_condition == MatchConditions.IfModified: - error_map.update({412: ResourceNotModifiedError}) - if match_condition == MatchConditions.IfPresent: - error_map.update({412: ResourceNotFoundError}) - if match_condition == MatchConditions.IfMissing: - error_map.update({412: ResourceExistsError}) - - if read_only: - key_value = await self._impl.put_lock( - key=configuration_setting.key, - label=configuration_setting.label, - if_match=prep_if_match(configuration_setting.etag, match_condition), - if_none_match=prep_if_none_match(configuration_setting.etag, match_condition), - error_map=error_map, - **kwargs, - ) - else: - key_value = await self._impl.delete_lock( - key=configuration_setting.key, - label=configuration_setting.label, - if_match=prep_if_match(configuration_setting.etag, match_condition), - if_none_match=prep_if_none_match(configuration_setting.etag, match_condition), - error_map=error_map, - **kwargs, - ) - return ConfigurationSetting._from_generated(key_value) - - @distributed_trace - def list_labels( - self, - *, - name: Optional[str] = None, - after: Optional[str] = None, - accept_datetime: Optional[Union[datetime, str]] = None, - fields: Optional[List[Union[str, LabelFields]]] = None, - **kwargs: Any, - ) -> AsyncItemPaged[ConfigurationSettingLabel]: - """Gets a list of labels. - - :keyword name: A filter for the name of the returned labels. '*' can be used as wildcard - in the beginning or end of the filter. For more information about supported filters, see - https://learn.microsoft.com/azure/azure-app-configuration/rest-api-labels?pivots=v23-11#supported-filters. - :paramtype name: str or None - :keyword after: Instructs the server to return elements that appear after the element referred to - by the specified token. - :paramtype after: str or None - :keyword accept_datetime: Requests the server to respond with the state of the resource at the - specified time. - :paramtype accept_datetime: ~datetime.datetime or str or None - :keyword fields: Specify which fields to include in the results. If not specified, will include all fields. - Available fields see :class:`~azure.appconfiguration.LabelFields`. - :paramtype fields: list[str] or list[~azure.appconfiguration.LabelFields] or None - :return: An async iterator of labels. - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.appconfiguration.ConfigurationSettingLabel] - :raises: :class:`~azure.core.exceptions.HttpResponseError` - """ - if isinstance(accept_datetime, datetime): - accept_datetime = str(accept_datetime) - return self._impl.get_labels( # type: ignore[return-value] - name=name, - after=after, - accept_datetime=accept_datetime, - select=fields, - cls=lambda objs: [ConfigurationSettingLabel(name=x.name) for x in objs], - **kwargs, - ) - - @distributed_trace_async - async def begin_create_snapshot( - self, - name: str, - filters: List[ConfigurationSettingsFilter], - *, - composition_type: Optional[Union[str, SnapshotComposition]] = None, - retention_period: Optional[int] = None, - tags: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> AsyncLROPoller[ConfigurationSnapshot]: - """Create a snapshot of the configuration settings. - - :param name: The name of the configuration snapshot to create. - :type name: str - :param filters: A list of filters used to filter the configuration settings by key field and label field - included in the configuration snapshot. - :type filters: list[~azure.appconfiguration.ConfigurationSettingsFilter] - :keyword composition_type: The composition type describes how the key-values within the configuration - snapshot are composed. Known values are: "key" and "key_label". The "key" composition type - ensures there are no two key-values containing the same key. The 'key_label' composition type ensures - there are no two key-values containing the same key and label. - :paramtype composition_type: str or ~azure.appconfiguration.SnapshotComposition or None - :keyword retention_period: The amount of time, in seconds, that a configuration snapshot will remain in the - archived state before expiring. This property is only writable during the creation of a configuration - snapshot. If not specified, will set to 2592000(30 days). If specified, should be - in range 3600(1 hour) to 7776000(90 days). - :paramtype retention_period: int or None - :keyword tags: The tags of the configuration snapshot. - :paramtype tags: dict[str, str] or None - :return: A poller for create configuration snapshot operation. Call `result()` on this object to wait for the - operation to complete and get the created snapshot. - :rtype: ~azure.core.polling.LROPoller[~azure.appconfiguration.ConfigurationSnapshot] - :raises: :class:`~azure.core.exceptions.HttpResponseError` - """ - snapshot = ConfigurationSnapshot( - filters=filters, composition_type=composition_type, retention_period=retention_period, tags=tags - ) - return cast( - AsyncLROPoller[ConfigurationSnapshot], - await self._impl.begin_create_snapshot( - name=name, entity=snapshot._to_generated(), cls=ConfigurationSnapshot._from_deserialized, **kwargs - ), - ) - - @distributed_trace_async - async def archive_snapshot( - self, - name: str, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - etag: Optional[str] = None, - **kwargs: Any, - ) -> ConfigurationSnapshot: - """Archive a configuration setting snapshot. It will update the status of a snapshot from "ready" to "archived". - The retention period will start to count, the snapshot will expire when the entire retention period elapses. - - :param name: The name of the configuration setting snapshot to archive. - :type name: str - :keyword match_condition: The match condition to use upon the etag. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword etag: Check if the ConfigurationSnapshot is changed. Set None to skip checking etag. - :paramtype etag: str or None - :return: The ConfigurationSnapshot returned from the service. - :rtype: ~azure.appconfiguration.ConfigurationSnapshot - :raises: :class:`~azure.core.exceptions.HttpResponseError` - """ - error_map: Dict[int, Any] = {} - if match_condition == MatchConditions.IfNotModified: - error_map.update({412: ResourceModifiedError}) - if match_condition == MatchConditions.IfModified: - error_map.update({412: ResourceNotModifiedError}) - if match_condition == MatchConditions.IfPresent: - error_map.update({412: ResourceNotFoundError}) - if match_condition == MatchConditions.IfMissing: - error_map.update({412: ResourceExistsError}) - generated_snapshot = await self._impl.update_snapshot( - name=name, - entity=SnapshotUpdateParameters(status=SnapshotStatus.ARCHIVED), - if_match=prep_if_match(etag, match_condition), - if_none_match=prep_if_none_match(etag, match_condition), - error_map=error_map, - **kwargs, - ) - return ConfigurationSnapshot._from_generated(generated_snapshot) - - @distributed_trace_async - async def recover_snapshot( - self, - name: str, - *, - match_condition: MatchConditions = MatchConditions.Unconditionally, - etag: Optional[str] = None, - **kwargs: Any, - ) -> ConfigurationSnapshot: - """Recover a configuration setting snapshot. It will update the status of a snapshot from "archived" to "ready". - - :param name: The name of the configuration setting snapshot to recover. - :type name: str - :keyword match_condition: The match condition to use upon the etag. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword etag: Check if the ConfigurationSnapshot is changed. Set None to skip checking etag. - :paramtype etag: str or None - :return: The ConfigurationSnapshot returned from the service. - :rtype: ~azure.appconfiguration.ConfigurationSnapshot - :raises: :class:`~azure.core.exceptions.HttpResponseError` - """ - error_map: Dict[int, Any] = {} - if match_condition == MatchConditions.IfNotModified: - error_map.update({412: ResourceModifiedError}) - if match_condition == MatchConditions.IfModified: - error_map.update({412: ResourceNotModifiedError}) - if match_condition == MatchConditions.IfPresent: - error_map.update({412: ResourceNotFoundError}) - if match_condition == MatchConditions.IfMissing: - error_map.update({412: ResourceExistsError}) - generated_snapshot = await self._impl.update_snapshot( - name=name, - entity=SnapshotUpdateParameters(status=SnapshotStatus.READY), - if_match=prep_if_match(etag, match_condition), - if_none_match=prep_if_none_match(etag, match_condition), - error_map=error_map, - **kwargs, - ) - return ConfigurationSnapshot._from_generated(generated_snapshot) - - @distributed_trace_async - async def get_snapshot( - self, name: str, *, fields: Optional[List[Union[str, SnapshotFields]]] = None, **kwargs: Any - ) -> ConfigurationSnapshot: - """Get a configuration setting snapshot. - - :param name: The name of the configuration setting snapshot to retrieve. - :type name: str - :keyword fields: Specify which fields to include in the results. If not specified, will include all fields. - Available fields see :class:`~azure.appconfiguration.SnapshotFields`. - :paramtype fields: list[str] or list[~azure.appconfiguration.SnapshotFields] or None - :return: The ConfigurationSnapshot returned from the service. - :rtype: ~azure.appconfiguration.ConfigurationSnapshot - :raises: :class:`~azure.core.exceptions.HttpResponseError` - """ - generated_snapshot = await self._impl.get_snapshot( - name=name, if_match=None, if_none_match=None, select=fields, **kwargs - ) - return ConfigurationSnapshot._from_generated(generated_snapshot) - - @distributed_trace - def list_snapshots( - self, - *, - name: Optional[str] = None, - fields: Optional[List[Union[str, SnapshotFields]]] = None, - status: Optional[List[Union[str, SnapshotStatus]]] = None, - **kwargs: Any, - ) -> AsyncItemPaged[ConfigurationSnapshot]: - """List the configuration setting snapshots stored in the configuration service, optionally filtered by - snapshot name, snapshot status and fields to present in return. - - :keyword name: Filter results based on snapshot name. - :paramtype name: str or None - :keyword fields: Specify which fields to include in the results. If not specified, will include all fields. - Available fields see :class:`~azure.appconfiguration.SnapshotFields`. - :paramtype fields: list[str] or list[~azure.appconfiguration.SnapshotFields] or None - :keyword status: Filter results based on snapshot keys. Available status see - :class:`~azure.appconfiguration.SnapshotStatus`. - :paramtype status: list[str] or list[~azure.appconfiguration.SnapshotStatus] or None - :return: An iterator of :class:`~azure.appconfiguration.ConfigurationSnapshot` - :rtype: ~azure.core.paging.ItemPaged[~azure.appconfiguration.ConfigurationSnapshot] - :raises: :class:`~azure.core.exceptions.HttpResponseError` - """ - return self._impl.get_snapshots( # type: ignore[return-value] - name=name, - select=fields, - status=status, - cls=lambda objs: [ConfigurationSnapshot._from_generated(x) for x in objs], - **kwargs, - ) - - async def update_sync_token(self, token: str) -> None: - """Add a sync token to the internal list of tokens. - - :param str token: The sync token to be added to the internal list of tokens - """ - - await self._sync_token_policy.add_token(token) - - async def close(self) -> None: - """Close all connections made by the client""" - await self._impl._client.close() - - async def __aenter__(self) -> "AzureAppConfigurationClient": - await self._impl.__aenter__() - return self - - async def __aexit__(self, *args: Any) -> None: - await self._impl.__aexit__(*args) diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/_azure_app_configuration.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_client.py similarity index 71% rename from sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/_azure_app_configuration.py rename to sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_client.py index 39ae86b6cec9..7959eac63eaa 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/_azure_app_configuration.py +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_client.py @@ -2,12 +2,12 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable, Optional +from typing import Any, Awaitable, TYPE_CHECKING, Union from typing_extensions import Self from azure.core import AsyncPipelineClient @@ -15,36 +15,35 @@ from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest -from .. import models as _models from .._serialization import Deserializer, Serializer -from ._configuration import AzureAppConfigurationConfiguration -from .operations import AzureAppConfigurationOperationsMixin +from ._configuration import AzureAppConfigurationClientConfiguration +from ._operations import AzureAppConfigurationClientOperationsMixin +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential -class AzureAppConfiguration(AzureAppConfigurationOperationsMixin): # pylint: disable=client-accepts-api-version-keyword - """AzureAppConfiguration. - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.AzureKeyCredential - :param endpoint: The endpoint of the App Configuration instance to send requests to. Required. +class AzureAppConfigurationClient(AzureAppConfigurationClientOperationsMixin): + """Azure App Configuration REST API. + + :param endpoint: Required. :type endpoint: str - :param sync_token: Used to guarantee real-time consistency between requests. Default value is - None. - :type sync_token: str - :keyword api_version: Api Version. Default value is "2023-11-01". Note that overriding this - default value may result in unsupported behavior. + :param credential: Credential used to authenticate requests to the service. Is either a + AzureKeyCredential type or a TokenCredential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is "2023-11-01". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( - self, credential: AzureKeyCredential, endpoint: str, sync_token: Optional[str] = None, **kwargs: Any + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any ) -> None: _endpoint = "{endpoint}" - self._config = AzureAppConfigurationConfiguration( - credential=credential, endpoint=endpoint, sync_token=sync_token, **kwargs - ) + self._config = AzureAppConfigurationClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -64,12 +63,11 @@ def __init__( ] self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False - def _send_request( + def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. @@ -77,7 +75,7 @@ def _send_request( >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = await client._send_request(request) + >>> response = await client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/_configuration.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_configuration.py similarity index 60% rename from sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/_configuration.py rename to sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_configuration.py index 0de2ae01c4d9..cc5729f26f28 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/_configuration.py +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_configuration.py @@ -2,54 +2,63 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional +from typing import Any, TYPE_CHECKING, Union from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies -VERSION = "unknown" +from .._version import VERSION +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential -class AzureAppConfigurationConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long - """Configuration for AzureAppConfiguration. + +class AzureAppConfigurationClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for AzureAppConfigurationClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.AzureKeyCredential - :param endpoint: The endpoint of the App Configuration instance to send requests to. Required. + :param endpoint: Required. :type endpoint: str - :param sync_token: Used to guarantee real-time consistency between requests. Default value is - None. - :type sync_token: str - :keyword api_version: Api Version. Default value is "2023-11-01". Note that overriding this - default value may result in unsupported behavior. + :param credential: Credential used to authenticate requests to the service. Is either a + AzureKeyCredential type or a TokenCredential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is "2023-11-01". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__( - self, credential: AzureKeyCredential, endpoint: str, sync_token: Optional[str] = None, **kwargs: Any + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any ) -> None: api_version: str = kwargs.pop("api_version", "2023-11-01") - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") - self.credential = credential self.endpoint = endpoint - self.sync_token = sync_token + self.credential = credential self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://azconfig.io/.default"]) kwargs.setdefault("sdk_moniker", "appconfiguration/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "Connection String", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + def _configure(self, **kwargs: Any) -> None: self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) @@ -61,6 +70,4 @@ def _configure(self, **kwargs: Any) -> None: self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AzureKeyCredentialPolicy( - self.credential, "Connection String", **kwargs - ) + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/__init__.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_operations/__init__.py similarity index 56% rename from sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/__init__.py rename to sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_operations/__init__.py index 75469c2e980c..a90b04c612d7 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/__init__.py +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_operations/__init__.py @@ -2,22 +2,24 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._azure_app_configuration import AzureAppConfiguration +from typing import TYPE_CHECKING -try: - from ._patch import __all__ as _patch_all +if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] + +from ._operations import AzureAppConfigurationClientOperationsMixin # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AzureAppConfiguration", + "AzureAppConfigurationClientOperationsMixin", ] -__all__.extend([p for p in _patch_all if p not in __all__]) - +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/operations/_azure_app_configuration_operations.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_operations/_operations.py similarity index 56% rename from sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/operations/_azure_app_configuration_operations.py rename to sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_operations/_operations.py index 1f1afcee5036..90039edad8b3 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/aio/operations/_azure_app_configuration_operations.py +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_operations/_operations.py @@ -1,35 +1,24 @@ -# pylint: disable=too-many-lines,too-many-statements +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase +import json import sys -from typing import ( - Any, - AsyncIterable, - AsyncIterator, - Callable, - Dict, - IO, - List, - Optional, - Type, - TypeVar, - Union, - cast, - overload, -) +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import MatchConditions from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, + ResourceModifiedError, ResourceNotFoundError, ResourceNotModifiedError, StreamClosedError, @@ -45,46 +34,52 @@ from azure.core.utils import case_insensitive_dict from ... import models as _models -from ...operations._azure_app_configuration_operations import ( - build_check_key_value_request, - build_check_key_values_request, - build_check_keys_request, - build_check_labels_request, - build_check_revisions_request, - build_check_snapshot_request, - build_check_snapshots_request, - build_create_snapshot_request, - build_delete_key_value_request, - build_delete_lock_request, - build_get_key_value_request, - build_get_key_values_request, - build_get_keys_request, - build_get_labels_request, - build_get_operation_details_request, - build_get_revisions_request, - build_get_snapshot_request, - build_get_snapshots_request, - build_put_key_value_request, - build_put_lock_request, - build_update_snapshot_request, +from ..._model_base import SdkJSONEncoder, _deserialize +from ..._operations._operations import ( + build_azure_app_configuration_check_key_value_request, + build_azure_app_configuration_check_key_values_request, + build_azure_app_configuration_check_keys_request, + build_azure_app_configuration_check_labels_request, + build_azure_app_configuration_check_revisions_request, + build_azure_app_configuration_check_snapshot_request, + build_azure_app_configuration_check_snapshots_request, + build_azure_app_configuration_create_snapshot_request, + build_azure_app_configuration_delete_key_value_request, + build_azure_app_configuration_delete_lock_request, + build_azure_app_configuration_get_key_value_request, + build_azure_app_configuration_get_key_values_request, + build_azure_app_configuration_get_keys_request, + build_azure_app_configuration_get_labels_request, + build_azure_app_configuration_get_operation_details_request, + build_azure_app_configuration_get_revisions_request, + build_azure_app_configuration_get_snapshot_request, + build_azure_app_configuration_get_snapshots_request, + build_azure_app_configuration_put_key_value_request, + build_azure_app_configuration_put_lock_request, + build_azure_app_configuration_update_snapshot_request, ) -from .._vendor import AzureAppConfigurationMixinABC +from .._vendor import AzureAppConfigurationClientMixinABC if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AzureAppConfigurationOperationsMixin(AzureAppConfigurationMixinABC): # pylint: disable=too-many-public-methods +class AzureAppConfigurationClientOperationsMixin( # pylint: disable=too-many-public-methods,name-too-long + AzureAppConfigurationClientMixinABC +): @distributed_trace def get_keys( self, + *, name: Optional[str] = None, after: Optional[str] = None, + sync_token: Optional[str] = None, accept_datetime: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Key"]: @@ -92,25 +87,28 @@ def get_keys( Gets a list of keys. - :param name: A filter for the name of the returned keys. Default value is None. - :type name: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :return: An iterator like instance of either Key or the result of cls(response) + :keyword name: A filter for the name of the returned keys. Default value is None. + :paramtype name: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :return: An iterator like instance of Key :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.appconfiguration.models.Key] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KeyListResult] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Key]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -121,12 +119,12 @@ def get_keys( def prepare_request(next_link=None): if not next_link: - _request = build_get_keys_request( + _request = build_azure_app_configuration_get_keys_request( name=name, after=after, + sync_token=sync_token, accept_datetime=accept_datetime, - sync_token=self._config.sync_token, - api_version=api_version, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -156,15 +154,15 @@ def prepare_request(next_link=None): ), } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" + return _request async def extract_data(pipeline_response): - deserialized = self._deserialize("KeyListResult", pipeline_response) - list_of_elem = deserialized.items + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.Key], deserialized["items"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) + return deserialized.get("@nextLink") or None, AsyncList(list_of_elem) async def get_next(next_link=None): _request = prepare_request(next_link) @@ -177,7 +175,7 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -185,30 +183,36 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def check_keys( # pylint: disable=inconsistent-return-statements + async def check_keys( self, + *, name: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, **kwargs: Any - ) -> None: + ) -> bool: """Requests the headers and status of the given resource. Requests the headers and status of the given resource. - :param name: A filter for the name of the returned keys. Default value is None. - :type name: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :return: None or the result of cls(response) - :rtype: None + :keyword name: A filter for the name of the returned keys. Default value is None. + :paramtype name: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -217,17 +221,16 @@ async def check_keys( # pylint: disable=inconsistent-return-statements error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_check_keys_request( + _request = build_azure_app_configuration_check_keys_request( name=name, + sync_token=sync_token, after=after, accept_datetime=accept_datetime, - sync_token=self._config.sync_token, - api_version=api_version, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -245,92 +248,104 @@ async def check_keys( # pylint: disable=inconsistent-return-statements if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) if cls: return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace def get_key_values( self, + *, key: Optional[str] = None, label: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, snapshot: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, tags: Optional[List[str]] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> AsyncIterable["_models.KeyValue"]: """Gets a list of key-values. Gets a list of key-values. - :param key: A filter used to match keys. Syntax reference: + :keyword key: A filter used to match keys. Syntax reference: https://aka.ms/azconfig/docs/keyvaluefiltering. Default value is None. - :type key: str - :param label: A filter used to match labels. Syntax reference: + :paramtype key: str + :keyword label: A filter used to match labels. Syntax reference: https://aka.ms/azconfig/docs/keyvaluefiltering. Default value is None. - :type label: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param select: Used to select what fields are present in the returned resource(s). Default + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] - :param snapshot: A filter used get key-values for a snapshot. The value should be the name of + :paramtype select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] + :keyword snapshot: A filter used get key-values for a snapshot. The value should be the name of the snapshot. Not valid when used with 'key' and 'label' filters. Default value is None. - :type snapshot: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param tags: A filter used to query by tags. Syntax reference: + :paramtype snapshot: str + :keyword tags: A filter used to query by tags. Syntax reference: https://aka.ms/azconfig/docs/keyvaluefiltering. Default value is None. - :type tags: list[str] - :return: An iterator like instance of either KeyValue or the result of cls(response) + :paramtype tags: list[str] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: An iterator like instance of KeyValue :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.appconfiguration.models.KeyValue] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KeyValueListResult] = kwargs.pop("cls", None) + cls: ClsType[List[_models.KeyValue]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: - _request = build_get_key_values_request( + _request = build_azure_app_configuration_get_key_values_request( key=key, label=label, + sync_token=sync_token, after=after, accept_datetime=accept_datetime, select=select, snapshot=snapshot, - if_match=if_match, - if_none_match=if_none_match, tags=tags, - sync_token=self._config.sync_token, - api_version=api_version, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -360,15 +375,15 @@ def prepare_request(next_link=None): ), } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" + return _request async def extract_data(pipeline_response): - deserialized = self._deserialize("KeyValueListResult", pipeline_response) - list_of_elem = deserialized.items + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.KeyValue], deserialized["items"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) + return deserialized.get("@nextLink") or None, AsyncList(list_of_elem) async def get_next(next_link=None): _request = prepare_request(next_link) @@ -381,7 +396,7 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -389,80 +404,90 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def check_key_values( # pylint: disable=inconsistent-return-statements + async def check_key_values( self, + *, key: Optional[str] = None, label: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, snapshot: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, tags: Optional[List[str]] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> None: + ) -> bool: """Requests the headers and status of the given resource. Requests the headers and status of the given resource. - :param key: A filter used to match keys. Syntax reference: + :keyword key: A filter used to match keys. Syntax reference: https://aka.ms/azconfig/docs/keyvaluefiltering. Default value is None. - :type key: str - :param label: A filter used to match labels. Syntax reference: + :paramtype key: str + :keyword label: A filter used to match labels. Syntax reference: https://aka.ms/azconfig/docs/keyvaluefiltering. Default value is None. - :type label: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param select: Used to select what fields are present in the returned resource(s). Default + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] - :param snapshot: A filter used get key-values for a snapshot. Not valid when used with 'key' + :paramtype select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] + :keyword snapshot: A filter used get key-values for a snapshot. Not valid when used with 'key' and 'label' filters. Default value is None. - :type snapshot: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param tags: A filter used to query by tags. Syntax reference: + :paramtype snapshot: str + :keyword tags: A filter used to query by tags. Syntax reference: https://aka.ms/azconfig/docs/keyvaluefiltering. Default value is None. - :type tags: list[str] - :return: None or the result of cls(response) - :rtype: None + :paramtype tags: list[str] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_check_key_values_request( + _request = build_azure_app_configuration_check_key_values_request( key=key, label=label, + sync_token=sync_token, after=after, accept_datetime=accept_datetime, select=select, snapshot=snapshot, - if_match=if_match, - if_none_match=if_none_match, tags=tags, - sync_token=self._config.sync_token, - api_version=api_version, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -480,7 +505,8 @@ async def check_key_values( # pylint: disable=inconsistent-return-statements if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) @@ -488,65 +514,76 @@ async def check_key_values( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace_async async def get_key_value( self, key: str, + *, label: Optional[str] = None, - accept_datetime: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, + sync_token: Optional[str] = None, + accept_datetime: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.KeyValue: """Gets a single key-value. Gets a single key-value. - :param key: The key of the key-value to retrieve. Required. + :param key: The key of the key-value. Required. :type key: str - :param label: The label of the key-value to retrieve. Default value is None. - :type label: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param select: Used to select what fields are present in the returned resource(s). Default + :keyword label: The label of the key-value to retrieve. Default value is None. + :paramtype label: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] - :return: KeyValue or the result of cls(response) + :paramtype select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KeyValue. The KeyValue is compatible with MutableMapping :rtype: ~azure.appconfiguration.models.KeyValue :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.KeyValue] = kwargs.pop("cls", None) - _request = build_get_key_value_request( + _request = build_azure_app_configuration_get_key_value_request( key=key, label=label, - accept_datetime=accept_datetime, - if_match=if_match, - if_none_match=if_none_match, select=select, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + accept_datetime=accept_datetime, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -555,7 +592,7 @@ async def get_key_value( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -563,15 +600,27 @@ async def get_key_value( response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("KeyValue", pipeline_response.http_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.KeyValue, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -579,88 +628,55 @@ async def get_key_value( return deserialized # type: ignore @overload - async def put_key_value( + async def _put_key_value( self, key: str, - label: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, entity: Optional[_models.KeyValue] = None, *, - content_type: str = "application/json", + content_type: str, + label: Optional[str] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models.KeyValue: - """Creates a key-value. - - Creates a key-value. - - :param key: The key of the key-value to create. Required. - :type key: str - :param label: The label of the key-value to create. Default value is None. - :type label: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param entity: The key-value to create. Default value is None. - :type entity: ~azure.appconfiguration.models.KeyValue - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: KeyValue or the result of cls(response) - :rtype: ~azure.appconfiguration.models.KeyValue - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models.KeyValue: ... @overload - async def put_key_value( + async def _put_key_value( self, key: str, + entity: Optional[JSON] = None, + *, + content_type: str, label: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models.KeyValue: ... + @overload + async def _put_key_value( + self, + key: str, entity: Optional[IO[bytes]] = None, *, - content_type: str = "application/json", + content_type: str, + label: Optional[str] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models.KeyValue: - """Creates a key-value. - - Creates a key-value. - - :param key: The key of the key-value to create. Required. - :type key: str - :param label: The label of the key-value to create. Default value is None. - :type label: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param entity: The key-value to create. Default value is None. - :type entity: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Known values are: 'application/*+json', 'application/json', 'application/json-patch+json', - 'application/vnd.microsoft.appconfig.kv+json', - 'application/vnd.microsoft.appconfig.kvset+json', 'text/json'. Default value is - "application/json". - :paramtype content_type: str - :return: KeyValue or the result of cls(response) - :rtype: ~azure.appconfiguration.models.KeyValue - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models.KeyValue: ... @distributed_trace_async - async def put_key_value( + async def _put_key_value( self, key: str, + entity: Optional[Union[_models.KeyValue, JSON, IO[bytes]]] = None, + *, label: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, - entity: Optional[Union[_models.KeyValue, IO[bytes]]] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.KeyValue: """Creates a key-value. @@ -669,56 +685,61 @@ async def put_key_value( :param key: The key of the key-value to create. Required. :type key: str - :param label: The label of the key-value to create. Default value is None. - :type label: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param entity: The key-value to create. Is either a KeyValue type or a IO[bytes] type. Default - value is None. - :type entity: ~azure.appconfiguration.models.KeyValue or IO[bytes] - :return: KeyValue or the result of cls(response) + :param entity: The key-value to create. Is one of the following types: KeyValue, JSON, + IO[bytes] Default value is None. + :type entity: ~azure.appconfiguration.models.KeyValue or JSON or IO[bytes] + :keyword label: The label of the key-value to create. Default value is None. + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KeyValue. The KeyValue is compatible with MutableMapping :rtype: ~azure.appconfiguration.models.KeyValue :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.KeyValue] = kwargs.pop("cls", None) content_type = content_type or "application/json" - _json = None _content = None if isinstance(entity, (IOBase, bytes)): _content = entity else: if entity is not None: - _json = self._serialize.body(entity, "KeyValue") + _content = json.dumps(entity, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: - _json = None + _content = None - _request = build_put_key_value_request( + _request = build_azure_app_configuration_put_key_value_request( key=key, label=label, - if_match=if_match, - if_none_match=if_none_match, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + etag=etag, + match_condition=match_condition, content_type=content_type, - json=_json, + api_version=self._config.api_version, content=_content, headers=_headers, params=_params, @@ -728,7 +749,7 @@ async def put_key_value( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -736,15 +757,24 @@ async def put_key_value( response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("KeyValue", pipeline_response.http_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.KeyValue, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -753,7 +783,14 @@ async def put_key_value( @distributed_trace_async async def delete_key_value( - self, key: str, label: Optional[str] = None, if_match: Optional[str] = None, **kwargs: Any + self, + key: str, + *, + label: Optional[str] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any ) -> Optional[_models.KeyValue]: """Deletes a key-value. @@ -761,35 +798,46 @@ async def delete_key_value( :param key: The key of the key-value to delete. Required. :type key: str - :param label: The label of the key-value to delete. Default value is None. - :type label: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :return: KeyValue or None or the result of cls(response) + :keyword label: The label of the key-value to delete. Default value is None. + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KeyValue or None. The KeyValue is compatible with MutableMapping :rtype: ~azure.appconfiguration.models.KeyValue or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[Optional[_models.KeyValue]] = kwargs.pop("cls", None) - _request = build_delete_key_value_request( + _request = build_azure_app_configuration_delete_key_value_request( key=key, label=label, - if_match=if_match, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -798,7 +846,7 @@ async def delete_key_value( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -806,8 +854,13 @@ async def delete_key_value( response = pipeline_response.http_response if response.status_code not in [200, 204]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) deserialized = None @@ -815,8 +868,12 @@ async def delete_key_value( if response.status_code == 200: response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("KeyValue", pipeline_response.http_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.KeyValue, response.json()) if response.status_code == 204: response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) @@ -827,63 +884,73 @@ async def delete_key_value( return deserialized # type: ignore @distributed_trace_async - async def check_key_value( # pylint: disable=inconsistent-return-statements + async def check_key_value( self, key: str, + *, label: Optional[str] = None, + sync_token: Optional[str] = None, accept_datetime: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> None: + ) -> bool: """Requests the headers and status of the given resource. Requests the headers and status of the given resource. :param key: The key of the key-value to retrieve. Required. :type key: str - :param label: The label of the key-value to retrieve. Default value is None. - :type label: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param select: Used to select what fields are present in the returned resource(s). Default + :keyword label: The label of the key-value to retrieve. Default value is None. + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] - :return: None or the result of cls(response) - :rtype: None + :paramtype select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_check_key_value_request( + _request = build_azure_app_configuration_check_key_value_request( key=key, label=label, + sync_token=sync_token, accept_datetime=accept_datetime, - if_match=if_match, - if_none_match=if_none_match, select=select, - sync_token=self._config.sync_token, - api_version=api_version, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -901,7 +968,8 @@ async def check_key_value( # pylint: disable=inconsistent-return-statements if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) @@ -909,42 +977,47 @@ async def check_key_value( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace def get_snapshots( self, + *, name: Optional[str] = None, after: Optional[str] = None, select: Optional[List[Union[str, _models.SnapshotFields]]] = None, status: Optional[List[Union[str, _models.SnapshotStatus]]] = None, + sync_token: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.Snapshot"]: """Gets a list of key-value snapshots. Gets a list of key-value snapshots. - :param name: A filter for the name of the returned snapshots. Default value is None. - :type name: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param select: Used to select what fields are present in the returned resource(s). Default + :keyword name: A filter for the name of the returned snapshots. Default value is None. + :paramtype name: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.SnapshotFields] - :param status: Used to filter returned snapshots by their status property. Default value is + :paramtype select: list[str or ~azure.appconfiguration.models.SnapshotFields] + :keyword status: Used to filter returned snapshots by their status property. Default value is + None. + :paramtype status: list[str or ~azure.appconfiguration.models.SnapshotStatus] + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is None. - :type status: list[str or ~azure.appconfiguration.models.SnapshotStatus] - :return: An iterator like instance of either Snapshot or the result of cls(response) + :paramtype sync_token: str + :return: An iterator like instance of Snapshot :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.appconfiguration.models.Snapshot] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.SnapshotListResult] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Snapshot]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -955,13 +1028,13 @@ def get_snapshots( def prepare_request(next_link=None): if not next_link: - _request = build_get_snapshots_request( + _request = build_azure_app_configuration_get_snapshots_request( name=name, after=after, select=select, status=status, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -991,15 +1064,15 @@ def prepare_request(next_link=None): ), } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" + return _request async def extract_data(pipeline_response): - deserialized = self._deserialize("SnapshotListResult", pipeline_response) - list_of_elem = deserialized.items + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.Snapshot], deserialized["items"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) + return deserialized.get("@nextLink") or None, AsyncList(list_of_elem) async def get_next(next_link=None): _request = prepare_request(next_link) @@ -1012,7 +1085,7 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -1020,21 +1093,24 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def check_snapshots( # pylint: disable=inconsistent-return-statements - self, after: Optional[str] = None, **kwargs: Any - ) -> None: + async def check_snapshots( + self, *, sync_token: Optional[str] = None, after: Optional[str] = None, **kwargs: Any + ) -> bool: """Requests the headers and status of the given resource. Requests the headers and status of the given resource. - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :return: None or the result of cls(response) - :rtype: None + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1043,15 +1119,14 @@ async def check_snapshots( # pylint: disable=inconsistent-return-statements error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_check_snapshots_request( + _request = build_azure_app_configuration_check_snapshots_request( + sync_token=sync_token, after=after, - sync_token=self._config.sync_token, - api_version=api_version, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1069,63 +1144,74 @@ async def check_snapshots( # pylint: disable=inconsistent-return-statements if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) if cls: return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace_async async def get_snapshot( self, name: str, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, + *, select: Optional[List[Union[str, _models.SnapshotFields]]] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.Snapshot: """Gets a single key-value snapshot. Gets a single key-value snapshot. - :param name: The name of the key-value snapshot to retrieve. Required. + :param name: The name of the snapshot. Required. :type name: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :param select: Used to select what fields are present in the returned resource(s). Default + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.SnapshotFields] - :return: Snapshot or the result of cls(response) + :paramtype select: list[str or ~azure.appconfiguration.models.SnapshotFields] + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: Snapshot. The Snapshot is compatible with MutableMapping :rtype: ~azure.appconfiguration.models.Snapshot :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Snapshot] = kwargs.pop("cls", None) - _request = build_get_snapshot_request( + _request = build_azure_app_configuration_get_snapshot_request( name=name, - if_match=if_match, - if_none_match=if_none_match, select=select, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1134,7 +1220,7 @@ async def get_snapshot( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1142,26 +1228,106 @@ async def get_snapshot( response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) response_headers["Link"] = self._deserialize("str", response.headers.get("Link")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("Snapshot", pipeline_response.http_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.Snapshot, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore + @distributed_trace_async + async def get_operation_details(self, *, snapshot: str, **kwargs: Any) -> _models.OperationDetails: + """Gets the state of a long running operation. + + Gets the state of a long running operation. + + :keyword snapshot: Snapshot identifier for the long running operation. Required. + :paramtype snapshot: str + :return: OperationDetails. The OperationDetails is compatible with MutableMapping + :rtype: ~azure.appconfiguration.models.OperationDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) + + _request = build_azure_app_configuration_get_operation_details_request( + snapshot=snapshot, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.OperationDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + async def _create_snapshot_initial( - self, name: str, entity: Union[_models.Snapshot, IO[bytes]], **kwargs: Any + self, + name: str, + entity: Union[_models.Snapshot, JSON, IO[bytes]], + *, + sync_token: Optional[str] = None, + **kwargs: Any ) -> AsyncIterator[bytes]: - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1170,26 +1336,23 @@ async def _create_snapshot_initial( error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" - _json = None _content = None if isinstance(entity, (IOBase, bytes)): _content = entity else: - _json = self._serialize.body(entity, "Snapshot") + _content = json.dumps(entity, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_create_snapshot_request( + _request = build_azure_app_configuration_create_snapshot_request( name=name, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, content_type=content_type, - json=_json, + api_version=self._config.api_version, content=_content, headers=_headers, params=_params, @@ -1199,7 +1362,6 @@ async def _create_snapshot_initial( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs @@ -1213,7 +1375,7 @@ async def _create_snapshot_initial( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1221,8 +1383,9 @@ async def _create_snapshot_initial( response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) response_headers["Link"] = self._deserialize("str", response.headers.get("Link")) response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + deserialized = response.iter_bytes() if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -1231,7 +1394,7 @@ async def _create_snapshot_initial( @overload async def begin_create_snapshot( - self, name: str, entity: _models.Snapshot, *, content_type: str = "application/json", **kwargs: Any + self, name: str, entity: _models.Snapshot, *, content_type: str, sync_token: Optional[str] = None, **kwargs: Any ) -> AsyncLROPoller[_models.Snapshot]: """Creates a key-value snapshot. @@ -1242,17 +1405,44 @@ async def begin_create_snapshot( :param entity: The key-value snapshot to create. Required. :type entity: ~azure.appconfiguration.models.Snapshot :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". + Required. + :paramtype content_type: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :return: An instance of AsyncLROPoller that returns Snapshot. The Snapshot is compatible with + MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.appconfiguration.models.Snapshot] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_snapshot( + self, name: str, entity: JSON, *, content_type: str, sync_token: Optional[str] = None, **kwargs: Any + ) -> AsyncLROPoller[_models.Snapshot]: + """Creates a key-value snapshot. + + Creates a key-value snapshot. + + :param name: The name of the key-value snapshot to create. Required. + :type name: str + :param entity: The key-value snapshot to create. Required. + :type entity: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Required. :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either Snapshot or the result of - cls(response) + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :return: An instance of AsyncLROPoller that returns Snapshot. The Snapshot is compatible with + MutableMapping :rtype: ~azure.core.polling.AsyncLROPoller[~azure.appconfiguration.models.Snapshot] :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def begin_create_snapshot( - self, name: str, entity: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + self, name: str, entity: IO[bytes], *, content_type: str, sync_token: Optional[str] = None, **kwargs: Any ) -> AsyncLROPoller[_models.Snapshot]: """Creates a key-value snapshot. @@ -1263,18 +1453,26 @@ async def begin_create_snapshot( :param entity: The key-value snapshot to create. Required. :type entity: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Known values are: 'application/json', 'application/vnd.microsoft.appconfig.snapshot+json'. - Default value is "application/json". + Known values are: 'application/vnd.microsoft.appconfig.snapshot+json', 'application/json'. + Required. :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either Snapshot or the result of - cls(response) + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :return: An instance of AsyncLROPoller that returns Snapshot. The Snapshot is compatible with + MutableMapping :rtype: ~azure.core.polling.AsyncLROPoller[~azure.appconfiguration.models.Snapshot] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def begin_create_snapshot( - self, name: str, entity: Union[_models.Snapshot, IO[bytes]], **kwargs: Any + self, + name: str, + entity: Union[_models.Snapshot, JSON, IO[bytes]], + *, + sync_token: Optional[str] = None, + **kwargs: Any ) -> AsyncLROPoller[_models.Snapshot]: """Creates a key-value snapshot. @@ -1282,18 +1480,20 @@ async def begin_create_snapshot( :param name: The name of the key-value snapshot to create. Required. :type name: str - :param entity: The key-value snapshot to create. Is either a Snapshot type or a IO[bytes] type. - Required. - :type entity: ~azure.appconfiguration.models.Snapshot or IO[bytes] - :return: An instance of AsyncLROPoller that returns either Snapshot or the result of - cls(response) + :param entity: The key-value snapshot to create. Is one of the following types: Snapshot, JSON, + IO[bytes] Required. + :type entity: ~azure.appconfiguration.models.Snapshot or JSON or IO[bytes] + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :return: An instance of AsyncLROPoller that returns Snapshot. The Snapshot is compatible with + MutableMapping :rtype: ~azure.core.polling.AsyncLROPoller[~azure.appconfiguration.models.Snapshot] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Snapshot] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -1303,7 +1503,7 @@ async def begin_create_snapshot( raw_result = await self._create_snapshot_initial( name=name, entity=entity, - api_version=api_version, + sync_token=sync_token, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, @@ -1322,8 +1522,9 @@ def get_long_running_output(pipeline_response): response_headers["Operation-Location"] = self._deserialize( "str", response.headers.get("Operation-Location") ) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("Snapshot", pipeline_response.http_response) + deserialized = _deserialize(_models.Snapshot, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized @@ -1353,79 +1554,51 @@ def get_long_running_output(pipeline_response): ) @overload - async def update_snapshot( + async def _update_snapshot( self, name: str, - entity: _models.SnapshotUpdateParameters, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, + entity: _models._models.SnapshotUpdateParameters, *, - content_type: str = "application/json", + content_type: str, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models.Snapshot: - """Updates the state of a key-value snapshot. - - Updates the state of a key-value snapshot. - - :param name: The name of the key-value snapshot to update. Required. - :type name: str - :param entity: The parameters used to update the snapshot. Required. - :type entity: ~azure.appconfiguration.models.SnapshotUpdateParameters - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Snapshot or the result of cls(response) - :rtype: ~azure.appconfiguration.models.Snapshot - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models.Snapshot: ... + @overload + async def _update_snapshot( + self, + name: str, + entity: JSON, + *, + content_type: str, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> _models.Snapshot: ... @overload - async def update_snapshot( + async def _update_snapshot( self, name: str, entity: IO[bytes], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, *, - content_type: str = "application/json", + content_type: str, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models.Snapshot: - """Updates the state of a key-value snapshot. - - Updates the state of a key-value snapshot. - - :param name: The name of the key-value snapshot to update. Required. - :type name: str - :param entity: The parameters used to update the snapshot. Required. - :type entity: IO[bytes] - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Known values are: 'application/json', 'application/merge-patch+json'. Default value is - "application/json". - :paramtype content_type: str - :return: Snapshot or the result of cls(response) - :rtype: ~azure.appconfiguration.models.Snapshot - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> _models.Snapshot: ... @distributed_trace_async - async def update_snapshot( + async def _update_snapshot( self, name: str, - entity: Union[_models.SnapshotUpdateParameters, IO[bytes]], - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, + entity: Union[_models._models.SnapshotUpdateParameters, JSON, IO[bytes]], + *, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.Snapshot: """Updates the state of a key-value snapshot. @@ -1434,50 +1607,56 @@ async def update_snapshot( :param name: The name of the key-value snapshot to update. Required. :type name: str - :param entity: The parameters used to update the snapshot. Is either a SnapshotUpdateParameters - type or a IO[bytes] type. Required. - :type entity: ~azure.appconfiguration.models.SnapshotUpdateParameters or IO[bytes] - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :return: Snapshot or the result of cls(response) + :param entity: The parameters used to update the snapshot. Is one of the following types: + SnapshotUpdateParameters, JSON, IO[bytes] Required. + :type entity: ~azure.appconfiguration.models._models.SnapshotUpdateParameters or JSON or + IO[bytes] + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: Snapshot. The Snapshot is compatible with MutableMapping :rtype: ~azure.appconfiguration.models.Snapshot :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Snapshot] = kwargs.pop("cls", None) content_type = content_type or "application/json" - _json = None _content = None if isinstance(entity, (IOBase, bytes)): _content = entity else: - _json = self._serialize.body(entity, "SnapshotUpdateParameters") + _content = json.dumps(entity, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_update_snapshot_request( + _request = build_azure_app_configuration_update_snapshot_request( name=name, - if_match=if_match, - if_none_match=if_none_match, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + etag=etag, + match_condition=match_condition, content_type=content_type, - json=_json, + api_version=self._config.api_version, content=_content, headers=_headers, params=_params, @@ -1487,7 +1666,7 @@ async def update_snapshot( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1495,16 +1674,25 @@ async def update_snapshot( response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) response_headers["Link"] = self._deserialize("str", response.headers.get("Link")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("Snapshot", pipeline_response.http_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.Snapshot, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -1512,45 +1700,58 @@ async def update_snapshot( return deserialized # type: ignore @distributed_trace_async - async def check_snapshot( # pylint: disable=inconsistent-return-statements - self, name: str, if_match: Optional[str] = None, if_none_match: Optional[str] = None, **kwargs: Any - ) -> None: + async def check_snapshot( + self, + name: str, + *, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, + **kwargs: Any + ) -> bool: """Requests the headers and status of the given resource. Requests the headers and status of the given resource. :param name: The name of the key-value snapshot to check. Required. :type name: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :return: None or the result of cls(response) - :rtype: None + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_check_snapshot_request( + _request = build_azure_app_configuration_check_snapshot_request( name=name, - if_match=if_match, - if_none_match=if_none_match, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1568,7 +1769,8 @@ async def check_snapshot( # pylint: disable=inconsistent-return-statements if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) @@ -1577,11 +1779,14 @@ async def check_snapshot( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace def get_labels( self, + *, name: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.LabelFields]]] = None, @@ -1591,28 +1796,31 @@ def get_labels( Gets a list of labels. - :param name: A filter for the name of the returned labels. Default value is None. - :type name: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param select: Used to select what fields are present in the returned resource(s). Default + :keyword name: A filter for the name of the returned labels. Default value is None. + :paramtype name: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.LabelFields] - :return: An iterator like instance of either Label or the result of cls(response) + :paramtype select: list[str or ~azure.appconfiguration.models.LabelFields] + :return: An iterator like instance of Label :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.appconfiguration.models.Label] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.LabelListResult] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Label]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1623,13 +1831,13 @@ def get_labels( def prepare_request(next_link=None): if not next_link: - _request = build_get_labels_request( + _request = build_azure_app_configuration_get_labels_request( name=name, + sync_token=sync_token, after=after, accept_datetime=accept_datetime, select=select, - sync_token=self._config.sync_token, - api_version=api_version, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1659,15 +1867,15 @@ def prepare_request(next_link=None): ), } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" + return _request async def extract_data(pipeline_response): - deserialized = self._deserialize("LabelListResult", pipeline_response) - list_of_elem = deserialized.items + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.Label], deserialized["items"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) + return deserialized.get("@nextLink") or None, AsyncList(list_of_elem) async def get_next(next_link=None): _request = prepare_request(next_link) @@ -1680,7 +1888,7 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -1688,34 +1896,40 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def check_labels( # pylint: disable=inconsistent-return-statements + async def check_labels( self, + *, name: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.LabelFields]]] = None, **kwargs: Any - ) -> None: + ) -> bool: """Requests the headers and status of the given resource. Requests the headers and status of the given resource. - :param name: A filter for the name of the returned labels. Default value is None. - :type name: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param select: Used to select what fields are present in the returned resource(s). Default + :keyword name: A filter for the name of the returned labels. Default value is None. + :paramtype name: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.LabelFields] - :return: None or the result of cls(response) - :rtype: None + :paramtype select: list[str or ~azure.appconfiguration.models.LabelFields] + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1724,18 +1938,17 @@ async def check_labels( # pylint: disable=inconsistent-return-statements error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_check_labels_request( + _request = build_azure_app_configuration_check_labels_request( name=name, + sync_token=sync_token, after=after, accept_datetime=accept_datetime, select=select, - sync_token=self._config.sync_token, - api_version=api_version, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1753,21 +1966,25 @@ async def check_labels( # pylint: disable=inconsistent-return-statements if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) if cls: return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace_async async def put_lock( self, key: str, + *, label: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.KeyValue: """Locks a key-value. @@ -1776,39 +1993,46 @@ async def put_lock( :param key: The key of the key-value to lock. Required. :type key: str - :param label: The label, if any, of the key-value to lock. Default value is None. - :type label: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :return: KeyValue or the result of cls(response) + :keyword label: The label, if any, of the key-value to lock. Default value is None. + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KeyValue. The KeyValue is compatible with MutableMapping :rtype: ~azure.appconfiguration.models.KeyValue :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.KeyValue] = kwargs.pop("cls", None) - _request = build_put_lock_request( + _request = build_azure_app_configuration_put_lock_request( key=key, label=label, - if_match=if_match, - if_none_match=if_none_match, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1817,7 +2041,7 @@ async def put_lock( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1825,15 +2049,24 @@ async def put_lock( response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("KeyValue", pipeline_response.http_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.KeyValue, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -1844,9 +2077,11 @@ async def put_lock( async def delete_lock( self, key: str, + *, label: Optional[str] = None, - if_match: Optional[str] = None, - if_none_match: Optional[str] = None, + sync_token: Optional[str] = None, + etag: Optional[str] = None, + match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.KeyValue: """Unlocks a key-value. @@ -1855,39 +2090,46 @@ async def delete_lock( :param key: The key of the key-value to unlock. Required. :type key: str - :param label: The label, if any, of the key-value to unlock. Default value is None. - :type label: str - :param if_match: Used to perform an operation only if the targeted resource's etag matches the - value provided. Default value is None. - :type if_match: str - :param if_none_match: Used to perform an operation only if the targeted resource's etag does - not match the value provided. Default value is None. - :type if_none_match: str - :return: KeyValue or the result of cls(response) + :keyword label: The label, if any, of the key-value to unlock. Default value is None. + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is + None. + :paramtype etag: str + :keyword match_condition: The match condition to use upon the etag. Default value is None. + :paramtype match_condition: ~azure.core.MatchConditions + :return: KeyValue. The KeyValue is compatible with MutableMapping :rtype: ~azure.appconfiguration.models.KeyValue :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } + if match_condition == MatchConditions.IfNotModified: + error_map[412] = ResourceModifiedError + elif match_condition == MatchConditions.IfPresent: + error_map[412] = ResourceNotFoundError + elif match_condition == MatchConditions.IfMissing: + error_map[412] = ResourceExistsError error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.KeyValue] = kwargs.pop("cls", None) - _request = build_delete_lock_request( + _request = build_azure_app_configuration_delete_lock_request( key=key, label=label, - if_match=if_match, - if_none_match=if_none_match, - sync_token=self._config.sync_token, - api_version=api_version, + sync_token=sync_token, + etag=etag, + match_condition=match_condition, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -1896,7 +2138,7 @@ async def delete_lock( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1904,15 +2146,24 @@ async def delete_lock( response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - deserialized = self._deserialize("KeyValue", pipeline_response.http_response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.KeyValue, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -1922,8 +2173,10 @@ async def delete_lock( @distributed_trace def get_revisions( self, + *, key: Optional[str] = None, label: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, @@ -1934,35 +2187,38 @@ def get_revisions( Gets a list of key-value revisions. - :param key: A filter used to match keys. Syntax reference: + :keyword key: A filter used to match keys. Syntax reference: https://aka.ms/azconfig/docs/restapirevisions. Default value is None. - :type key: str - :param label: A filter used to match labels. Syntax reference: + :paramtype key: str + :keyword label: A filter used to match labels. Syntax reference: https://aka.ms/azconfig/docs/restapirevisions. Default value is None. - :type label: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param select: Used to select what fields are present in the returned resource(s). Default + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] - :param tags: A filter used to query by tags. Syntax reference: + :paramtype select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] + :keyword tags: A filter used to query by tags. Syntax reference: https://aka.ms/azconfig/docs/restapirevisions. Default value is None. - :type tags: list[str] - :return: An iterator like instance of either KeyValue or the result of cls(response) + :paramtype tags: list[str] + :return: An iterator like instance of KeyValue :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.appconfiguration.models.KeyValue] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.KeyValueListResult] = kwargs.pop("cls", None) + cls: ClsType[List[_models.KeyValue]] = kwargs.pop("cls", None) - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1973,15 +2229,15 @@ def get_revisions( def prepare_request(next_link=None): if not next_link: - _request = build_get_revisions_request( + _request = build_azure_app_configuration_get_revisions_request( key=key, label=label, + sync_token=sync_token, after=after, accept_datetime=accept_datetime, select=select, tags=tags, - sync_token=self._config.sync_token, - api_version=api_version, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -2011,15 +2267,15 @@ def prepare_request(next_link=None): ), } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request.method = "GET" + return _request async def extract_data(pipeline_response): - deserialized = self._deserialize("KeyValueListResult", pipeline_response) - list_of_elem = deserialized.items + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.KeyValue], deserialized["items"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) + return deserialized.get("@nextLink") or None, AsyncList(list_of_elem) async def get_next(next_link=None): _request = prepare_request(next_link) @@ -2032,7 +2288,7 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + error = _deserialize(_models.Error, response.json()) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -2040,43 +2296,49 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def check_revisions( # pylint: disable=inconsistent-return-statements + async def check_revisions( self, + *, key: Optional[str] = None, label: Optional[str] = None, + sync_token: Optional[str] = None, after: Optional[str] = None, accept_datetime: Optional[str] = None, select: Optional[List[Union[str, _models.ConfigurationSettingFields]]] = None, tags: Optional[List[str]] = None, **kwargs: Any - ) -> None: + ) -> bool: """Requests the headers and status of the given resource. Requests the headers and status of the given resource. - :param key: A filter used to match keys. Syntax reference: + :keyword key: A filter used to match keys. Syntax reference: https://aka.ms/azconfig/docs/restapirevisions. Default value is None. - :type key: str - :param label: A filter used to match labels. Syntax reference: + :paramtype key: str + :keyword label: A filter used to match labels. Syntax reference: https://aka.ms/azconfig/docs/restapirevisions. Default value is None. - :type label: str - :param after: Instructs the server to return elements that appear after the element referred to - by the specified token. Default value is None. - :type after: str - :param accept_datetime: Requests the server to respond with the state of the resource at the - specified time. Default value is None. - :type accept_datetime: str - :param select: Used to select what fields are present in the returned resource(s). Default + :paramtype label: str + :keyword sync_token: Used to guarantee real-time consistency between requests. Default value is + None. + :paramtype sync_token: str + :keyword after: Instructs the server to return elements that appear after the element referred + to by the specified token. Default value is None. + :paramtype after: str + :keyword accept_datetime: Requests the server to respond with the state of the resource at the + specified + time. Default value is None. + :paramtype accept_datetime: str + :keyword select: Used to select what fields are present in the returned resource(s). Default value is None. - :type select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] - :param tags: A filter used to query by tags. Syntax reference: + :paramtype select: list[str or ~azure.appconfiguration.models.ConfigurationSettingFields] + :keyword tags: A filter used to query by tags. Syntax reference: https://aka.ms/azconfig/docs/restapirevisions. Default value is None. - :type tags: list[str] - :return: None or the result of cls(response) - :rtype: None + :paramtype tags: list[str] + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2085,20 +2347,19 @@ async def check_revisions( # pylint: disable=inconsistent-return-statements error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_check_revisions_request( + _request = build_azure_app_configuration_check_revisions_request( key=key, label=label, + sync_token=sync_token, after=after, accept_datetime=accept_datetime, select=select, tags=tags, - sync_token=self._config.sync_token, - api_version=api_version, + api_version=self._config.api_version, headers=_headers, params=_params, ) @@ -2116,7 +2377,8 @@ async def check_revisions( # pylint: disable=inconsistent-return-statements if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _deserialize(_models.Error, response.json()) + raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["Sync-Token"] = self._deserialize("str", response.headers.get("Sync-Token")) @@ -2124,59 +2386,4 @@ async def check_revisions( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def get_operation_details(self, snapshot: str, **kwargs: Any) -> _models.OperationDetails: - """Gets the state of a long running operation. - - Gets the state of a long running operation. - - :param snapshot: Snapshot identifier for the long running operation. Required. - :type snapshot: str - :return: OperationDetails or the result of cls(response) - :rtype: ~azure.appconfiguration.models.OperationDetails - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationDetails] = kwargs.pop("cls", None) - - _request = build_get_operation_details_request( - snapshot=snapshot, - api_version=api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize("OperationDetails", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + return 200 <= response.status_code <= 299 diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_operations/_patch.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_patch.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_sync_token_async.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_sync_token_async.py deleted file mode 100644 index 5bf387ac7598..000000000000 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_sync_token_async.py +++ /dev/null @@ -1,91 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from typing import Any, Dict, Optional -from asyncio import Lock -from azure.core.pipeline import PipelineRequest, PipelineResponse -from azure.core.pipeline.policies import SansIOHTTPPolicy - -from .._sync_token import SyncToken - - -class AsyncSyncTokenPolicy(SansIOHTTPPolicy): - """A simple policy that enable the given callback with the response. - - :keyword callback raw_response_hook: Callback function. Will be invoked on response. - """ - - def __init__(self, **kwargs: Any) -> None: # pylint: disable=unused-argument - self._sync_token_header = "Sync-Token" - self._sync_tokens: Dict[str, Any] = {} - self._lock = Lock() - - async def on_request(self, request: PipelineRequest) -> None: # pylint: disable=invalid-overridden-method - """This is executed before sending the request to the next policy. - - :param request: The PipelineRequest object. - :type request: ~azure.core.pipeline.PipelineRequest - """ - async with self._lock: - sync_token_header = ",".join(str(x) for x in self._sync_tokens.values()) - if sync_token_header: - request.http_request.headers.update({self._sync_token_header: sync_token_header}) - - async def on_response( # pylint: disable=invalid-overridden-method - self, request: PipelineRequest, response: PipelineResponse - ) -> None: - """This is executed after the request comes back from the policy. - - :param request: The PipelineRequest object. - :type request: ~azure.core.pipeline.PipelineRequest - :param response: The PipelineResponse object. - :type response: ~azure.core.pipeline.PipelineResponse - """ - sync_token_header = response.http_response.headers.get(self._sync_token_header) - if not sync_token_header: - return - sync_token_strings = sync_token_header.split(",") - if not sync_token_strings: - return - for sync_token_string in sync_token_strings: - sync_token = SyncToken.from_sync_token_string(sync_token_string) - await self._update_sync_token(sync_token) - - async def add_token(self, full_raw_tokens: str) -> None: - raw_tokens = full_raw_tokens.split(",") - for raw_token in raw_tokens: - sync_token = SyncToken.from_sync_token_string(raw_token) - await self._update_sync_token(sync_token) - - async def _update_sync_token(self, sync_token: Optional[SyncToken]) -> None: - if not sync_token: - return - async with self._lock: - existing_token = self._sync_tokens.get(sync_token.token_id, None) - if not existing_token: - self._sync_tokens[sync_token.token_id] = sync_token - return - if existing_token.sequence_number < sync_token.sequence_number: - self._sync_tokens[sync_token.token_id] = sync_token diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_vendor.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_vendor.py new file mode 100644 index 000000000000..7ad457cb022b --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/aio/_vendor.py @@ -0,0 +1,57 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import Optional, TYPE_CHECKING + +from azure.core import MatchConditions + +from ._configuration import AzureAppConfigurationClientConfiguration + +if TYPE_CHECKING: + from azure.core import AsyncPipelineClient + + from .._serialization import Deserializer, Serializer + + +class AzureAppConfigurationClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "AsyncPipelineClient" + _config: AzureAppConfigurationClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" + + +def quote_etag(etag: Optional[str]) -> Optional[str]: + if not etag or etag == "*": + return etag + if etag.startswith("W/"): + return etag + if etag.startswith('"') and etag.endswith('"'): + return etag + if etag.startswith("'") and etag.endswith("'"): + return etag + return '"' + etag + '"' + + +def prep_if_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfNotModified: + if_match = quote_etag(etag) if etag else None + return if_match + if match_condition == MatchConditions.IfPresent: + return "*" + return None + + +def prep_if_none_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: + if match_condition == MatchConditions.IfModified: + if_none_match = quote_etag(etag) if etag else None + return if_none_match + if match_condition == MatchConditions.IfMissing: + return "*" + return None diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/models/__init__.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/models/__init__.py new file mode 100644 index 000000000000..fb2389220f29 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/models/__init__.py @@ -0,0 +1,54 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + Error, + Key, + KeyValue, + KeyValueFilter, + Label, + OperationDetails, + Snapshot, +) + +from ._enums import ( # type: ignore + ConfigurationSettingFields, + LabelFields, + OperationState, + SnapshotComposition, + SnapshotFields, + SnapshotStatus, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Error", + "Key", + "KeyValue", + "KeyValueFilter", + "Label", + "OperationDetails", + "Snapshot", + "ConfigurationSettingFields", + "LabelFields", + "OperationState", + "SnapshotComposition", + "SnapshotFields", + "SnapshotStatus", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/models/_azure_app_configuration_enums.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/models/_enums.py similarity index 57% rename from sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/models/_azure_app_configuration_enums.py rename to sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/models/_enums.py index 8a1f283b8bf5..f96f5dadd444 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/_generated/models/_azure_app_configuration_enums.py +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/models/_enums.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -11,64 +11,92 @@ class ConfigurationSettingFields(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """ConfigurationSettingFields.""" + """Key-value fields.""" KEY = "key" + """Key field.""" LABEL = "label" + """Label field.""" CONTENT_TYPE = "content_type" + """Content type field.""" VALUE = "value" + """Value field.""" LAST_MODIFIED = "last_modified" + """Last modified field.""" TAGS = "tags" + """Tags field.""" LOCKED = "locked" + """Locked field.""" ETAG = "etag" + """Etag field.""" class LabelFields(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """LabelFields.""" + """Label fields.""" NAME = "name" + """Name field.""" + + +class OperationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum describing allowed operation states.""" + + NOT_STARTED = "NotStarted" + """The operation has not started.""" + RUNNING = "Running" + """The operation is in progress.""" + SUCCEEDED = "Succeeded" + """The operation has completed successfully.""" + FAILED = "Failed" + """The operation has failed.""" + CANCELED = "Canceled" + """The operation has been canceled by the user.""" class SnapshotComposition(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The composition type describes how the key-values within the snapshot are composed. The 'key' - composition type ensures there are no two key-values containing the same key. The 'key_label' - composition type ensures there are no two key-values containing the same key and label. - """ + """Composition types.""" KEY = "key" + """The 'key' composition type.""" KEY_LABEL = "key_label" + """The 'key_label' composition type.""" class SnapshotFields(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """SnapshotFields.""" + """Snapshot fields.""" NAME = "name" + """Name field.""" STATUS = "status" + """Status field.""" FILTERS = "filters" + """Filters field.""" COMPOSITION_TYPE = "composition_type" + """Composition type field.""" CREATED = "created" + """Created field.""" EXPIRES = "expires" + """Expires field.""" RETENTION_PERIOD = "retention_period" + """Retention period field.""" SIZE = "size" + """Size field.""" ITEMS_COUNT = "items_count" + """Items count field.""" TAGS = "tags" + """Tags field.""" ETAG = "etag" + """Etag field.""" class SnapshotStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The current status of the snapshot.""" + """Snapshot status.""" PROVISIONING = "provisioning" + """Provisioning""" READY = "ready" + """Ready""" ARCHIVED = "archived" + """Archived""" FAILED = "failed" - - -class State(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The current status of the operation.""" - - NOT_STARTED = "NotStarted" - RUNNING = "Running" - SUCCEEDED = "Succeeded" - FAILED = "Failed" - CANCELED = "Canceled" + """Failed""" diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/models/_models.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/models/_models.py new file mode 100644 index 000000000000..5fa31326bbc8 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/models/_models.py @@ -0,0 +1,362 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation + +import datetime +from typing import Any, Dict, List, Mapping, Optional, TYPE_CHECKING, Union, overload + +from azure.core.exceptions import ODataV4Format + +from .. import _model_base +from .._model_base import rest_field + +if TYPE_CHECKING: + from .. import models as _models + + +class Error(_model_base.Model): + """Azure App Configuration error object. + + :ivar type: The type of the error. + :vartype type: str + :ivar title: A brief summary of the error. + :vartype title: str + :ivar name: The name of the parameter that resulted in the error. + :vartype name: str + :ivar detail: A detailed description of the error. + :vartype detail: str + :ivar status: The HTTP status code that the error maps to. + :vartype status: int + """ + + type: Optional[str] = rest_field() + """The type of the error.""" + title: Optional[str] = rest_field() + """A brief summary of the error.""" + name: Optional[str] = rest_field() + """The name of the parameter that resulted in the error.""" + detail: Optional[str] = rest_field() + """A detailed description of the error.""" + status: Optional[int] = rest_field() + """The HTTP status code that the error maps to.""" + + @overload + def __init__( + self, + *, + type: Optional[str] = None, + title: Optional[str] = None, + name: Optional[str] = None, + detail: Optional[str] = None, + status: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Key(_model_base.Model): + """Keys serve as identifiers for key-values and are used to store and retrieve corresponding + values. + + Readonly variables are only populated by the server, and will be ignored when sending a request. + + + :ivar name: The name of the key. Required. + :vartype name: str + """ + + name: str = rest_field(visibility=["read"]) + """The name of the key. Required.""" + + +class KeyValue(_model_base.Model): + """A key-value pair representing application settings. + + Readonly variables are only populated by the server, and will be ignored when sending a request. + + + :ivar key: The key of the key-value. Required. + :vartype key: str + :ivar label: The label the key-value belongs to. + :vartype label: str + :ivar content_type: The content type of the value stored within the key-value. + :vartype content_type: str + :ivar value: The value of the key-value. + :vartype value: str + :ivar last_modified: A date representing the last time the key-value was modified. + :vartype last_modified: ~datetime.datetime + :ivar tags: The tags of the key-value. + :vartype tags: dict[str, str] + :ivar locked: Indicates whether the key-value is locked. + :vartype locked: bool + :ivar etag: A value representing the current state of the resource. + :vartype etag: str + """ + + key: str = rest_field(visibility=["read"]) + """The key of the key-value. Required.""" + label: Optional[str] = rest_field() + """The label the key-value belongs to.""" + content_type: Optional[str] = rest_field() + """The content type of the value stored within the key-value.""" + value: Optional[str] = rest_field() + """The value of the key-value.""" + last_modified: Optional[datetime.datetime] = rest_field(format="rfc3339") + """A date representing the last time the key-value was modified.""" + tags: Optional[Dict[str, str]] = rest_field() + """The tags of the key-value.""" + locked: Optional[bool] = rest_field() + """Indicates whether the key-value is locked.""" + etag: Optional[str] = rest_field() + """A value representing the current state of the resource.""" + + @overload + def __init__( + self, + *, + label: Optional[str] = None, + content_type: Optional[str] = None, + value: Optional[str] = None, + last_modified: Optional[datetime.datetime] = None, + tags: Optional[Dict[str, str]] = None, + locked: Optional[bool] = None, + etag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KeyValueFilter(_model_base.Model): + """Enables filtering of key-values. Syntax reference: + https://aka.ms/azconfig/docs/restapisnapshots. + + + :ivar key: Filters key-values by their key field. Required. + :vartype key: str + :ivar label: Filters key-values by their label field. + :vartype label: str + :ivar tags: Filters key-values by their tags field. + :vartype tags: list[str] + """ + + key: str = rest_field() + """Filters key-values by their key field. Required.""" + label: Optional[str] = rest_field() + """Filters key-values by their label field.""" + tags: Optional[List[str]] = rest_field() + """Filters key-values by their tags field.""" + + @overload + def __init__( + self, + *, + key: str, + label: Optional[str] = None, + tags: Optional[List[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Label(_model_base.Model): + """Labels are used to group key-values. + + :ivar name: The name of the label. + :vartype name: str + """ + + name: Optional[str] = rest_field() + """The name of the label.""" + + @overload + def __init__( + self, + *, + name: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class OperationDetails(_model_base.Model): + """Details of a long running operation. + + + :ivar id: The unique id of the operation. Required. + :vartype id: str + :ivar status: The current status of the operation. Required. Known values are: "NotStarted", + "Running", "Succeeded", "Failed", and "Canceled". + :vartype status: str or ~azure.appconfiguration.models.OperationState + :ivar error: An error, available when the status is ``Failed``\\ , describing why the operation + failed. + :vartype error: ~azure.core.ODataV4Format + """ + + id: str = rest_field() + """The unique id of the operation. Required.""" + status: Union[str, "_models.OperationState"] = rest_field() + """The current status of the operation. Required. Known values are: \"NotStarted\", \"Running\", + \"Succeeded\", \"Failed\", and \"Canceled\".""" + error: Optional[ODataV4Format] = rest_field() + """An error, available when the status is ``Failed``\ , describing why the operation + failed.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + status: Union[str, "_models.OperationState"], + error: Optional[ODataV4Format] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Snapshot(_model_base.Model): + """A snapshot is a named, immutable subset of an App Configuration store's key-values. + + Readonly variables are only populated by the server, and will be ignored when sending a request. + + + :ivar name: The name of the snapshot. Required. + :vartype name: str + :ivar status: The current status of the snapshot. Known values are: "provisioning", "ready", + "archived", and "failed". + :vartype status: str or ~azure.appconfiguration.models.SnapshotStatus + :ivar filters: A list of filters used to filter the key-values included in the snapshot. + Required. + :vartype filters: list[~azure.appconfiguration.models.KeyValueFilter] + :ivar composition_type: The composition type describes how the key-values within the snapshot + are + composed. The 'key' composition type ensures there are no two key-values + containing the same key. The 'key_label' composition type ensures there are no + two key-values containing the same key and label. Known values are: "key" and "key_label". + :vartype composition_type: str or ~azure.appconfiguration.models.SnapshotComposition + :ivar created: The time that the snapshot was created. + :vartype created: ~datetime.datetime + :ivar expires: The time that the snapshot will expire. + :vartype expires: ~datetime.datetime + :ivar retention_period: The amount of time, in seconds, that a snapshot will remain in the + archived + state before expiring. This property is only writable during the creation of a + snapshot. If not specified, the default lifetime of key-value revisions will be + used. + :vartype retention_period: int + :ivar size: The size in bytes of the snapshot. + :vartype size: int + :ivar items_count: The amount of key-values in the snapshot. + :vartype items_count: int + :ivar tags: The tags of the snapshot. + :vartype tags: dict[str, str] + :ivar etag: A value representing the current state of the snapshot. + :vartype etag: str + """ + + name: str = rest_field(visibility=["read"]) + """The name of the snapshot. Required.""" + status: Optional[Union[str, "_models.SnapshotStatus"]] = rest_field(visibility=["read"]) + """The current status of the snapshot. Known values are: \"provisioning\", \"ready\", + \"archived\", and \"failed\".""" + filters: List["_models.KeyValueFilter"] = rest_field() + """A list of filters used to filter the key-values included in the snapshot. Required.""" + composition_type: Optional[Union[str, "_models.SnapshotComposition"]] = rest_field() + """The composition type describes how the key-values within the snapshot are + composed. The 'key' composition type ensures there are no two key-values + containing the same key. The 'key_label' composition type ensures there are no + two key-values containing the same key and label. Known values are: \"key\" and \"key_label\".""" + created: Optional[datetime.datetime] = rest_field(visibility=["read"], format="rfc3339") + """The time that the snapshot was created.""" + expires: Optional[datetime.datetime] = rest_field(visibility=["read"], format="rfc3339") + """The time that the snapshot will expire.""" + retention_period: Optional[int] = rest_field() + """The amount of time, in seconds, that a snapshot will remain in the archived + state before expiring. This property is only writable during the creation of a + snapshot. If not specified, the default lifetime of key-value revisions will be + used.""" + size: Optional[int] = rest_field(visibility=["read"]) + """The size in bytes of the snapshot.""" + items_count: Optional[int] = rest_field(visibility=["read"]) + """The amount of key-values in the snapshot.""" + tags: Optional[Dict[str, str]] = rest_field() + """The tags of the snapshot.""" + etag: Optional[str] = rest_field(visibility=["read"]) + """A value representing the current state of the snapshot.""" + + @overload + def __init__( + self, + *, + filters: List["_models.KeyValueFilter"], + composition_type: Optional[Union[str, "_models.SnapshotComposition"]] = None, + retention_period: Optional[int] = None, + tags: Optional[Dict[str, str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SnapshotUpdateParameters(_model_base.Model): + """Parameters used to update a snapshot. + + :ivar status: The desired status of the snapshot. Known values are: "provisioning", "ready", + "archived", and "failed". + :vartype status: str or ~azure.appconfiguration.models.SnapshotStatus + """ + + status: Optional[Union[str, "_models.SnapshotStatus"]] = rest_field() + """The desired status of the snapshot. Known values are: \"provisioning\", \"ready\", + \"archived\", and \"failed\".""" diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/models/_patch.py b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/py.typed b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/py.typed index e69de29bb2d1..e5aff4f83af8 100644 --- a/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/py.typed +++ b/sdk/appconfiguration/azure-appconfiguration/azure/appconfiguration/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_value.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_value.py new file mode 100644 index 000000000000..145636c9b96a --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_value.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python check_key_value.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.check_key_value( + key="Message", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/CheckKeyValue.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_value_if_match.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_value_if_match.py new file mode 100644 index 000000000000..5dc96035afed --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_value_if_match.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python check_key_value_if_match.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.check_key_value( + key="Message", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/CheckKeyValue_IfMatch.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_value_if_none_match.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_value_if_none_match.py new file mode 100644 index 000000000000..ae8db69ef5e8 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_value_if_none_match.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python check_key_value_if_none_match.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.check_key_value( + key="Message", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/CheckKeyValue_IfNoneMatch.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_values.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_values.py new file mode 100644 index 000000000000..ae17c88f5e18 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_values.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python check_key_values.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.check_key_values() + print(response) + + +# x-ms-original-file: 2023-11-01/CheckKeyValues.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_values_if_match.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_values_if_match.py new file mode 100644 index 000000000000..f0a36f5944c1 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_values_if_match.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python check_key_values_if_match.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.check_key_values() + print(response) + + +# x-ms-original-file: 2023-11-01/CheckKeyValues_IfMatch.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_values_if_none_match.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_values_if_none_match.py new file mode 100644 index 000000000000..cdb832e2c08b --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_key_values_if_none_match.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python check_key_values_if_none_match.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.check_key_values() + print(response) + + +# x-ms-original-file: 2023-11-01/CheckKeyValues_IfNoneMatch.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_keys.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_keys.py new file mode 100644 index 000000000000..29003383fa72 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_keys.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python check_keys.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.check_keys() + print(response) + + +# x-ms-original-file: 2023-11-01/CheckKeys.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_labels.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_labels.py new file mode 100644 index 000000000000..36d52038d6a9 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_labels.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python check_labels.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.check_labels() + print(response) + + +# x-ms-original-file: 2023-11-01/CheckLabels.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_revisions.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_revisions.py new file mode 100644 index 000000000000..be3887160b76 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_revisions.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python check_revisions.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.check_revisions() + print(response) + + +# x-ms-original-file: 2023-11-01/CheckRevisions.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_snapshot.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_snapshot.py new file mode 100644 index 000000000000..946bc0a61d07 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_snapshot.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python check_snapshot.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.check_snapshot( + name="Prod-2022-08-01", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/CheckSnapshot.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_snapshot_if_match.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_snapshot_if_match.py new file mode 100644 index 000000000000..45559d8f3ee9 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_snapshot_if_match.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python check_snapshot_if_match.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.check_snapshot( + name="Prod-2022-08-01", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/CheckSnapshot_IfMatch.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_snapshot_if_none_match.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_snapshot_if_none_match.py new file mode 100644 index 000000000000..b1d77b84db2e --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_snapshot_if_none_match.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python check_snapshot_if_none_match.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.check_snapshot( + name="Prod-2022-08-01", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/CheckSnapshot_IfNoneMatch.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_snapshots.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_snapshots.py new file mode 100644 index 000000000000..239bbd5fb9bd --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/check_snapshots.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python check_snapshots.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.check_snapshots() + print(response) + + +# x-ms-original-file: 2023-11-01/CheckSnapshots.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/create_snapshot.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/create_snapshot.py new file mode 100644 index 000000000000..8f0d970ba073 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/create_snapshot.py @@ -0,0 +1,34 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python create_snapshot.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.begin_create_snapshot( + name="Prod-2022-08-01", + entity={"filters": [{"key": "app1/*", "label": "Production"}], "retention_period": 3600}, + ).result() + print(response) + + +# x-ms-original-file: 2023-11-01/CreateSnapshot.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/delete_key_value.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/delete_key_value.py new file mode 100644 index 000000000000..2fd331990b21 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/delete_key_value.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python delete_key_value.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.delete_key_value( + key="Message", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/DeleteKeyValue.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/delete_key_value_if_match.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/delete_key_value_if_match.py new file mode 100644 index 000000000000..130008815f80 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/delete_key_value_if_match.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python delete_key_value_if_match.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.delete_key_value( + key="Message", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/DeleteKeyValue_IfMatch.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/delete_lock.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/delete_lock.py new file mode 100644 index 000000000000..0e04f06fa5ce --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/delete_lock.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python delete_lock.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.delete_lock( + key="Message", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/DeleteLock.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/delete_lock_if_match.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/delete_lock_if_match.py new file mode 100644 index 000000000000..3a186865d522 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/delete_lock_if_match.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python delete_lock_if_match.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.delete_lock( + key="Message", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/DeleteLock_IfMatch.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_value.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_value.py new file mode 100644 index 000000000000..a4db921bbb75 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_value.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python get_key_value.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.get_key_value( + key="Message", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/GetKeyValue.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_value_if_match.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_value_if_match.py new file mode 100644 index 000000000000..1d67d1b8d77c --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_value_if_match.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python get_key_value_if_match.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.get_key_value( + key="Message", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/GetKeyValue_IfMatch.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_value_if_none_match.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_value_if_none_match.py new file mode 100644 index 000000000000..fddbfdd55ce0 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_value_if_none_match.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python get_key_value_if_none_match.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.get_key_value( + key="Message", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/GetKeyValue_IfNoneMatch.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_values.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_values.py new file mode 100644 index 000000000000..7d82b6c03c24 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_values.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python get_key_values.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.get_key_values() + for item in response: + print(item) + + +# x-ms-original-file: 2023-11-01/GetKeyValues.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_values_if_match.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_values_if_match.py new file mode 100644 index 000000000000..d853bc905679 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_values_if_match.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python get_key_values_if_match.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.get_key_values() + for item in response: + print(item) + + +# x-ms-original-file: 2023-11-01/GetKeyValues_IfMatch.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_values_if_none_match.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_values_if_none_match.py new file mode 100644 index 000000000000..62fe7d97b386 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_key_values_if_none_match.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python get_key_values_if_none_match.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.get_key_values() + for item in response: + print(item) + + +# x-ms-original-file: 2023-11-01/GetKeyValues_IfNoneMatch.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_keys.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_keys.py new file mode 100644 index 000000000000..c3104084fb73 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_keys.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python get_keys.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.get_keys() + for item in response: + print(item) + + +# x-ms-original-file: 2023-11-01/GetKeys.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_labels.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_labels.py new file mode 100644 index 000000000000..0820f8a91bc5 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_labels.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python get_labels.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.get_labels() + for item in response: + print(item) + + +# x-ms-original-file: 2023-11-01/GetLabels.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_operation_status.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_operation_status.py new file mode 100644 index 000000000000..752297da4f48 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_operation_status.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python get_operation_status.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.get_operation_details( + snapshot="Prod-2022-08-01", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/GetOperationStatus.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_revisions.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_revisions.py new file mode 100644 index 000000000000..f9a8350f79a3 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_revisions.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python get_revisions.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.get_revisions() + for item in response: + print(item) + + +# x-ms-original-file: 2023-11-01/GetRevisions.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_snapshot.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_snapshot.py new file mode 100644 index 000000000000..165f683f9a9e --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_snapshot.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python get_snapshot.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.get_snapshot( + name="Prod-2022-08-01", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/GetSnapshot.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_snapshot_failed.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_snapshot_failed.py new file mode 100644 index 000000000000..f081cacb0148 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_snapshot_failed.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python get_snapshot_failed.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.get_snapshot( + name="Prod-2022-08-01", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/GetSnapshot_Failed.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_snapshot_if_match.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_snapshot_if_match.py new file mode 100644 index 000000000000..4e94dbf5ac41 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_snapshot_if_match.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python get_snapshot_if_match.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.get_snapshot( + name="Prod-2022-08-01", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/GetSnapshot_IfMatch.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_snapshot_if_none_match.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_snapshot_if_none_match.py new file mode 100644 index 000000000000..3444b06b2f89 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_snapshot_if_none_match.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python get_snapshot_if_none_match.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.get_snapshot( + name="Prod-2022-08-01", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/GetSnapshot_IfNoneMatch.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_snapshots.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_snapshots.py new file mode 100644 index 000000000000..d2db2465c1db --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/get_snapshots.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python get_snapshots.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.get_snapshots() + for item in response: + print(item) + + +# x-ms-original-file: 2023-11-01/GetSnapshots.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/put_lock.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/put_lock.py new file mode 100644 index 000000000000..7fc810e8a5ef --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/put_lock.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python put_lock.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.put_lock( + key="Message", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/PutLock.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_samples/put_lock_if_match.py b/sdk/appconfiguration/azure-appconfiguration/generated_samples/put_lock_if_match.py new file mode 100644 index 000000000000..2767cf4995f8 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_samples/put_lock_if_match.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.appconfiguration import AzureAppConfigurationClient + +""" +# PREREQUISITES + pip install azure-appconfiguration +# USAGE + python put_lock_if_match.py +""" + + +def main(): + client = AzureAppConfigurationClient( + endpoint="https://{exampleAppConfigurationName}.azconfig.io", + credential="CREDENTIAL", + ) + + response = client.put_lock( + key="Message", + ) + print(response) + + +# x-ms-original-file: 2023-11-01/PutLock_IfMatch.json +if __name__ == "__main__": + main() diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_tests/conftest.py b/sdk/appconfiguration/azure-appconfiguration/generated_tests/conftest.py new file mode 100644 index 000000000000..4a951d947504 --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_tests/conftest.py @@ -0,0 +1,45 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + azureappconfiguration_subscription_id = os.environ.get( + "AZUREAPPCONFIGURATION_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + azureappconfiguration_tenant_id = os.environ.get( + "AZUREAPPCONFIGURATION_TENANT_ID", "00000000-0000-0000-0000-000000000000" + ) + azureappconfiguration_client_id = os.environ.get( + "AZUREAPPCONFIGURATION_CLIENT_ID", "00000000-0000-0000-0000-000000000000" + ) + azureappconfiguration_client_secret = os.environ.get( + "AZUREAPPCONFIGURATION_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer( + regex=azureappconfiguration_subscription_id, value="00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer(regex=azureappconfiguration_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=azureappconfiguration_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=azureappconfiguration_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_tests/test_azure_app_configuration.py b/sdk/appconfiguration/azure-appconfiguration/generated_tests/test_azure_app_configuration.py new file mode 100644 index 000000000000..3729657ec88c --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_tests/test_azure_app_configuration.py @@ -0,0 +1,215 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import AzureAppConfigurationClientTestBase, AzureAppConfigurationPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureAppConfiguration(AzureAppConfigurationClientTestBase): + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_get_keys(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.get_keys() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_check_keys(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.check_keys() + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_get_key_values(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.get_key_values() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_check_key_values(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.check_key_values() + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_get_key_value(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.get_key_value( + key="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_delete_key_value(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.delete_key_value( + key="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_check_key_value(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.check_key_value( + key="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_get_snapshots(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.get_snapshots() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_check_snapshots(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.check_snapshots() + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_get_snapshot(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.get_snapshot( + name="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_get_operation_details(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.get_operation_details( + snapshot="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_begin_create_snapshot(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.begin_create_snapshot( + name="str", + entity={ + "filters": [{"key": "str", "label": "str", "tags": ["str"]}], + "name": "str", + "composition_type": "str", + "created": "2020-02-20 00:00:00", + "etag": "str", + "expires": "2020-02-20 00:00:00", + "items_count": 0, + "retention_period": 0, + "size": 0, + "status": "str", + "tags": {"str": "str"}, + }, + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_check_snapshot(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.check_snapshot( + name="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_get_labels(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.get_labels() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_check_labels(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.check_labels() + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_put_lock(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.put_lock( + key="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_delete_lock(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.delete_lock( + key="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_get_revisions(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.get_revisions() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy + def test_check_revisions(self, azureappconfiguration_endpoint): + client = self.create_client(endpoint=azureappconfiguration_endpoint) + response = client.check_revisions() + + # please add some check logic here by yourself + # ... diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_tests/test_azure_app_configuration_async.py b/sdk/appconfiguration/azure-appconfiguration/generated_tests/test_azure_app_configuration_async.py new file mode 100644 index 000000000000..02b33d04d03f --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_tests/test_azure_app_configuration_async.py @@ -0,0 +1,218 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import AzureAppConfigurationPreparer +from testpreparer_async import AzureAppConfigurationClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureAppConfigurationAsync(AzureAppConfigurationClientTestBaseAsync): + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_get_keys(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = client.get_keys() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_check_keys(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = await client.check_keys() + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_get_key_values(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = client.get_key_values() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_check_key_values(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = await client.check_key_values() + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_get_key_value(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = await client.get_key_value( + key="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_delete_key_value(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = await client.delete_key_value( + key="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_check_key_value(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = await client.check_key_value( + key="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_get_snapshots(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = client.get_snapshots() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_check_snapshots(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = await client.check_snapshots() + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_get_snapshot(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = await client.get_snapshot( + name="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_get_operation_details(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = await client.get_operation_details( + snapshot="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_begin_create_snapshot(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = await ( + await client.begin_create_snapshot( + name="str", + entity={ + "filters": [{"key": "str", "label": "str", "tags": ["str"]}], + "name": "str", + "composition_type": "str", + "created": "2020-02-20 00:00:00", + "etag": "str", + "expires": "2020-02-20 00:00:00", + "items_count": 0, + "retention_period": 0, + "size": 0, + "status": "str", + "tags": {"str": "str"}, + }, + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_check_snapshot(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = await client.check_snapshot( + name="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_get_labels(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = client.get_labels() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_check_labels(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = await client.check_labels() + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_put_lock(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = await client.put_lock( + key="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_delete_lock(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = await client.delete_lock( + key="str", + ) + + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_get_revisions(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = client.get_revisions() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @AzureAppConfigurationPreparer() + @recorded_by_proxy_async + async def test_check_revisions(self, azureappconfiguration_endpoint): + client = self.create_async_client(endpoint=azureappconfiguration_endpoint) + response = await client.check_revisions() + + # please add some check logic here by yourself + # ... diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_tests/testpreparer.py b/sdk/appconfiguration/azure-appconfiguration/generated_tests/testpreparer.py new file mode 100644 index 000000000000..96540c3f4d8e --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_tests/testpreparer.py @@ -0,0 +1,28 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from azure.appconfiguration import AzureAppConfigurationClient +from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer +import functools + + +class AzureAppConfigurationClientTestBase(AzureRecordedTestCase): + + def create_client(self, endpoint): + credential = self.get_credential(AzureAppConfigurationClient) + return self.create_client_from_credential( + AzureAppConfigurationClient, + credential=credential, + endpoint=endpoint, + ) + + +AzureAppConfigurationPreparer = functools.partial( + PowerShellPreparer, + "azureappconfiguration", + azureappconfiguration_endpoint="https://fake_azureappconfiguration_endpoint.com", +) diff --git a/sdk/appconfiguration/azure-appconfiguration/generated_tests/testpreparer_async.py b/sdk/appconfiguration/azure-appconfiguration/generated_tests/testpreparer_async.py new file mode 100644 index 000000000000..71f0697b659c --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/generated_tests/testpreparer_async.py @@ -0,0 +1,20 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from azure.appconfiguration.aio import AzureAppConfigurationClient +from devtools_testutils import AzureRecordedTestCase + + +class AzureAppConfigurationClientTestBaseAsync(AzureRecordedTestCase): + + def create_async_client(self, endpoint): + credential = self.get_credential(AzureAppConfigurationClient, is_async=True) + return self.create_client_from_credential( + AzureAppConfigurationClient, + credential=credential, + endpoint=endpoint, + ) diff --git a/sdk/appconfiguration/azure-appconfiguration/setup.py b/sdk/appconfiguration/azure-appconfiguration/setup.py index f4a0bfb6dde7..e82ff93988d6 100644 --- a/sdk/appconfiguration/azure-appconfiguration/setup.py +++ b/sdk/appconfiguration/azure-appconfiguration/setup.py @@ -1,24 +1,22 @@ -#!/usr/bin/env python - -# ------------------------------------------------------------------------- +# coding=utf-8 +# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# coding: utf-8 +import os import re -import os.path -from io import open -from setuptools import find_packages, setup +from setuptools import setup, find_packages + -# Change the PACKAGE_NAME only to change folder and different name PACKAGE_NAME = "azure-appconfiguration" -PACKAGE_PPRINT_NAME = "App Configuration Data" +PACKAGE_PPRINT_NAME = "Azure Appconfiguration" # a-b-c => a/b/c package_folder_path = PACKAGE_NAME.replace("-", "/") -# a-b-c => a.b.c -namespace_name = PACKAGE_NAME.replace("-", ".") # Version extraction inspired from 'requests' with open(os.path.join(package_folder_path, "_version.py"), "r") as fd: @@ -27,33 +25,20 @@ if not version: raise RuntimeError("Cannot find version information") -with open("README.md", encoding="utf-8") as f: - readme = f.read() -with open("CHANGELOG.md", encoding="utf-8") as f: - changelog = f.read() - -exclude_packages = [ - "tests", - "tests.*", - "samples", - # Exclude packages that will be covered by PEP420 or nspkg - "azure", -] setup( name=PACKAGE_NAME, version=version, - include_package_data=True, - description="Microsoft {} Library for Python".format(PACKAGE_PPRINT_NAME), - long_description=readme + "\n\n" + changelog, + description="Microsoft {} Client Library for Python".format(PACKAGE_PPRINT_NAME), + long_description=open("README.md", "r").read(), long_description_content_type="text/markdown", license="MIT License", author="Microsoft Corporation", author_email="azpysdkhelp@microsoft.com", - url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/appconfiguration/azure-appconfiguration", + url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk", keywords="azure, azure sdk", classifiers=[ - "Development Status :: 5 - Production/Stable", + "Development Status :: 4 - Beta", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", @@ -65,10 +50,21 @@ "License :: OSI Approved :: MIT License", ], zip_safe=False, - packages=find_packages(exclude=exclude_packages), - python_requires=">=3.8", + packages=find_packages( + exclude=[ + "tests", + # Exclude packages that will be covered by PEP420 or nspkg + "azure", + ] + ), + include_package_data=True, + package_data={ + "azure.appconfiguration": ["py.typed"], + }, install_requires=[ - "azure-core>=1.28.0", - "isodate>=0.6.0", + "isodate>=0.6.1", + "azure-core>=1.30.0", + "typing-extensions>=4.6.0", ], + python_requires=">=3.8", ) diff --git a/sdk/appconfiguration/azure-appconfiguration/tests/test_azure_appconfiguration_client.py b/sdk/appconfiguration/azure-appconfiguration/tests/test_azure_appconfiguration_client.py index daeb1935e391..4791831525c5 100644 --- a/sdk/appconfiguration/azure-appconfiguration/tests/test_azure_appconfiguration_client.py +++ b/sdk/appconfiguration/azure-appconfiguration/tests/test_azure_appconfiguration_client.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for diff --git a/sdk/appconfiguration/azure-appconfiguration/tests/test_azure_appconfiguration_client_async.py b/sdk/appconfiguration/azure-appconfiguration/tests/test_azure_appconfiguration_client_async.py index 84a5311da909..d491cc87c86f 100644 --- a/sdk/appconfiguration/azure-appconfiguration/tests/test_azure_appconfiguration_client_async.py +++ b/sdk/appconfiguration/azure-appconfiguration/tests/test_azure_appconfiguration_client_async.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for diff --git a/sdk/appconfiguration/azure-appconfiguration/tsp-location.yaml b/sdk/appconfiguration/azure-appconfiguration/tsp-location.yaml new file mode 100644 index 000000000000..1ba6424761cf --- /dev/null +++ b/sdk/appconfiguration/azure-appconfiguration/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/appconfiguration/AppConfiguration +commit: 26af8eff710ea634da1b33fed369967d1c39b689 +repo: Azure/azure-rest-api-specs +additionalDirectories: