diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/README.md b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/README.md index 1661e8f8ceaf..da310df8a0f8 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/README.md +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/README.md @@ -1,7 +1,7 @@ # Microsoft Azure SDK for Python This is the Microsoft Azure Cognitive Services Management Client Library. -This package has been tested with Python 3.7+. +This package has been tested with Python 3.8+. For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). ## _Disclaimer_ @@ -12,7 +12,7 @@ _Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For ### Prerequisites -- Python 3.7+ is required to use this package. +- Python 3.8+ is required to use this package. - [Azure subscription](https://azure.microsoft.com/free/) ### Install the package @@ -59,6 +59,3 @@ Code samples for this package can be found at: If you encounter any bugs or have suggestions, please file an issue in the [Issues](https://github.com/Azure/azure-sdk-for-python/issues) section of the project. - - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fazure-mgmt-cognitiveservices%2FREADME.png) diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/_meta.json b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/_meta.json index ff7441707e7c..e6f65b381f18 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/_meta.json +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/_meta.json @@ -1,11 +1,11 @@ { - "commit": "4b7481587132ce0bde5f0a6d6ab590129f7b7179", + "commit": "ea6ad35ac1ada673c94e486f1ac451824ca3993d", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest": "3.9.2", + "autorest": "3.10.2", "use": [ - "@autorest/python@6.6.0", - "@autorest/modelerfour@4.24.3" + "@autorest/python@6.19.0", + "@autorest/modelerfour@4.27.0" ], - "autorest_command": "autorest specification/cognitiveservices/resource-manager/readme.md --generate-sample=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/home/vsts/work/1/azure-sdk-for-python/sdk --use=@autorest/python@6.6.0 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", + "autorest_command": "autorest specification/cognitiveservices/resource-manager/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.19.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", "readme": "specification/cognitiveservices/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_cognitive_services_management_client.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_cognitive_services_management_client.py index abaa9824b87e..a1f1c2283335 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_cognitive_services_management_client.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_cognitive_services_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from ._configuration import CognitiveServicesManagementClientConfiguration @@ -20,12 +23,21 @@ CognitiveServicesManagementClientOperationsMixin, CommitmentPlansOperations, CommitmentTiersOperations, + DefenderForAISettingsOperations, DeletedAccountsOperations, DeploymentsOperations, + EncryptionScopesOperations, + LocationBasedModelCapacitiesOperations, + ModelCapacitiesOperations, ModelsOperations, + NetworkSecurityPerimeterConfigurationsOperations, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations, + RaiBlocklistItemsOperations, + RaiBlocklistsOperations, + RaiContentFiltersOperations, + RaiPoliciesOperations, ResourceSkusOperations, UsagesOperations, ) @@ -54,6 +66,11 @@ class CognitiveServicesManagementClient( :vartype commitment_tiers: azure.mgmt.cognitiveservices.operations.CommitmentTiersOperations :ivar models: ModelsOperations operations :vartype models: azure.mgmt.cognitiveservices.operations.ModelsOperations + :ivar location_based_model_capacities: LocationBasedModelCapacitiesOperations operations + :vartype location_based_model_capacities: + azure.mgmt.cognitiveservices.operations.LocationBasedModelCapacitiesOperations + :ivar model_capacities: ModelCapacitiesOperations operations + :vartype model_capacities: azure.mgmt.cognitiveservices.operations.ModelCapacitiesOperations :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations :vartype private_endpoint_connections: azure.mgmt.cognitiveservices.operations.PrivateEndpointConnectionsOperations @@ -64,13 +81,32 @@ class CognitiveServicesManagementClient( :vartype deployments: azure.mgmt.cognitiveservices.operations.DeploymentsOperations :ivar commitment_plans: CommitmentPlansOperations operations :vartype commitment_plans: azure.mgmt.cognitiveservices.operations.CommitmentPlansOperations + :ivar encryption_scopes: EncryptionScopesOperations operations + :vartype encryption_scopes: azure.mgmt.cognitiveservices.operations.EncryptionScopesOperations + :ivar rai_policies: RaiPoliciesOperations operations + :vartype rai_policies: azure.mgmt.cognitiveservices.operations.RaiPoliciesOperations + :ivar rai_blocklists: RaiBlocklistsOperations operations + :vartype rai_blocklists: azure.mgmt.cognitiveservices.operations.RaiBlocklistsOperations + :ivar rai_blocklist_items: RaiBlocklistItemsOperations operations + :vartype rai_blocklist_items: + azure.mgmt.cognitiveservices.operations.RaiBlocklistItemsOperations + :ivar rai_content_filters: RaiContentFiltersOperations operations + :vartype rai_content_filters: + azure.mgmt.cognitiveservices.operations.RaiContentFiltersOperations + :ivar network_security_perimeter_configurations: + NetworkSecurityPerimeterConfigurationsOperations operations + :vartype network_security_perimeter_configurations: + azure.mgmt.cognitiveservices.operations.NetworkSecurityPerimeterConfigurationsOperations + :ivar defender_for_ai_settings: DefenderForAISettingsOperations operations + :vartype defender_for_ai_settings: + azure.mgmt.cognitiveservices.operations.DefenderForAISettingsOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str - :keyword api_version: Api Version. Default value is "2023-05-01". Note that overriding this + :keyword api_version: Api Version. Default value is "2024-10-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 @@ -87,7 +123,25 @@ def __init__( self._config = CognitiveServicesManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) @@ -104,6 +158,12 @@ def __init__( self._client, self._config, self._serialize, self._deserialize ) self.models = ModelsOperations(self._client, self._config, self._serialize, self._deserialize) + self.location_based_model_capacities = LocationBasedModelCapacitiesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.model_capacities = ModelCapacitiesOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.private_endpoint_connections = PrivateEndpointConnectionsOperations( self._client, self._config, self._serialize, self._deserialize ) @@ -114,8 +174,25 @@ def __init__( self.commitment_plans = CommitmentPlansOperations( self._client, self._config, self._serialize, self._deserialize ) + self.encryption_scopes = EncryptionScopesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.rai_policies = RaiPoliciesOperations(self._client, self._config, self._serialize, self._deserialize) + self.rai_blocklists = RaiBlocklistsOperations(self._client, self._config, self._serialize, self._deserialize) + self.rai_blocklist_items = RaiBlocklistItemsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.rai_content_filters = RaiContentFiltersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.network_security_perimeter_configurations = NetworkSecurityPerimeterConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.defender_for_ai_settings = DefenderForAISettingsOperations( + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, request: HttpRequest, **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 @@ -135,12 +212,12 @@ def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore def close(self) -> None: self._client.close() - def __enter__(self) -> "CognitiveServicesManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_configuration.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_configuration.py index 7cfb8d0ace29..fe5d779db3a0 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_configuration.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_configuration.py @@ -8,7 +8,6 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy @@ -19,7 +18,7 @@ from azure.core.credentials import TokenCredential -class CognitiveServicesManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class CognitiveServicesManagementClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for CognitiveServicesManagementClient. Note that all parameters used to create this instance are saved as instance @@ -29,14 +28,13 @@ class CognitiveServicesManagementClientConfiguration(Configuration): # pylint: :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :keyword api_version: Api Version. Default value is "2023-05-01". Note that overriding this + :keyword api_version: Api Version. Default value is "2024-10-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(CognitiveServicesManagementClientConfiguration, self).__init__(**kwargs) - api_version: str = kwargs.pop("api_version", "2023-05-01") + api_version: str = kwargs.pop("api_version", "2024-10-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -48,6 +46,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-cognitiveservices/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +55,9 @@ def _configure(self, **kwargs: Any) -> None: self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + 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 = ARMChallengeAuthenticationPolicy( diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_serialization.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_serialization.py index 842ae727fbbc..8139854b97bb 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_serialization.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_serialization.py @@ -63,8 +63,8 @@ import isodate # type: ignore -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback -from azure.core.serialization import NULL as AzureCoreNull +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") @@ -124,7 +124,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: pass return ET.fromstring(data_as_str) # nosec - except ET.ParseError: + except ET.ParseError as err: # It might be because the server has an issue, and returned JSON with # content-type XML.... # So let's try a JSON load, and if it's still broken @@ -143,7 +143,9 @@ def _json_attemp(data): # The function hack is because Py2.7 messes up with exception # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod @@ -170,13 +172,6 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], return None -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str - unicode_str = str - _LOGGER = logging.getLogger(__name__) try: @@ -295,7 +290,7 @@ class Model(object): _validation: Dict[str, Dict[str, Any]] = {} def __init__(self, **kwargs: Any) -> None: - self.additional_properties: Dict[str, Any] = {} + self.additional_properties: Optional[Dict[str, Any]] = {} for k in kwargs: 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__) @@ -340,7 +335,7 @@ def _create_xml_node(cls): return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to azure from this model. + """Return the JSON that would be sent to server from this model. This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. @@ -351,7 +346,7 @@ 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) + return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore def as_dict( self, @@ -390,7 +385,7 @@ def my_key_transformer(key, attr_desc, value): :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore @classmethod def _infer_class_models(cls): @@ -415,7 +410,7 @@ def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = N :raises: DeserializationError if something went wrong """ deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def from_dict( @@ -445,7 +440,7 @@ def from_dict( if key_extractors is None else key_extractors ) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def _flatten_subtype(cls, key, objects): @@ -545,7 +540,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -561,7 +556,7 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_transformer = full_restapi_key_transformer self.client_side_validation = True @@ -649,7 +644,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): else: # That's a basic type # Integrate namespace if necessary local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) + local_node.text = str(new_attr) serialized.append(local_node) # type: ignore else: # JSON for k in reversed(keys): # type: ignore @@ -662,12 +657,13 @@ def _serialize(self, target_obj, data_type=None, **kwargs): _serialized.update(_new_attr) # type: ignore _new_attr = _new_attr[k] # type: ignore _serialized = _serialized[k] - except ValueError: - continue + except ValueError as err: + if isinstance(err, SerializationError): + raise except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err else: return serialized @@ -709,7 +705,7 @@ def body(self, data, data_type, **kwargs): ] data = deserializer._deserialize(data_type, data) except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + raise SerializationError("Unable to build a model: " + str(err)) from err return self._serialize(data, data_type, **kwargs) @@ -729,6 +725,7 @@ def url(self, name, data, data_type, **kwargs): if kwargs.get("skip_quote") is True: output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") except SerializationError: @@ -741,7 +738,9 @@ def query(self, name, data, data_type, **kwargs): :param data: The data to be serialized. :param str data_type: The type to be serialized from. - :rtype: str + :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 """ @@ -749,10 +748,8 @@ def query(self, name, data, data_type, **kwargs): # Treat the list aside, since we don't want to encode the div separator if data_type.startswith("["): internal_data_type = data_type[1:-1] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) # Not a list, regular serialization output = self.serialize_data(data, data_type, **kwargs) @@ -803,7 +800,7 @@ def serialize_data(self, data, data_type, **kwargs): raise ValueError("No value for given attribute") try: - if data is AzureCoreNull: + if data is CoreNull: return None if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) @@ -823,7 +820,7 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) + raise SerializationError(msg.format(data, data_type)) from err else: return self._serialize(data, **kwargs) @@ -891,6 +888,8 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): 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 """ if isinstance(data, str): @@ -903,9 +902,14 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): for d in data: try: serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized.append(None) + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + if div: serialized = ["" if s is None else str(s) for s in serialized] serialized = div.join(serialized) @@ -950,7 +954,9 @@ def serialize_dict(self, attr, dict_type, **kwargs): for key, value in attr.items(): try: serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized[self.serialize_unicode(key)] = None if "xml" in serialization_ctxt: @@ -983,7 +989,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) if obj_type is _long_type: return self.serialize_long(attr) - if obj_type is unicode_str: + if obj_type is str: return self.serialize_unicode(attr) if obj_type is datetime.datetime: return self.serialize_iso(attr) @@ -1160,10 +1166,10 @@ def serialize_iso(attr, **kwargs): return date + microseconds + "Z" except (ValueError, OverflowError) as err: msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err except AttributeError as err: msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) + raise TypeError(msg) from err @staticmethod def serialize_unix(attr, **kwargs): @@ -1199,7 +1205,6 @@ def rest_key_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1220,7 +1225,6 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1361,7 +1365,7 @@ class Deserializer(object): 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}]?") - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1381,7 +1385,7 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_extractors = [rest_key_extractor, xml_key_extractor] # Additional properties only works if the "rest_key_extractor" is used to # extract the keys. Making it to work whatever the key extractor is too much @@ -1434,12 +1438,12 @@ def _deserialize(self, target_obj, data): response, class_name = self._classify_target(target_obj, data) - if isinstance(response, basestring): + if isinstance(response, str): return self.deserialize_data(data, response) elif isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) - if data is None: + if data is None or data is CoreNull: return data try: attributes = response._attribute_map # type: ignore @@ -1471,7 +1475,7 @@ def _deserialize(self, target_obj, data): d_attrs[attr] = value except (AttributeError, TypeError, KeyError) as err: msg = "Unable to deserialize to object: " + class_name # type: ignore - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: additional_properties = self._build_additional_properties(attributes, data) return self._instantiate_model(response, d_attrs, additional_properties) @@ -1505,14 +1509,14 @@ def _classify_target(self, target, data): if target is None: return None, None - if isinstance(target, basestring): + if isinstance(target, str): try: target = self.dependencies[target] except KeyError: return target, target try: - target = target._classify(data, self.dependencies) + target = target._classify(data, self.dependencies) # type: ignore except AttributeError: pass # Target is not a Model, no classify return target, target.__class__.__name__ # type: ignore @@ -1568,7 +1572,7 @@ def _unpack_content(raw_data, content_type=None): if hasattr(raw_data, "_content_consumed"): return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore return raw_data @@ -1642,7 +1646,7 @@ def deserialize_data(self, data, data_type): except (ValueError, TypeError, AttributeError) as err: msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return self._deserialize(obj_type, data) @@ -1690,7 +1694,7 @@ def deserialize_object(self, attr, **kwargs): if isinstance(attr, ET.Element): # Do no recurse on XML, just return the tree as-is return attr - if isinstance(attr, basestring): + if isinstance(attr, str): return self.deserialize_basic(attr, "str") obj_type = type(attr) if obj_type in self.basic_types: @@ -1747,7 +1751,7 @@ def deserialize_basic(self, attr, data_type): if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, basestring): + elif isinstance(attr, str): if attr.lower() in ["true", "1"]: return True elif attr.lower() in ["false", "0"]: @@ -1798,7 +1802,6 @@ def deserialize_enum(data, enum_obj): data = data.value if isinstance(data, int): # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 try: return list(enum_obj.__members__.values())[data] except IndexError: @@ -1852,10 +1855,10 @@ def deserialize_decimal(attr): if isinstance(attr, ET.Element): attr = attr.text try: - return decimal.Decimal(attr) # type: ignore + return decimal.Decimal(str(attr)) # type: ignore except decimal.DecimalException as err: msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err @staticmethod def deserialize_long(attr): @@ -1883,7 +1886,7 @@ def deserialize_duration(attr): duration = isodate.parse_duration(attr) except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return duration @@ -1900,7 +1903,7 @@ def deserialize_date(attr): if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore raise DeserializationError("Date must have only digits and -. Received: %s" % attr) # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) @staticmethod def deserialize_time(attr): @@ -1935,7 +1938,7 @@ def deserialize_rfc(attr): date_obj = date_obj.astimezone(tz=TZ_UTC) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return date_obj @@ -1972,7 +1975,7 @@ def deserialize_iso(attr): raise OverflowError("Hit max or min date") except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return date_obj @@ -1988,9 +1991,10 @@ def deserialize_unix(attr): if isinstance(attr, ET.Element): attr = int(attr.text) # type: ignore try: + attr = int(attr) date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) except ValueError as err: msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return date_obj diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_vendor.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_vendor.py index 1866139c50f9..d064dd73a618 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_vendor.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_vendor.py @@ -6,9 +6,7 @@ # -------------------------------------------------------------------------- from abc import ABC -from typing import List, TYPE_CHECKING, cast - -from azure.core.pipeline.transport import HttpRequest +from typing import TYPE_CHECKING from ._configuration import CognitiveServicesManagementClientConfiguration @@ -19,27 +17,7 @@ from ._serialization import Deserializer, Serializer -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) - - -class CognitiveServicesManagementClientMixinABC(ABC): +class CognitiveServicesManagementClientMixinABC(ABC): # pylint: disable=name-too-long """DO NOT use this class. It is for internal typing use only.""" _client: "PipelineClient" diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_version.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_version.py index 59a719dd7a03..75a1436b862f 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_version.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "13.5.0" +VERSION = "11.0.0b1" diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/_cognitive_services_management_client.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/_cognitive_services_management_client.py index 81522e39b1e2..78ef2a21910e 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/_cognitive_services_management_client.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/_cognitive_services_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from .._serialization import Deserializer, Serializer @@ -20,12 +23,21 @@ CognitiveServicesManagementClientOperationsMixin, CommitmentPlansOperations, CommitmentTiersOperations, + DefenderForAISettingsOperations, DeletedAccountsOperations, DeploymentsOperations, + EncryptionScopesOperations, + LocationBasedModelCapacitiesOperations, + ModelCapacitiesOperations, ModelsOperations, + NetworkSecurityPerimeterConfigurationsOperations, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations, + RaiBlocklistItemsOperations, + RaiBlocklistsOperations, + RaiContentFiltersOperations, + RaiPoliciesOperations, ResourceSkusOperations, UsagesOperations, ) @@ -56,6 +68,12 @@ class CognitiveServicesManagementClient( azure.mgmt.cognitiveservices.aio.operations.CommitmentTiersOperations :ivar models: ModelsOperations operations :vartype models: azure.mgmt.cognitiveservices.aio.operations.ModelsOperations + :ivar location_based_model_capacities: LocationBasedModelCapacitiesOperations operations + :vartype location_based_model_capacities: + azure.mgmt.cognitiveservices.aio.operations.LocationBasedModelCapacitiesOperations + :ivar model_capacities: ModelCapacitiesOperations operations + :vartype model_capacities: + azure.mgmt.cognitiveservices.aio.operations.ModelCapacitiesOperations :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations :vartype private_endpoint_connections: azure.mgmt.cognitiveservices.aio.operations.PrivateEndpointConnectionsOperations @@ -67,13 +85,33 @@ class CognitiveServicesManagementClient( :ivar commitment_plans: CommitmentPlansOperations operations :vartype commitment_plans: azure.mgmt.cognitiveservices.aio.operations.CommitmentPlansOperations + :ivar encryption_scopes: EncryptionScopesOperations operations + :vartype encryption_scopes: + azure.mgmt.cognitiveservices.aio.operations.EncryptionScopesOperations + :ivar rai_policies: RaiPoliciesOperations operations + :vartype rai_policies: azure.mgmt.cognitiveservices.aio.operations.RaiPoliciesOperations + :ivar rai_blocklists: RaiBlocklistsOperations operations + :vartype rai_blocklists: azure.mgmt.cognitiveservices.aio.operations.RaiBlocklistsOperations + :ivar rai_blocklist_items: RaiBlocklistItemsOperations operations + :vartype rai_blocklist_items: + azure.mgmt.cognitiveservices.aio.operations.RaiBlocklistItemsOperations + :ivar rai_content_filters: RaiContentFiltersOperations operations + :vartype rai_content_filters: + azure.mgmt.cognitiveservices.aio.operations.RaiContentFiltersOperations + :ivar network_security_perimeter_configurations: + NetworkSecurityPerimeterConfigurationsOperations operations + :vartype network_security_perimeter_configurations: + azure.mgmt.cognitiveservices.aio.operations.NetworkSecurityPerimeterConfigurationsOperations + :ivar defender_for_ai_settings: DefenderForAISettingsOperations operations + :vartype defender_for_ai_settings: + azure.mgmt.cognitiveservices.aio.operations.DefenderForAISettingsOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str - :keyword api_version: Api Version. Default value is "2023-05-01". Note that overriding this + :keyword api_version: Api Version. Default value is "2024-10-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 @@ -90,7 +128,25 @@ def __init__( self._config = CognitiveServicesManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) @@ -107,6 +163,12 @@ def __init__( self._client, self._config, self._serialize, self._deserialize ) self.models = ModelsOperations(self._client, self._config, self._serialize, self._deserialize) + self.location_based_model_capacities = LocationBasedModelCapacitiesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.model_capacities = ModelCapacitiesOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.private_endpoint_connections = PrivateEndpointConnectionsOperations( self._client, self._config, self._serialize, self._deserialize ) @@ -117,8 +179,27 @@ def __init__( self.commitment_plans = CommitmentPlansOperations( self._client, self._config, self._serialize, self._deserialize ) + self.encryption_scopes = EncryptionScopesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.rai_policies = RaiPoliciesOperations(self._client, self._config, self._serialize, self._deserialize) + self.rai_blocklists = RaiBlocklistsOperations(self._client, self._config, self._serialize, self._deserialize) + self.rai_blocklist_items = RaiBlocklistItemsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.rai_content_filters = RaiContentFiltersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.network_security_perimeter_configurations = NetworkSecurityPerimeterConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.defender_for_ai_settings = DefenderForAISettingsOperations( + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -138,12 +219,12 @@ def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncH request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "CognitiveServicesManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/_configuration.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/_configuration.py index b3746e44eafd..2ce4b4dddddf 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/_configuration.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/_configuration.py @@ -8,7 +8,6 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy @@ -19,7 +18,7 @@ from azure.core.credentials_async import AsyncTokenCredential -class CognitiveServicesManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class CognitiveServicesManagementClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for CognitiveServicesManagementClient. Note that all parameters used to create this instance are saved as instance @@ -29,14 +28,13 @@ class CognitiveServicesManagementClientConfiguration(Configuration): # pylint: :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :keyword api_version: Api Version. Default value is "2023-05-01". Note that overriding this + :keyword api_version: Api Version. Default value is "2024-10-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(CognitiveServicesManagementClientConfiguration, self).__init__(**kwargs) - api_version: str = kwargs.pop("api_version", "2023-05-01") + api_version: str = kwargs.pop("api_version", "2024-10-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -48,6 +46,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-cognitiveservices/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +55,9 @@ def _configure(self, **kwargs: Any) -> None: self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + 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 = AsyncARMChallengeAuthenticationPolicy( diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/_vendor.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/_vendor.py index ae033a9e6c69..9d3c651db221 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/_vendor.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/_vendor.py @@ -8,8 +8,6 @@ from abc import ABC from typing import TYPE_CHECKING -from azure.core.pipeline.transport import HttpRequest - from ._configuration import CognitiveServicesManagementClientConfiguration if TYPE_CHECKING: @@ -19,7 +17,7 @@ from .._serialization import Deserializer, Serializer -class CognitiveServicesManagementClientMixinABC(ABC): +class CognitiveServicesManagementClientMixinABC(ABC): # pylint: disable=name-too-long """DO NOT use this class. It is for internal typing use only.""" _client: "AsyncPipelineClient" diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/__init__.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/__init__.py index 26043fb0a303..fdaa24c0f86a 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/__init__.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/__init__.py @@ -14,10 +14,19 @@ from ._cognitive_services_management_client_operations import CognitiveServicesManagementClientOperationsMixin from ._commitment_tiers_operations import CommitmentTiersOperations from ._models_operations import ModelsOperations +from ._location_based_model_capacities_operations import LocationBasedModelCapacitiesOperations +from ._model_capacities_operations import ModelCapacitiesOperations from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations from ._private_link_resources_operations import PrivateLinkResourcesOperations from ._deployments_operations import DeploymentsOperations from ._commitment_plans_operations import CommitmentPlansOperations +from ._encryption_scopes_operations import EncryptionScopesOperations +from ._rai_policies_operations import RaiPoliciesOperations +from ._rai_blocklists_operations import RaiBlocklistsOperations +from ._rai_blocklist_items_operations import RaiBlocklistItemsOperations +from ._rai_content_filters_operations import RaiContentFiltersOperations +from ._network_security_perimeter_configurations_operations import NetworkSecurityPerimeterConfigurationsOperations +from ._defender_for_ai_settings_operations import DefenderForAISettingsOperations from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import @@ -32,10 +41,19 @@ "CognitiveServicesManagementClientOperationsMixin", "CommitmentTiersOperations", "ModelsOperations", + "LocationBasedModelCapacitiesOperations", + "ModelCapacitiesOperations", "PrivateEndpointConnectionsOperations", "PrivateLinkResourcesOperations", "DeploymentsOperations", "CommitmentPlansOperations", + "EncryptionScopesOperations", + "RaiPoliciesOperations", + "RaiBlocklistsOperations", + "RaiBlocklistItemsOperations", + "RaiContentFiltersOperations", + "NetworkSecurityPerimeterConfigurationsOperations", + "DefenderForAISettingsOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_accounts_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_accounts_operations.py index 060fbfad96c6..d3a2bb7e4b48 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_accounts_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_accounts_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -17,12 +18,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict @@ -30,7 +32,6 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._accounts_operations import ( build_create_request, build_delete_request, @@ -44,8 +45,11 @@ build_regenerate_key_request, build_update_request, ) -from .._vendor import CognitiveServicesManagementClientMixinABC +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -70,9 +74,9 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") async def _create_initial( - self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO], **kwargs: Any - ) -> _models.Account: - error_map = { + self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO[bytes]], **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -85,7 +89,7 @@ async def _create_initial( 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.Account] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -95,7 +99,7 @@ async def _create_initial( else: _json = self._serialize.body(account, "Account") - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, @@ -103,43 +107,35 @@ async def _create_initial( content_type=content_type, json=_json, content=_content, - template_url=self._create_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("Account", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("Account", pipeline_response) - - if response.status_code == 202: - deserialized = self._deserialize("Account", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - _create_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" - } - @overload async def begin_create( self, @@ -163,14 +159,6 @@ async def begin_create( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Account or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.Account] @@ -182,7 +170,7 @@ async def begin_create( self, resource_group_name: str, account_name: str, - account: IO, + account: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -196,18 +184,10 @@ async def begin_create( :param account_name: The name of Cognitive Services account. Required. :type account_name: str :param account: The parameters to provide for the created account. Required. - :type account: IO + :type account: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Account or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.Account] @@ -216,7 +196,7 @@ async def begin_create( @distributed_trace_async async def begin_create( - self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO], **kwargs: Any + self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.Account]: """Create Cognitive Services Account. Accounts is a resource group wide resource type. It holds the keys for developer to access intelligent APIs. It's also the resource type for billing. @@ -227,19 +207,8 @@ async def begin_create( :param account_name: The name of Cognitive Services account. Required. :type account_name: str :param account: The parameters to provide for the created account. Is either a Account type or - a IO type. Required. - :type account: ~azure.mgmt.cognitiveservices.models.Account or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + a IO[bytes] type. Required. + :type account: ~azure.mgmt.cognitiveservices.models.Account or IO[bytes] :return: An instance of AsyncLROPoller that returns either Account or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.Account] @@ -266,12 +235,13 @@ async def begin_create( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Account", pipeline_response) + deserialized = self._deserialize("Account", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -281,22 +251,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.Account].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" - } + return AsyncLROPoller[_models.Account]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _update_initial( - self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO], **kwargs: Any - ) -> _models.Account: - error_map = { + self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO[bytes]], **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -309,7 +277,7 @@ async def _update_initial( 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.Account] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -319,7 +287,7 @@ async def _update_initial( else: _json = self._serialize.body(account, "Account") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, @@ -327,40 +295,35 @@ async def _update_initial( content_type=content_type, json=_json, content=_content, - template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("Account", pipeline_response) - - if response.status_code == 202: - deserialized = self._deserialize("Account", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - _update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" - } - @overload async def begin_update( self, @@ -383,14 +346,6 @@ async def begin_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Account or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.Account] @@ -402,7 +357,7 @@ async def begin_update( self, resource_group_name: str, account_name: str, - account: IO, + account: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -415,18 +370,10 @@ async def begin_update( :param account_name: The name of Cognitive Services account. Required. :type account_name: str :param account: The parameters to provide for the created account. Required. - :type account: IO + :type account: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Account or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.Account] @@ -435,7 +382,7 @@ async def begin_update( @distributed_trace_async async def begin_update( - self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO], **kwargs: Any + self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.Account]: """Updates a Cognitive Services account. @@ -445,19 +392,8 @@ async def begin_update( :param account_name: The name of Cognitive Services account. Required. :type account_name: str :param account: The parameters to provide for the created account. Is either a Account type or - a IO type. Required. - :type account: ~azure.mgmt.cognitiveservices.models.Account or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + a IO[bytes] type. Required. + :type account: ~azure.mgmt.cognitiveservices.models.Account or IO[bytes] :return: An instance of AsyncLROPoller that returns either Account or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.Account] @@ -484,12 +420,13 @@ async def begin_update( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Account", pipeline_response) + deserialized = self._deserialize("Account", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -499,22 +436,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.Account].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" - } + return AsyncLROPoller[_models.Account]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> None: - error_map = { + async def _delete_initial(self, resource_group_name: str, account_name: str, **kwargs: Any) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -526,38 +459,41 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements _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[None] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - _delete_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" - } + return deserialized # type: ignore @distributed_trace_async async def begin_delete(self, resource_group_name: str, account_name: str, **kwargs: Any) -> AsyncLROPoller[None]: @@ -568,14 +504,6 @@ async def begin_delete(self, resource_group_name: str, account_name: str, **kwar :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -589,7 +517,7 @@ async def begin_delete(self, resource_group_name: str, account_name: str, **kwar lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( # type: ignore + raw_result = await self._delete_initial( resource_group_name=resource_group_name, account_name=account_name, api_version=api_version, @@ -598,11 +526,12 @@ async def begin_delete(self, resource_group_name: str, account_name: str, **kwar params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) @@ -611,17 +540,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" - } + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace_async async def get(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _models.Account: @@ -632,12 +557,11 @@ async def get(self, resource_group_name: str, account_name: str, **kwargs: Any) :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Account or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.Account :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -651,21 +575,19 @@ async def get(self, resource_group_name: str, account_name: str, **kwargs: Any) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Account] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -675,16 +597,12 @@ async def get(self, resource_group_name: str, account_name: str, **kwargs: Any) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Account", pipeline_response) + deserialized = self._deserialize("Account", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" - } + return deserialized # type: ignore @distributed_trace def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.Account"]: @@ -693,7 +611,6 @@ def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Asy :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Account or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.Account] :raises ~azure.core.exceptions.HttpResponseError: @@ -704,7 +621,7 @@ def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Asy api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AccountListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -715,16 +632,14 @@ def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Asy def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_group_request( + _request = build_list_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -736,13 +651,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AccountListResult", pipeline_response) @@ -752,11 +666,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -769,15 +683,10 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts" - } - @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.Account"]: """Returns all the resources of a particular type belonging to a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Account or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.Account] :raises ~azure.core.exceptions.HttpResponseError: @@ -788,7 +697,7 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Account"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AccountListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -799,15 +708,13 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Account"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -819,13 +726,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AccountListResult", pipeline_response) @@ -835,11 +741,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -852,8 +758,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/accounts"} - @distributed_trace_async async def list_keys(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _models.ApiKeys: """Lists the account keys for the specified Cognitive Services account. @@ -863,12 +767,11 @@ async def list_keys(self, resource_group_name: str, account_name: str, **kwargs: :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ApiKeys or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.ApiKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -882,21 +785,19 @@ async def list_keys(self, resource_group_name: str, account_name: str, **kwargs: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ApiKeys] = kwargs.pop("cls", None) - request = build_list_keys_request( + _request = build_list_keys_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_keys.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -906,16 +807,12 @@ async def list_keys(self, resource_group_name: str, account_name: str, **kwargs: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ApiKeys", pipeline_response) + deserialized = self._deserialize("ApiKeys", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list_keys.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/listKeys" - } + return deserialized # type: ignore @distributed_trace_async async def regenerate_key( @@ -931,12 +828,11 @@ async def regenerate_key( :param key_name: key name to generate (Key1|Key2). Known values are: "Key1" and "Key2". Required. :type key_name: str or ~azure.mgmt.cognitiveservices.models.KeyName - :keyword callable cls: A custom type or function that will be passed the direct response :return: ApiKeys or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.ApiKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -954,23 +850,21 @@ async def regenerate_key( _parameters = _models.RegenerateKeyParameters(key_name=key_name) _json = self._serialize.body(_parameters, "RegenerateKeyParameters") - request = build_regenerate_key_request( + _request = build_regenerate_key_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.regenerate_key.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -980,16 +874,12 @@ async def regenerate_key( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ApiKeys", pipeline_response) + deserialized = self._deserialize("ApiKeys", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - regenerate_key.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/regenerateKey" - } + return deserialized # type: ignore @distributed_trace_async async def list_skus( @@ -1002,12 +892,11 @@ async def list_skus( :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AccountSkuListResult or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.AccountSkuListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1021,21 +910,19 @@ async def list_skus( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AccountSkuListResult] = kwargs.pop("cls", None) - request = build_list_skus_request( + _request = build_list_skus_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_skus.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1045,16 +932,12 @@ async def list_skus( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AccountSkuListResult", pipeline_response) + deserialized = self._deserialize("AccountSkuListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list_skus.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/skus" - } + return deserialized # type: ignore @distributed_trace_async async def list_usages( @@ -1071,12 +954,11 @@ async def list_usages( supported parameter is name.value (name of the metric, can have an or of multiple names). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: UsageListResult or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.UsageListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1090,22 +972,20 @@ async def list_usages( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.UsageListResult] = kwargs.pop("cls", None) - request = build_list_usages_request( + _request = build_list_usages_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, filter=filter, api_version=api_version, - template_url=self.list_usages.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1115,16 +995,12 @@ async def list_usages( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("UsageListResult", pipeline_response) + deserialized = self._deserialize("UsageListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list_usages.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/usages" - } + return deserialized # type: ignore @distributed_trace def list_models( @@ -1137,7 +1013,6 @@ def list_models( :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AccountModel or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.AccountModel] @@ -1149,7 +1024,7 @@ def list_models( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AccountModelListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1160,17 +1035,15 @@ def list_models( def prepare_request(next_link=None): if not next_link: - request = build_list_models_request( + _request = build_list_models_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_models.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1182,13 +1055,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AccountModelListResult", pipeline_response) @@ -1198,11 +1070,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1214,7 +1086,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_models.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/models" - } diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_cognitive_services_management_client_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_cognitive_services_management_client_operations.py index 8f6f9ee4b9d1..e566a4959840 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_cognitive_services_management_client_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_cognitive_services_management_client_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, List, Optional, TypeVar +import sys +from typing import Any, Callable, Dict, List, Optional, Type, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, @@ -17,25 +18,31 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._cognitive_services_management_client_operations import ( + build_calculate_model_capacity_request, build_check_domain_availability_request, build_check_sku_availability_request, ) from .._vendor import CognitiveServicesManagementClientMixinABC +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class CognitiveServicesManagementClientOperationsMixin(CognitiveServicesManagementClientMixinABC): +class CognitiveServicesManagementClientOperationsMixin( # pylint: disable=name-too-long + CognitiveServicesManagementClientMixinABC +): + @distributed_trace_async async def check_sku_availability( self, location: str, skus: List[str], kind: str, type: str, **kwargs: Any @@ -46,16 +53,15 @@ async def check_sku_availability( :type location: str :param skus: The SKU of the resource. Required. :type skus: list[str] - :param kind: The Kind of the resource. Required. + :param kind: The kind (type) of cognitive service account. Required. :type kind: str :param type: The Type of the resource. Required. :type type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: SkuAvailabilityListResult or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.SkuAvailabilityListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -73,22 +79,20 @@ async def check_sku_availability( _parameters = _models.CheckSkuAvailabilityParameter(kind=kind, skus=skus, type=type) _json = self._serialize.body(_parameters, "CheckSkuAvailabilityParameter") - request = build_check_sku_availability_request( + _request = build_check_sku_availability_request( location=location, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_sku_availability.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -98,16 +102,12 @@ async def check_sku_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SkuAvailabilityListResult", pipeline_response) + deserialized = self._deserialize("SkuAvailabilityListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - check_sku_availability.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/checkSkuAvailability" - } + return deserialized # type: ignore @distributed_trace_async async def check_domain_availability( @@ -121,12 +121,11 @@ async def check_domain_availability( :type type: str :param kind: The Kind of the resource. Default value is None. :type kind: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DomainAvailability or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.DomainAvailability :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -144,21 +143,19 @@ async def check_domain_availability( _parameters = _models.CheckDomainAvailabilityParameter(kind=kind, subdomain_name=subdomain_name, type=type) _json = self._serialize.body(_parameters, "CheckDomainAvailabilityParameter") - request = build_check_domain_availability_request( + _request = build_check_domain_availability_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_domain_availability.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -168,13 +165,76 @@ async def check_domain_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DomainAvailability", pipeline_response) + deserialized = self._deserialize("DomainAvailability", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore - return deserialized + @distributed_trace_async + async def calculate_model_capacity( + self, + model: Optional[_models.DeploymentModel] = None, + sku_name: Optional[str] = None, + workloads: Optional[List[_models.ModelCapacityCalculatorWorkload]] = None, + **kwargs: Any + ) -> _models.CalculateModelCapacityResult: + """Model capacity calculator. + + :param model: Properties of Cognitive Services account deployment model. Default value is None. + :type model: ~azure.mgmt.cognitiveservices.models.DeploymentModel + :param sku_name: The name of SKU. Default value is None. + :type sku_name: str + :param workloads: List of Model Capacity Calculator Workload. Default value is None. + :type workloads: list[~azure.mgmt.cognitiveservices.models.ModelCapacityCalculatorWorkload] + :return: CalculateModelCapacityResult or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.CalculateModelCapacityResult + :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 = 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", self._config.api_version)) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[_models.CalculateModelCapacityResult] = kwargs.pop("cls", None) + + _parameters = _models.CalculateModelCapacityParameter(model=model, sku_name=sku_name, workloads=workloads) + _json = self._serialize.body(_parameters, "CalculateModelCapacityParameter") + + _request = build_calculate_model_capacity_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CalculateModelCapacityResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - check_domain_availability.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/checkDomainAvailability" - } + return deserialized # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_commitment_plans_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_commitment_plans_operations.py index 1769ffadf453..ee9103a0dd8c 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_commitment_plans_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_commitment_plans_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -17,12 +18,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict @@ -30,7 +32,6 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._commitment_plans_operations import ( build_create_or_update_association_request, build_create_or_update_plan_request, @@ -47,8 +48,11 @@ build_list_request, build_update_plan_request, ) -from .._vendor import CognitiveServicesManagementClientMixinABC +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -83,7 +87,6 @@ def list( :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.CommitmentPlan] @@ -95,7 +98,7 @@ def list( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentPlanListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -106,17 +109,15 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -128,13 +129,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("CommitmentPlanListResult", pipeline_response) @@ -144,11 +144,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -161,10 +161,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/commitmentPlans" - } - @distributed_trace_async async def get( self, resource_group_name: str, account_name: str, commitment_plan_name: str, **kwargs: Any @@ -179,12 +175,11 @@ async def get( :param commitment_plan_name: The name of the commitmentPlan associated with the Cognitive Services Account. Required. :type commitment_plan_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CommitmentPlan or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.CommitmentPlan :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -198,22 +193,20 @@ async def get( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentPlan] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, commitment_plan_name=commitment_plan_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -223,16 +216,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CommitmentPlan", pipeline_response) + deserialized = self._deserialize("CommitmentPlan", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/commitmentPlans/{commitmentPlanName}" - } + return deserialized # type: ignore @overload async def create_or_update( @@ -260,7 +249,6 @@ async def create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CommitmentPlan or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.CommitmentPlan :raises ~azure.core.exceptions.HttpResponseError: @@ -272,7 +260,7 @@ async def create_or_update( resource_group_name: str, account_name: str, commitment_plan_name: str, - commitment_plan: IO, + commitment_plan: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -288,11 +276,10 @@ async def create_or_update( Services Account. Required. :type commitment_plan_name: str :param commitment_plan: The commitmentPlan properties. Required. - :type commitment_plan: IO + :type commitment_plan: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CommitmentPlan or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.CommitmentPlan :raises ~azure.core.exceptions.HttpResponseError: @@ -304,7 +291,7 @@ async def create_or_update( resource_group_name: str, account_name: str, commitment_plan_name: str, - commitment_plan: Union[_models.CommitmentPlan, IO], + commitment_plan: Union[_models.CommitmentPlan, IO[bytes]], **kwargs: Any ) -> _models.CommitmentPlan: """Update the state of specified commitmentPlans associated with the Cognitive Services account. @@ -317,18 +304,14 @@ async def create_or_update( :param commitment_plan_name: The name of the commitmentPlan associated with the Cognitive Services Account. Required. :type commitment_plan_name: str - :param commitment_plan: The commitmentPlan properties. Is either a CommitmentPlan type or a IO - type. Required. - :type commitment_plan: ~azure.mgmt.cognitiveservices.models.CommitmentPlan or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param commitment_plan: The commitmentPlan properties. Is either a CommitmentPlan type or a + IO[bytes] type. Required. + :type commitment_plan: ~azure.mgmt.cognitiveservices.models.CommitmentPlan or IO[bytes] :return: CommitmentPlan or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.CommitmentPlan :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -351,7 +334,7 @@ async def create_or_update( else: _json = self._serialize.body(commitment_plan, "CommitmentPlan") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, account_name=account_name, commitment_plan_name=commitment_plan_name, @@ -360,16 +343,14 @@ async def create_or_update( content_type=content_type, json=_json, content=_content, - template_url=self.create_or_update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -379,25 +360,17 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("CommitmentPlan", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("CommitmentPlan", pipeline_response) + deserialized = self._deserialize("CommitmentPlan", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/commitmentPlans/{commitmentPlanName}" - } - - async def _delete_initial( # pylint: disable=inconsistent-return-statements + async def _delete_initial( self, resource_group_name: str, account_name: str, commitment_plan_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -409,39 +382,42 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements _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[None] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, commitment_plan_name=commitment_plan_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - _delete_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/commitmentPlans/{commitmentPlanName}" - } + return deserialized # type: ignore @distributed_trace_async async def begin_delete( @@ -457,14 +433,6 @@ async def begin_delete( :param commitment_plan_name: The name of the commitmentPlan associated with the Cognitive Services Account. Required. :type commitment_plan_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -478,7 +446,7 @@ async def begin_delete( lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( # type: ignore + raw_result = await self._delete_initial( resource_group_name=resource_group_name, account_name=account_name, commitment_plan_name=commitment_plan_name, @@ -488,11 +456,12 @@ async def begin_delete( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) @@ -501,26 +470,22 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/commitmentPlans/{commitmentPlanName}" - } + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore async def _create_or_update_plan_initial( self, resource_group_name: str, commitment_plan_name: str, - commitment_plan: Union[_models.CommitmentPlan, IO], + commitment_plan: Union[_models.CommitmentPlan, IO[bytes]], **kwargs: Any - ) -> _models.CommitmentPlan: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -533,7 +498,7 @@ async def _create_or_update_plan_initial( 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.CommitmentPlan] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -543,7 +508,7 @@ async def _create_or_update_plan_initial( else: _json = self._serialize.body(commitment_plan, "CommitmentPlan") - request = build_create_or_update_plan_request( + _request = build_create_or_update_plan_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, subscription_id=self._config.subscription_id, @@ -551,40 +516,35 @@ async def _create_or_update_plan_initial( content_type=content_type, json=_json, content=_content, - template_url=self._create_or_update_plan_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("CommitmentPlan", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("CommitmentPlan", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - _create_or_update_plan_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" - } - @overload async def begin_create_or_update_plan( self, @@ -608,14 +568,6 @@ async def begin_create_or_update_plan( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.CommitmentPlan] @@ -627,7 +579,7 @@ async def begin_create_or_update_plan( self, resource_group_name: str, commitment_plan_name: str, - commitment_plan: IO, + commitment_plan: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -641,18 +593,10 @@ async def begin_create_or_update_plan( Services Account. Required. :type commitment_plan_name: str :param commitment_plan: The parameters to provide for the created commitment plan. Required. - :type commitment_plan: IO + :type commitment_plan: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.CommitmentPlan] @@ -664,7 +608,7 @@ async def begin_create_or_update_plan( self, resource_group_name: str, commitment_plan_name: str, - commitment_plan: Union[_models.CommitmentPlan, IO], + commitment_plan: Union[_models.CommitmentPlan, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.CommitmentPlan]: """Create Cognitive Services commitment plan. @@ -676,19 +620,8 @@ async def begin_create_or_update_plan( Services Account. Required. :type commitment_plan_name: str :param commitment_plan: The parameters to provide for the created commitment plan. Is either a - CommitmentPlan type or a IO type. Required. - :type commitment_plan: ~azure.mgmt.cognitiveservices.models.CommitmentPlan or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + CommitmentPlan type or a IO[bytes] type. Required. + :type commitment_plan: ~azure.mgmt.cognitiveservices.models.CommitmentPlan or IO[bytes] :return: An instance of AsyncLROPoller that returns either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.CommitmentPlan] @@ -715,12 +648,13 @@ async def begin_create_or_update_plan( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CommitmentPlan", pipeline_response) + deserialized = self._deserialize("CommitmentPlan", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -733,26 +667,24 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.CommitmentPlan].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update_plan.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" - } + return AsyncLROPoller[_models.CommitmentPlan]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _update_plan_initial( self, resource_group_name: str, commitment_plan_name: str, - commitment_plan: Union[_models.PatchResourceTagsAndSku, IO], + commitment_plan: Union[_models.PatchResourceTagsAndSku, IO[bytes]], **kwargs: Any - ) -> Optional[_models.CommitmentPlan]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -765,7 +697,7 @@ async def _update_plan_initial( 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[Optional[_models.CommitmentPlan]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -775,7 +707,7 @@ async def _update_plan_initial( else: _json = self._serialize.body(commitment_plan, "PatchResourceTagsAndSku") - request = build_update_plan_request( + _request = build_update_plan_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, subscription_id=self._config.subscription_id, @@ -783,41 +715,38 @@ async def _update_plan_initial( content_type=content_type, json=_json, content=_content, - template_url=self._update_plan_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("CommitmentPlan", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _update_plan_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" - } + return deserialized # type: ignore @overload async def begin_update_plan( @@ -842,14 +771,6 @@ async def begin_update_plan( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.CommitmentPlan] @@ -861,7 +782,7 @@ async def begin_update_plan( self, resource_group_name: str, commitment_plan_name: str, - commitment_plan: IO, + commitment_plan: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -875,18 +796,10 @@ async def begin_update_plan( Services Account. Required. :type commitment_plan_name: str :param commitment_plan: The parameters to provide for the created commitment plan. Required. - :type commitment_plan: IO + :type commitment_plan: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.CommitmentPlan] @@ -898,7 +811,7 @@ async def begin_update_plan( self, resource_group_name: str, commitment_plan_name: str, - commitment_plan: Union[_models.PatchResourceTagsAndSku, IO], + commitment_plan: Union[_models.PatchResourceTagsAndSku, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.CommitmentPlan]: """Create Cognitive Services commitment plan. @@ -910,19 +823,9 @@ async def begin_update_plan( Services Account. Required. :type commitment_plan_name: str :param commitment_plan: The parameters to provide for the created commitment plan. Is either a - PatchResourceTagsAndSku type or a IO type. Required. - :type commitment_plan: ~azure.mgmt.cognitiveservices.models.PatchResourceTagsAndSku or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + PatchResourceTagsAndSku type or a IO[bytes] type. Required. + :type commitment_plan: ~azure.mgmt.cognitiveservices.models.PatchResourceTagsAndSku or + IO[bytes] :return: An instance of AsyncLROPoller that returns either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.CommitmentPlan] @@ -949,12 +852,13 @@ async def begin_update_plan( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CommitmentPlan", pipeline_response) + deserialized = self._deserialize("CommitmentPlan", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -966,22 +870,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.CommitmentPlan].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_update_plan.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" - } + return AsyncLROPoller[_models.CommitmentPlan]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - async def _delete_plan_initial( # pylint: disable=inconsistent-return-statements + async def _delete_plan_initial( self, resource_group_name: str, commitment_plan_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -993,28 +895,31 @@ async def _delete_plan_initial( # pylint: disable=inconsistent-return-statement _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[None] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_plan_request( + _request = build_delete_plan_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_plan_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) @@ -1023,12 +928,12 @@ async def _delete_plan_initial( # pylint: disable=inconsistent-return-statement if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _delete_plan_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" - } + return deserialized # type: ignore @distributed_trace_async async def begin_delete_plan( @@ -1042,14 +947,6 @@ async def begin_delete_plan( :param commitment_plan_name: The name of the commitmentPlan associated with the Cognitive Services Account. Required. :type commitment_plan_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -1063,7 +960,7 @@ async def begin_delete_plan( lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_plan_initial( # type: ignore + raw_result = await self._delete_plan_initial( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, api_version=api_version, @@ -1072,11 +969,12 @@ async def begin_delete_plan( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: AsyncPollingMethod = cast( @@ -1087,17 +985,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete_plan.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" - } + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace_async async def get_plan( @@ -1111,12 +1005,11 @@ async def get_plan( :param commitment_plan_name: The name of the commitmentPlan associated with the Cognitive Services Account. Required. :type commitment_plan_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CommitmentPlan or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.CommitmentPlan :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1130,21 +1023,19 @@ async def get_plan( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentPlan] = kwargs.pop("cls", None) - request = build_get_plan_request( + _request = build_get_plan_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_plan.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1154,16 +1045,12 @@ async def get_plan( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CommitmentPlan", pipeline_response) + deserialized = self._deserialize("CommitmentPlan", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_plan.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" - } + return deserialized # type: ignore @distributed_trace def list_plans_by_resource_group( @@ -1174,7 +1061,6 @@ def list_plans_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.CommitmentPlan] @@ -1186,7 +1072,7 @@ def list_plans_by_resource_group( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentPlanListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1197,16 +1083,14 @@ def list_plans_by_resource_group( def prepare_request(next_link=None): if not next_link: - request = build_list_plans_by_resource_group_request( + _request = build_list_plans_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_plans_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1218,13 +1102,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("CommitmentPlanListResult", pipeline_response) @@ -1234,11 +1117,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1251,15 +1134,10 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_plans_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans" - } - @distributed_trace def list_plans_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.CommitmentPlan"]: """Returns all the resources of a particular type belonging to a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.CommitmentPlan] @@ -1271,7 +1149,7 @@ def list_plans_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Co api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentPlanListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1282,15 +1160,13 @@ def list_plans_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Co def prepare_request(next_link=None): if not next_link: - request = build_list_plans_by_subscription_request( + _request = build_list_plans_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_plans_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1302,13 +1178,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("CommitmentPlanListResult", pipeline_response) @@ -1318,11 +1193,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1335,10 +1210,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_plans_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/commitmentPlans" - } - @distributed_trace def list_associations( self, resource_group_name: str, commitment_plan_name: str, **kwargs: Any @@ -1351,7 +1222,6 @@ def list_associations( :param commitment_plan_name: The name of the commitmentPlan associated with the Cognitive Services Account. Required. :type commitment_plan_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either CommitmentPlanAccountAssociation or the result of cls(response) :rtype: @@ -1364,7 +1234,7 @@ def list_associations( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentPlanAccountAssociationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1375,17 +1245,15 @@ def list_associations( def prepare_request(next_link=None): if not next_link: - request = build_list_associations_request( + _request = build_list_associations_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_associations.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1397,13 +1265,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("CommitmentPlanAccountAssociationListResult", pipeline_response) @@ -1413,11 +1280,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1430,10 +1297,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_associations.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations" - } - @distributed_trace_async async def get_association( self, resource_group_name: str, commitment_plan_name: str, commitment_plan_association_name: str, **kwargs: Any @@ -1449,12 +1312,11 @@ async def get_association( :param commitment_plan_association_name: The name of the commitment plan association with the Cognitive Services Account. Required. :type commitment_plan_association_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CommitmentPlanAccountAssociation or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.CommitmentPlanAccountAssociation :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1468,22 +1330,20 @@ async def get_association( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentPlanAccountAssociation] = kwargs.pop("cls", None) - request = build_get_association_request( + _request = build_get_association_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, commitment_plan_association_name=commitment_plan_association_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_association.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1493,26 +1353,22 @@ async def get_association( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CommitmentPlanAccountAssociation", pipeline_response) + deserialized = self._deserialize("CommitmentPlanAccountAssociation", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_association.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations/{commitmentPlanAssociationName}" - } + return deserialized # type: ignore async def _create_or_update_association_initial( self, resource_group_name: str, commitment_plan_name: str, commitment_plan_association_name: str, - association: Union[_models.CommitmentPlanAccountAssociation, IO], + association: Union[_models.CommitmentPlanAccountAssociation, IO[bytes]], **kwargs: Any - ) -> _models.CommitmentPlanAccountAssociation: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1525,7 +1381,7 @@ async def _create_or_update_association_initial( 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.CommitmentPlanAccountAssociation] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -1535,7 +1391,7 @@ async def _create_or_update_association_initial( else: _json = self._serialize.body(association, "CommitmentPlanAccountAssociation") - request = build_create_or_update_association_request( + _request = build_create_or_update_association_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, commitment_plan_association_name=commitment_plan_association_name, @@ -1544,40 +1400,35 @@ async def _create_or_update_association_initial( content_type=content_type, json=_json, content=_content, - template_url=self._create_or_update_association_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("CommitmentPlanAccountAssociation", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("CommitmentPlanAccountAssociation", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - _create_or_update_association_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations/{commitmentPlanAssociationName}" - } - @overload async def begin_create_or_update_association( self, @@ -1605,14 +1456,6 @@ async def begin_create_or_update_association( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either CommitmentPlanAccountAssociation or the result of cls(response) :rtype: @@ -1626,7 +1469,7 @@ async def begin_create_or_update_association( resource_group_name: str, commitment_plan_name: str, commitment_plan_association_name: str, - association: IO, + association: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1643,18 +1486,10 @@ async def begin_create_or_update_association( Cognitive Services Account. Required. :type commitment_plan_association_name: str :param association: The commitmentPlan properties. Required. - :type association: IO + :type association: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either CommitmentPlanAccountAssociation or the result of cls(response) :rtype: @@ -1668,7 +1503,7 @@ async def begin_create_or_update_association( resource_group_name: str, commitment_plan_name: str, commitment_plan_association_name: str, - association: Union[_models.CommitmentPlanAccountAssociation, IO], + association: Union[_models.CommitmentPlanAccountAssociation, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.CommitmentPlanAccountAssociation]: """Create or update the association of the Cognitive Services commitment plan. @@ -1683,19 +1518,9 @@ async def begin_create_or_update_association( Cognitive Services Account. Required. :type commitment_plan_association_name: str :param association: The commitmentPlan properties. Is either a CommitmentPlanAccountAssociation - type or a IO type. Required. - :type association: ~azure.mgmt.cognitiveservices.models.CommitmentPlanAccountAssociation or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + type or a IO[bytes] type. Required. + :type association: ~azure.mgmt.cognitiveservices.models.CommitmentPlanAccountAssociation or + IO[bytes] :return: An instance of AsyncLROPoller that returns either CommitmentPlanAccountAssociation or the result of cls(response) :rtype: @@ -1724,12 +1549,13 @@ async def begin_create_or_update_association( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CommitmentPlanAccountAssociation", pipeline_response) + deserialized = self._deserialize("CommitmentPlanAccountAssociation", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -1742,22 +1568,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.CommitmentPlanAccountAssociation].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update_association.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations/{commitmentPlanAssociationName}" - } + return AsyncLROPoller[_models.CommitmentPlanAccountAssociation]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - async def _delete_association_initial( # pylint: disable=inconsistent-return-statements + async def _delete_association_initial( self, resource_group_name: str, commitment_plan_name: str, commitment_plan_association_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1769,29 +1593,32 @@ async def _delete_association_initial( # pylint: disable=inconsistent-return-st _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[None] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_association_request( + _request = build_delete_association_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, commitment_plan_association_name=commitment_plan_association_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_association_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) @@ -1800,12 +1627,12 @@ async def _delete_association_initial( # pylint: disable=inconsistent-return-st if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _delete_association_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations/{commitmentPlanAssociationName}" - } + return deserialized # type: ignore @distributed_trace_async async def begin_delete_association( @@ -1822,14 +1649,6 @@ async def begin_delete_association( :param commitment_plan_association_name: The name of the commitment plan association with the Cognitive Services Account. Required. :type commitment_plan_association_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -1843,7 +1662,7 @@ async def begin_delete_association( lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_association_initial( # type: ignore + raw_result = await self._delete_association_initial( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, commitment_plan_association_name=commitment_plan_association_name, @@ -1853,11 +1672,12 @@ async def begin_delete_association( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: AsyncPollingMethod = cast( @@ -1868,14 +1688,10 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete_association.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations/{commitmentPlanAssociationName}" - } + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_commitment_tiers_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_commitment_tiers_operations.py index 5ddd292a1023..f1f9faf98f1d 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_commitment_tiers_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_commitment_tiers_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -19,17 +20,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._commitment_tiers_operations import build_list_request -from .._vendor import CognitiveServicesManagementClientMixinABC +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,7 +61,6 @@ def list(self, location: str, **kwargs: Any) -> AsyncIterable["_models.Commitmen :param location: Resource location. Required. :type location: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either CommitmentTier or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.CommitmentTier] @@ -71,7 +72,7 @@ def list(self, location: str, **kwargs: Any) -> AsyncIterable["_models.Commitmen api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentTierListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -82,16 +83,14 @@ def list(self, location: str, **kwargs: Any) -> AsyncIterable["_models.Commitmen def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( location=location, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -103,13 +102,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("CommitmentTierListResult", pipeline_response) @@ -119,11 +117,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -135,7 +133,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/commitmentTiers" - } diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_defender_for_ai_settings_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_defender_for_ai_settings_operations.py new file mode 100644 index 000000000000..228da076938b --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_defender_for_ai_settings_operations.py @@ -0,0 +1,494 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._defender_for_ai_settings_operations import ( + build_create_or_update_request, + build_get_request, + build_list_request, + build_update_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class DefenderForAISettingsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.aio.CognitiveServicesManagementClient`'s + :attr:`defender_for_ai_settings` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DefenderForAISetting"]: + """Lists the Defender for AI settings. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :return: An iterator like instance of either DefenderForAISetting or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.DefenderForAISetting] + :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.DefenderForAISettingResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DefenderForAISettingResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get( + self, resource_group_name: str, account_name: str, defender_for_ai_setting_name: str, **kwargs: Any + ) -> _models.DefenderForAISetting: + """Gets the specified Defender for AI setting by name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param defender_for_ai_setting_name: The name of the defender for AI setting. Required. + :type defender_for_ai_setting_name: str + :return: DefenderForAISetting or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :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.DefenderForAISetting] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + defender_for_ai_setting_name=defender_for_ai_setting_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DefenderForAISetting", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, + resource_group_name: str, + account_name: str, + defender_for_ai_setting_name: str, + defender_for_ai_settings: _models.DefenderForAISetting, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DefenderForAISetting: + """Creates or Updates the specified Defender for AI setting. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param defender_for_ai_setting_name: The name of the defender for AI setting. Required. + :type defender_for_ai_setting_name: str + :param defender_for_ai_settings: Properties describing the Defender for AI setting. Required. + :type defender_for_ai_settings: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: DefenderForAISetting or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + account_name: str, + defender_for_ai_setting_name: str, + defender_for_ai_settings: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DefenderForAISetting: + """Creates or Updates the specified Defender for AI setting. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param defender_for_ai_setting_name: The name of the defender for AI setting. Required. + :type defender_for_ai_setting_name: str + :param defender_for_ai_settings: Properties describing the Defender for AI setting. Required. + :type defender_for_ai_settings: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: DefenderForAISetting or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + account_name: str, + defender_for_ai_setting_name: str, + defender_for_ai_settings: Union[_models.DefenderForAISetting, IO[bytes]], + **kwargs: Any + ) -> _models.DefenderForAISetting: + """Creates or Updates the specified Defender for AI setting. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param defender_for_ai_setting_name: The name of the defender for AI setting. Required. + :type defender_for_ai_setting_name: str + :param defender_for_ai_settings: Properties describing the Defender for AI setting. Is either a + DefenderForAISetting type or a IO[bytes] type. Required. + :type defender_for_ai_settings: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting or + IO[bytes] + :return: DefenderForAISetting or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :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 = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DefenderForAISetting] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(defender_for_ai_settings, (IOBase, bytes)): + _content = defender_for_ai_settings + else: + _json = self._serialize.body(defender_for_ai_settings, "DefenderForAISetting") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + defender_for_ai_setting_name=defender_for_ai_setting_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DefenderForAISetting", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, + resource_group_name: str, + account_name: str, + defender_for_ai_setting_name: str, + defender_for_ai_settings: _models.DefenderForAISetting, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DefenderForAISetting: + """Updates the specified Defender for AI setting. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param defender_for_ai_setting_name: The name of the defender for AI setting. Required. + :type defender_for_ai_setting_name: str + :param defender_for_ai_settings: Properties describing the Defender for AI setting. Required. + :type defender_for_ai_settings: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: DefenderForAISetting or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + account_name: str, + defender_for_ai_setting_name: str, + defender_for_ai_settings: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DefenderForAISetting: + """Updates the specified Defender for AI setting. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param defender_for_ai_setting_name: The name of the defender for AI setting. Required. + :type defender_for_ai_setting_name: str + :param defender_for_ai_settings: Properties describing the Defender for AI setting. Required. + :type defender_for_ai_settings: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: DefenderForAISetting or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + resource_group_name: str, + account_name: str, + defender_for_ai_setting_name: str, + defender_for_ai_settings: Union[_models.DefenderForAISetting, IO[bytes]], + **kwargs: Any + ) -> _models.DefenderForAISetting: + """Updates the specified Defender for AI setting. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param defender_for_ai_setting_name: The name of the defender for AI setting. Required. + :type defender_for_ai_setting_name: str + :param defender_for_ai_settings: Properties describing the Defender for AI setting. Is either a + DefenderForAISetting type or a IO[bytes] type. Required. + :type defender_for_ai_settings: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting or + IO[bytes] + :return: DefenderForAISetting or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :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 = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DefenderForAISetting] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(defender_for_ai_settings, (IOBase, bytes)): + _content = defender_for_ai_settings + else: + _json = self._serialize.body(defender_for_ai_settings, "DefenderForAISetting") + + _request = build_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + defender_for_ai_setting_name=defender_for_ai_setting_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DefenderForAISetting", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_deleted_accounts_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_deleted_accounts_operations.py index 55003e4d2dc6..db5d37aca5c7 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_deleted_accounts_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_deleted_accounts_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, Optional, Type, TypeVar, Union, cast import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -16,12 +17,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict @@ -29,10 +31,12 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._deleted_accounts_operations import build_get_request, build_list_request, build_purge_request -from .._vendor import CognitiveServicesManagementClientMixinABC +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -67,12 +71,11 @@ async def get(self, location: str, resource_group_name: str, account_name: str, :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Account or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.Account :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -86,22 +89,20 @@ async def get(self, location: str, resource_group_name: str, account_name: str, api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Account] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( location=location, resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -111,21 +112,17 @@ async def get(self, location: str, resource_group_name: str, account_name: str, error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Account", pipeline_response) + deserialized = self._deserialize("Account", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/resourceGroups/{resourceGroupName}/deletedAccounts/{accountName}" - } - - async def _purge_initial( # pylint: disable=inconsistent-return-statements + async def _purge_initial( self, location: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -137,39 +134,42 @@ async def _purge_initial( # pylint: disable=inconsistent-return-statements _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[None] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_purge_request( + _request = build_purge_request( location=location, resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._purge_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - _purge_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/resourceGroups/{resourceGroupName}/deletedAccounts/{accountName}" - } + return deserialized # type: ignore @distributed_trace_async async def begin_purge( @@ -184,14 +184,6 @@ async def begin_purge( :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -205,7 +197,7 @@ async def begin_purge( lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._purge_initial( # type: ignore + raw_result = await self._purge_initial( location=location, resource_group_name=resource_group_name, account_name=account_name, @@ -215,11 +207,12 @@ async def begin_purge( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) @@ -228,23 +221,18 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_purge.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/resourceGroups/{resourceGroupName}/deletedAccounts/{accountName}" - } + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.Account"]: """Returns all the resources of a particular type belonging to a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Account or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.Account] :raises ~azure.core.exceptions.HttpResponseError: @@ -255,7 +243,7 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Account"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AccountListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -266,15 +254,13 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Account"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -286,13 +272,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AccountListResult", pipeline_response) @@ -302,11 +287,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -318,5 +303,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/deletedAccounts"} diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_deployments_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_deployments_operations.py index 9335902dd41f..c6b90b7b0bc8 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_deployments_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_deployments_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -17,12 +18,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict @@ -30,15 +32,19 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._deployments_operations import ( build_create_or_update_request, build_delete_request, build_get_request, build_list_request, + build_list_skus_request, + build_update_request, ) -from .._vendor import CognitiveServicesManagementClientMixinABC +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -71,7 +77,6 @@ def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> As :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Deployment or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.Deployment] @@ -83,7 +88,7 @@ def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> As api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DeploymentListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -94,17 +99,15 @@ def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> As def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -116,13 +119,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DeploymentListResult", pipeline_response) @@ -132,11 +134,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -149,10 +151,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments" - } - @distributed_trace_async async def get( self, resource_group_name: str, account_name: str, deployment_name: str, **kwargs: Any @@ -167,12 +165,11 @@ async def get( :param deployment_name: The name of the deployment associated with the Cognitive Services Account. Required. :type deployment_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Deployment or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.Deployment :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -186,22 +183,20 @@ async def get( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Deployment] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, deployment_name=deployment_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -211,26 +206,22 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Deployment", pipeline_response) + deserialized = self._deserialize("Deployment", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}" - } + return deserialized # type: ignore async def _create_or_update_initial( self, resource_group_name: str, account_name: str, deployment_name: str, - deployment: Union[_models.Deployment, IO], + deployment: Union[_models.Deployment, IO[bytes]], **kwargs: Any - ) -> _models.Deployment: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -243,7 +234,7 @@ async def _create_or_update_initial( 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.Deployment] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -253,7 +244,7 @@ async def _create_or_update_initial( else: _json = self._serialize.body(deployment, "Deployment") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, account_name=account_name, deployment_name=deployment_name, @@ -262,40 +253,35 @@ async def _create_or_update_initial( content_type=content_type, json=_json, content=_content, - template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("Deployment", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("Deployment", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}" - } - @overload async def begin_create_or_update( self, @@ -322,14 +308,6 @@ async def begin_create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Deployment or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.Deployment] @@ -342,7 +320,7 @@ async def begin_create_or_update( resource_group_name: str, account_name: str, deployment_name: str, - deployment: IO, + deployment: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -358,18 +336,10 @@ async def begin_create_or_update( Account. Required. :type deployment_name: str :param deployment: The deployment properties. Required. - :type deployment: IO + :type deployment: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Deployment or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.Deployment] @@ -382,7 +352,7 @@ async def begin_create_or_update( resource_group_name: str, account_name: str, deployment_name: str, - deployment: Union[_models.Deployment, IO], + deployment: Union[_models.Deployment, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.Deployment]: """Update the state of specified deployments associated with the Cognitive Services account. @@ -395,20 +365,9 @@ async def begin_create_or_update( :param deployment_name: The name of the deployment associated with the Cognitive Services Account. Required. :type deployment_name: str - :param deployment: The deployment properties. Is either a Deployment type or a IO type. + :param deployment: The deployment properties. Is either a Deployment type or a IO[bytes] type. Required. - :type deployment: ~azure.mgmt.cognitiveservices.models.Deployment or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + :type deployment: ~azure.mgmt.cognitiveservices.models.Deployment or IO[bytes] :return: An instance of AsyncLROPoller that returns either Deployment or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.Deployment] @@ -436,12 +395,13 @@ async def begin_create_or_update( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Deployment", pipeline_response) + deserialized = self._deserialize("Deployment", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -454,22 +414,234 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.Deployment].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return AsyncLROPoller[_models.Deployment]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}" - } + async def _update_initial( + self, + resource_group_name: str, + account_name: str, + deployment_name: str, + deployment: Union[_models.PatchResourceTagsAndSku, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - async def _delete_initial( # pylint: disable=inconsistent-return-statements + 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(deployment, (IOBase, bytes)): + _content = deployment + else: + _json = self._serialize.body(deployment, "PatchResourceTagsAndSku") + + _request = build_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + deployment_name=deployment_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update( + self, + resource_group_name: str, + account_name: str, + deployment_name: str, + deployment: _models.PatchResourceTagsAndSku, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Deployment]: + """Update specified deployments associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param deployment_name: The name of the deployment associated with the Cognitive Services + Account. Required. + :type deployment_name: str + :param deployment: The deployment properties. Required. + :type deployment: ~azure.mgmt.cognitiveservices.models.PatchResourceTagsAndSku + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either Deployment or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.Deployment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + account_name: str, + deployment_name: str, + deployment: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Deployment]: + """Update specified deployments associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param deployment_name: The name of the deployment associated with the Cognitive Services + Account. Required. + :type deployment_name: str + :param deployment: The deployment properties. Required. + :type deployment: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either Deployment or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.Deployment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + account_name: str, + deployment_name: str, + deployment: Union[_models.PatchResourceTagsAndSku, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.Deployment]: + """Update specified deployments associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param deployment_name: The name of the deployment associated with the Cognitive Services + Account. Required. + :type deployment_name: str + :param deployment: The deployment properties. Is either a PatchResourceTagsAndSku type or a + IO[bytes] type. Required. + :type deployment: ~azure.mgmt.cognitiveservices.models.PatchResourceTagsAndSku or IO[bytes] + :return: An instance of AsyncLROPoller that returns either Deployment or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.Deployment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Deployment] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + account_name=account_name, + deployment_name=deployment_name, + deployment=deployment, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Deployment", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.Deployment].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.Deployment]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial( self, resource_group_name: str, account_name: str, deployment_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -481,39 +653,42 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements _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[None] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, deployment_name=deployment_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - _delete_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}" - } + return deserialized # type: ignore @distributed_trace_async async def begin_delete( @@ -529,14 +704,6 @@ async def begin_delete( :param deployment_name: The name of the deployment associated with the Cognitive Services Account. Required. :type deployment_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -550,7 +717,7 @@ async def begin_delete( lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( # type: ignore + raw_result = await self._delete_initial( resource_group_name=resource_group_name, account_name=account_name, deployment_name=deployment_name, @@ -560,11 +727,12 @@ async def begin_delete( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) @@ -573,14 +741,99 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_skus( + self, resource_group_name: str, account_name: str, deployment_name: str, **kwargs: Any + ) -> AsyncIterable["_models.SkuResource"]: + """Lists the specified deployments skus associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param deployment_name: The name of the deployment associated with the Cognitive Services + Account. Required. + :type deployment_name: str + :return: An iterator like instance of either SkuResource or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.SkuResource] + :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.DeploymentSkuListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_skus_request( + resource_group_name=resource_group_name, + account_name=account_name, + deployment_name=deployment_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DeploymentSkuListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}" - } + 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_encryption_scopes_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_encryption_scopes_operations.py new file mode 100644 index 000000000000..08428d59d993 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_encryption_scopes_operations.py @@ -0,0 +1,473 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._encryption_scopes_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class EncryptionScopesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.aio.CognitiveServicesManagementClient`'s + :attr:`encryption_scopes` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.EncryptionScope"]: + """Gets the content filters associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :return: An iterator like instance of either EncryptionScope or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.EncryptionScope] + :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.EncryptionScopeListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("EncryptionScopeListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get( + self, resource_group_name: str, account_name: str, encryption_scope_name: str, **kwargs: Any + ) -> _models.EncryptionScope: + """Gets the specified EncryptionScope associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param encryption_scope_name: The name of the encryptionScope associated with the Cognitive + Services Account. Required. + :type encryption_scope_name: str + :return: EncryptionScope or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.EncryptionScope + :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.EncryptionScope] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + encryption_scope_name=encryption_scope_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("EncryptionScope", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, + resource_group_name: str, + account_name: str, + encryption_scope_name: str, + encryption_scope: _models.EncryptionScope, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EncryptionScope: + """Update the state of specified encryptionScope associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param encryption_scope_name: The name of the encryptionScope associated with the Cognitive + Services Account. Required. + :type encryption_scope_name: str + :param encryption_scope: The encryptionScope properties. Required. + :type encryption_scope: ~azure.mgmt.cognitiveservices.models.EncryptionScope + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EncryptionScope or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.EncryptionScope + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + account_name: str, + encryption_scope_name: str, + encryption_scope: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EncryptionScope: + """Update the state of specified encryptionScope associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param encryption_scope_name: The name of the encryptionScope associated with the Cognitive + Services Account. Required. + :type encryption_scope_name: str + :param encryption_scope: The encryptionScope properties. Required. + :type encryption_scope: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: EncryptionScope or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.EncryptionScope + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + account_name: str, + encryption_scope_name: str, + encryption_scope: Union[_models.EncryptionScope, IO[bytes]], + **kwargs: Any + ) -> _models.EncryptionScope: + """Update the state of specified encryptionScope associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param encryption_scope_name: The name of the encryptionScope associated with the Cognitive + Services Account. Required. + :type encryption_scope_name: str + :param encryption_scope: The encryptionScope properties. Is either a EncryptionScope type or a + IO[bytes] type. Required. + :type encryption_scope: ~azure.mgmt.cognitiveservices.models.EncryptionScope or IO[bytes] + :return: EncryptionScope or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.EncryptionScope + :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 = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.EncryptionScope] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(encryption_scope, (IOBase, bytes)): + _content = encryption_scope + else: + _json = self._serialize.body(encryption_scope, "EncryptionScope") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + encryption_scope_name=encryption_scope_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("EncryptionScope", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _delete_initial( + self, resource_group_name: str, account_name: str, encryption_scope_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + 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[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + encryption_scope_name=encryption_scope_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, account_name: str, encryption_scope_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the specified encryptionScope associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param encryption_scope_name: The name of the encryptionScope associated with the Cognitive + Services Account. Required. + :type encryption_scope_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :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[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + encryption_scope_name=encryption_scope_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_location_based_model_capacities_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_location_based_model_capacities_operations.py new file mode 100644 index 000000000000..ed37d79e5290 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_location_based_model_capacities_operations.py @@ -0,0 +1,147 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._location_based_model_capacities_operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class LocationBasedModelCapacitiesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.aio.CognitiveServicesManagementClient`'s + :attr:`location_based_model_capacities` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, location: str, model_format: str, model_name: str, model_version: str, **kwargs: Any + ) -> AsyncIterable["_models.ModelCapacityListResultValueItem"]: + """List Location Based ModelCapacities. + + :param location: Resource location. Required. + :type location: str + :param model_format: The format of the Model. Required. + :type model_format: str + :param model_name: The name of the Model. Required. + :type model_name: str + :param model_version: The version of the Model. Required. + :type model_version: str + :return: An iterator like instance of either ModelCapacityListResultValueItem or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.ModelCapacityListResultValueItem] + :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.ModelCapacityListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + location=location, + subscription_id=self._config.subscription_id, + model_format=model_format, + model_name=model_name, + model_version=model_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ModelCapacityListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_model_capacities_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_model_capacities_operations.py new file mode 100644 index 000000000000..287d3c7da2f9 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_model_capacities_operations.py @@ -0,0 +1,144 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._model_capacities_operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ModelCapacitiesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.aio.CognitiveServicesManagementClient`'s + :attr:`model_capacities` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, model_format: str, model_name: str, model_version: str, **kwargs: Any + ) -> AsyncIterable["_models.ModelCapacityListResultValueItem"]: + """List ModelCapacities. + + :param model_format: The format of the Model. Required. + :type model_format: str + :param model_name: The name of the Model. Required. + :type model_name: str + :param model_version: The version of the Model. Required. + :type model_version: str + :return: An iterator like instance of either ModelCapacityListResultValueItem or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.ModelCapacityListResultValueItem] + :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.ModelCapacityListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + subscription_id=self._config.subscription_id, + model_format=model_format, + model_name=model_name, + model_version=model_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ModelCapacityListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_models_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_models_operations.py index ee1bfd6a0f19..ed4de7ac009c 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_models_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_models_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -19,17 +20,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._models_operations import build_list_request -from .._vendor import CognitiveServicesManagementClientMixinABC +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,7 +61,6 @@ def list(self, location: str, **kwargs: Any) -> AsyncIterable["_models.Model"]: :param location: Resource location. Required. :type location: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Model or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.Model] :raises ~azure.core.exceptions.HttpResponseError: @@ -70,7 +71,7 @@ def list(self, location: str, **kwargs: Any) -> AsyncIterable["_models.Model"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ModelListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -81,16 +82,14 @@ def list(self, location: str, **kwargs: Any) -> AsyncIterable["_models.Model"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( location=location, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -102,13 +101,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ModelListResult", pipeline_response) @@ -118,11 +116,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -134,7 +132,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/models" - } diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_network_security_perimeter_configurations_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_network_security_perimeter_configurations_operations.py new file mode 100644 index 000000000000..e4c5721f6481 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_network_security_perimeter_configurations_operations.py @@ -0,0 +1,334 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, Optional, Type, TypeVar, Union, cast +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._network_security_perimeter_configurations_operations import ( + build_get_request, + build_list_request, + build_reconcile_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class NetworkSecurityPerimeterConfigurationsOperations: # pylint: disable=name-too-long + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.aio.CognitiveServicesManagementClient`'s + :attr:`network_security_perimeter_configurations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.NetworkSecurityPerimeterConfiguration"]: + """Gets a list of NSP configurations for an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :return: An iterator like instance of either NetworkSecurityPerimeterConfiguration or the + result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterConfiguration] + :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.NetworkSecurityPerimeterConfigurationList] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("NetworkSecurityPerimeterConfigurationList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get( + self, resource_group_name: str, account_name: str, nsp_configuration_name: str, **kwargs: Any + ) -> _models.NetworkSecurityPerimeterConfiguration: + """Gets the specified NSP configurations for an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param nsp_configuration_name: The name of the NSP Configuration. Required. + :type nsp_configuration_name: str + :return: NetworkSecurityPerimeterConfiguration or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterConfiguration + :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.NetworkSecurityPerimeterConfiguration] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + nsp_configuration_name=nsp_configuration_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("NetworkSecurityPerimeterConfiguration", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _reconcile_initial( + self, resource_group_name: str, account_name: str, nsp_configuration_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + 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[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_reconcile_request( + resource_group_name=resource_group_name, + account_name=account_name, + nsp_configuration_name=nsp_configuration_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_reconcile( + self, resource_group_name: str, account_name: str, nsp_configuration_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.NetworkSecurityPerimeterConfiguration]: + """Reconcile the NSP configuration for an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param nsp_configuration_name: The name of the NSP Configuration. Required. + :type nsp_configuration_name: str + :return: An instance of AsyncLROPoller that returns either + NetworkSecurityPerimeterConfiguration or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterConfiguration] + :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.NetworkSecurityPerimeterConfiguration] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._reconcile_initial( + resource_group_name=resource_group_name, + account_name=account_name, + nsp_configuration_name=nsp_configuration_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("NetworkSecurityPerimeterConfiguration", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.NetworkSecurityPerimeterConfiguration].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.NetworkSecurityPerimeterConfiguration]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_operations.py index 95cb470c6705..ff191e3e8446 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -19,17 +20,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._operations import build_list_request -from .._vendor import CognitiveServicesManagementClientMixinABC +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -57,7 +59,6 @@ def __init__(self, *args, **kwargs) -> None: def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists all the available Cognitive Services account operations. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: @@ -68,7 +69,7 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -79,14 +80,12 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -98,13 +97,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) @@ -114,11 +112,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -130,5 +128,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.CognitiveServices/operations"} diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_private_endpoint_connections_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_private_endpoint_connections_operations.py index 182b07b61334..f6b5a668220f 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_private_endpoint_connections_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_private_endpoint_connections_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase -from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import sys +from typing import Any, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -15,27 +16,30 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._private_endpoint_connections_operations import ( build_create_or_update_request, build_delete_request, build_get_request, build_list_request, ) -from .._vendor import CognitiveServicesManagementClientMixinABC +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -70,12 +74,11 @@ async def list( :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateEndpointConnectionListResult or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.PrivateEndpointConnectionListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -89,21 +92,19 @@ async def list( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PrivateEndpointConnectionListResult] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -113,16 +114,12 @@ async def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections" - } + return deserialized # type: ignore @distributed_trace_async async def get( @@ -138,12 +135,11 @@ async def get( :param private_endpoint_connection_name: The name of the private endpoint connection associated with the Cognitive Services Account. Required. :type private_endpoint_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.PrivateEndpointConnection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -157,22 +153,20 @@ async def get( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -182,26 +176,22 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore async def _create_or_update_initial( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, - properties: Union[_models.PrivateEndpointConnection, IO], + properties: Union[_models.PrivateEndpointConnection, IO[bytes]], **kwargs: Any - ) -> _models.PrivateEndpointConnection: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -214,7 +204,7 @@ async def _create_or_update_initial( 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.PrivateEndpointConnection] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -224,7 +214,7 @@ async def _create_or_update_initial( else: _json = self._serialize.body(properties, "PrivateEndpointConnection") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -233,40 +223,35 @@ async def _create_or_update_initial( content_type=content_type, json=_json, content=_content, - template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) - - if response.status_code == 202: - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" - } - @overload async def begin_create_or_update( self, @@ -294,14 +279,6 @@ async def begin_create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: @@ -315,7 +292,7 @@ async def begin_create_or_update( resource_group_name: str, account_name: str, private_endpoint_connection_name: str, - properties: IO, + properties: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -332,18 +309,10 @@ async def begin_create_or_update( with the Cognitive Services Account. Required. :type private_endpoint_connection_name: str :param properties: The private endpoint connection properties. Required. - :type properties: IO + :type properties: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: @@ -357,7 +326,7 @@ async def begin_create_or_update( resource_group_name: str, account_name: str, private_endpoint_connection_name: str, - properties: Union[_models.PrivateEndpointConnection, IO], + properties: Union[_models.PrivateEndpointConnection, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: """Update the state of specified private endpoint connection associated with the Cognitive @@ -372,19 +341,8 @@ async def begin_create_or_update( with the Cognitive Services Account. Required. :type private_endpoint_connection_name: str :param properties: The private endpoint connection properties. Is either a - PrivateEndpointConnection type or a IO type. Required. - :type properties: ~azure.mgmt.cognitiveservices.models.PrivateEndpointConnection or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + PrivateEndpointConnection type or a IO[bytes] type. Required. + :type properties: ~azure.mgmt.cognitiveservices.models.PrivateEndpointConnection or IO[bytes] :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: @@ -413,12 +371,13 @@ async def begin_create_or_update( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -428,22 +387,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.PrivateEndpointConnection].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return AsyncLROPoller[_models.PrivateEndpointConnection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - async def _delete_initial( # pylint: disable=inconsistent-return-statements + async def _delete_initial( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -455,39 +412,42 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements _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[None] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - _delete_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore @distributed_trace_async async def begin_delete( @@ -504,14 +464,6 @@ async def begin_delete( :param private_endpoint_connection_name: The name of the private endpoint connection associated with the Cognitive Services Account. Required. :type private_endpoint_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -525,7 +477,7 @@ async def begin_delete( lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( # type: ignore + raw_result = await self._delete_initial( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -535,11 +487,12 @@ async def begin_delete( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) @@ -548,14 +501,10 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_private_link_resources_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_private_link_resources_operations.py index f572e9c349ad..29ee4f4d5b3d 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_private_link_resources_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_private_link_resources_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar +import sys +from typing import Any, Callable, Dict, Optional, Type, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, @@ -17,17 +18,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._private_link_resources_operations import build_list_request -from .._vendor import CognitiveServicesManagementClientMixinABC +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -62,12 +64,11 @@ async def list( :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateLinkResourceListResult or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.PrivateLinkResourceListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -81,21 +82,19 @@ async def list( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PrivateLinkResourceListResult] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -105,13 +104,9 @@ async def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) + deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateLinkResources" - } + return deserialized # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_rai_blocklist_items_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_rai_blocklist_items_operations.py new file mode 100644 index 000000000000..b8594b008c62 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_rai_blocklist_items_operations.py @@ -0,0 +1,749 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import ( + Any, + AsyncIterable, + AsyncIterator, + Callable, + Dict, + IO, + List, + Optional, + Type, + TypeVar, + Union, + cast, + overload, +) +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._rai_blocklist_items_operations import ( + build_batch_add_request, + build_batch_delete_request, + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RaiBlocklistItemsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.aio.CognitiveServicesManagementClient`'s + :attr:`rai_blocklist_items` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, account_name: str, rai_blocklist_name: str, **kwargs: Any + ) -> AsyncIterable["_models.RaiBlocklistItem"]: + """Gets the blocklist items associated with the custom blocklist. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :return: An iterator like instance of either RaiBlocklistItem or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.RaiBlocklistItem] + :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.RaiBlockListItemsResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RaiBlockListItemsResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_item_name: str, + **kwargs: Any + ) -> _models.RaiBlocklistItem: + """Gets the specified custom blocklist Item associated with the custom blocklist. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_item_name: The name of the RaiBlocklist Item associated with the custom + blocklist. Required. + :type rai_blocklist_item_name: str + :return: RaiBlocklistItem or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItem + :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.RaiBlocklistItem] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + rai_blocklist_item_name=rai_blocklist_item_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiBlocklistItem", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_item_name: str, + rai_blocklist_item: _models.RaiBlocklistItem, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiBlocklistItem: + """Update the state of specified blocklist item associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_item_name: The name of the RaiBlocklist Item associated with the custom + blocklist. Required. + :type rai_blocklist_item_name: str + :param rai_blocklist_item: Properties describing the custom blocklist. Required. + :type rai_blocklist_item: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItem + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiBlocklistItem or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItem + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_item_name: str, + rai_blocklist_item: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiBlocklistItem: + """Update the state of specified blocklist item associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_item_name: The name of the RaiBlocklist Item associated with the custom + blocklist. Required. + :type rai_blocklist_item_name: str + :param rai_blocklist_item: Properties describing the custom blocklist. Required. + :type rai_blocklist_item: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiBlocklistItem or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItem + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_item_name: str, + rai_blocklist_item: Union[_models.RaiBlocklistItem, IO[bytes]], + **kwargs: Any + ) -> _models.RaiBlocklistItem: + """Update the state of specified blocklist item associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_item_name: The name of the RaiBlocklist Item associated with the custom + blocklist. Required. + :type rai_blocklist_item_name: str + :param rai_blocklist_item: Properties describing the custom blocklist. Is either a + RaiBlocklistItem type or a IO[bytes] type. Required. + :type rai_blocklist_item: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItem or IO[bytes] + :return: RaiBlocklistItem or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItem + :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 = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RaiBlocklistItem] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(rai_blocklist_item, (IOBase, bytes)): + _content = rai_blocklist_item + else: + _json = self._serialize.body(rai_blocklist_item, "RaiBlocklistItem") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + rai_blocklist_item_name=rai_blocklist_item_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiBlocklistItem", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_item_name: str, + **kwargs: Any + ) -> AsyncIterator[bytes]: + 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[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + rai_blocklist_item_name=rai_blocklist_item_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_item_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the specified blocklist Item associated with the custom blocklist. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_item_name: The name of the RaiBlocklist Item associated with the custom + blocklist. Required. + :type rai_blocklist_item_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :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[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + rai_blocklist_item_name=rai_blocklist_item_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @overload + async def batch_add( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_items: List[_models.RaiBlocklistItemBulkRequest], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiBlocklist: + """Batch operation to add blocklist items. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_items: Properties describing the custom blocklist items. Required. + :type rai_blocklist_items: + list[~azure.mgmt.cognitiveservices.models.RaiBlocklistItemBulkRequest] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiBlocklist or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def batch_add( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_items: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiBlocklist: + """Batch operation to add blocklist items. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_items: Properties describing the custom blocklist items. Required. + :type rai_blocklist_items: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiBlocklist or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def batch_add( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_items: Union[List[_models.RaiBlocklistItemBulkRequest], IO[bytes]], + **kwargs: Any + ) -> _models.RaiBlocklist: + """Batch operation to add blocklist items. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_items: Properties describing the custom blocklist items. Is either a + [RaiBlocklistItemBulkRequest] type or a IO[bytes] type. Required. + :type rai_blocklist_items: + list[~azure.mgmt.cognitiveservices.models.RaiBlocklistItemBulkRequest] or IO[bytes] + :return: RaiBlocklist or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :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 = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RaiBlocklist] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(rai_blocklist_items, (IOBase, bytes)): + _content = rai_blocklist_items + else: + _json = self._serialize.body(rai_blocklist_items, "[RaiBlocklistItemBulkRequest]") + + _request = build_batch_add_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiBlocklist", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def batch_delete( # pylint: disable=inconsistent-return-statements + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_items_names: JSON, + **kwargs: Any + ) -> None: + """Batch operation to delete blocklist items. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_items_names: List of RAI Blocklist Items Names. Required. + :type rai_blocklist_items_names: JSON + :return: None or the result of cls(response) + :rtype: None + :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 = 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", self._config.api_version)) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _json = self._serialize.body(rai_blocklist_items_names, "object") + + _request = build_batch_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_rai_blocklists_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_rai_blocklists_operations.py new file mode 100644 index 000000000000..7382d6fd797f --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_rai_blocklists_operations.py @@ -0,0 +1,473 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._rai_blocklists_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RaiBlocklistsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.aio.CognitiveServicesManagementClient`'s + :attr:`rai_blocklists` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> AsyncIterable["_models.RaiBlocklist"]: + """Gets the custom blocklists associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :return: An iterator like instance of either RaiBlocklist or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.RaiBlocklist] + :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.RaiBlockListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RaiBlockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get( + self, resource_group_name: str, account_name: str, rai_blocklist_name: str, **kwargs: Any + ) -> _models.RaiBlocklist: + """Gets the specified custom blocklist associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :return: RaiBlocklist or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :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.RaiBlocklist] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiBlocklist", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist: _models.RaiBlocklist, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiBlocklist: + """Update the state of specified blocklist associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist: Properties describing the custom blocklist. Required. + :type rai_blocklist: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiBlocklist or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiBlocklist: + """Update the state of specified blocklist associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist: Properties describing the custom blocklist. Required. + :type rai_blocklist: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiBlocklist or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist: Union[_models.RaiBlocklist, IO[bytes]], + **kwargs: Any + ) -> _models.RaiBlocklist: + """Update the state of specified blocklist associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist: Properties describing the custom blocklist. Is either a RaiBlocklist type + or a IO[bytes] type. Required. + :type rai_blocklist: ~azure.mgmt.cognitiveservices.models.RaiBlocklist or IO[bytes] + :return: RaiBlocklist or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :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 = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RaiBlocklist] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(rai_blocklist, (IOBase, bytes)): + _content = rai_blocklist + else: + _json = self._serialize.body(rai_blocklist, "RaiBlocklist") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiBlocklist", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _delete_initial( + self, resource_group_name: str, account_name: str, rai_blocklist_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + 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[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, account_name: str, rai_blocklist_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the specified custom blocklist associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :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[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_rai_content_filters_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_rai_content_filters_operations.py new file mode 100644 index 000000000000..a35659689d30 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_rai_content_filters_operations.py @@ -0,0 +1,191 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ...operations._rai_content_filters_operations import build_get_request, build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RaiContentFiltersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.aio.CognitiveServicesManagementClient`'s + :attr:`rai_content_filters` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, location: str, **kwargs: Any) -> AsyncIterable["_models.RaiContentFilter"]: + """List Content Filters types. + + :param location: Resource location. Required. + :type location: str + :return: An iterator like instance of either RaiContentFilter or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.RaiContentFilter] + :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.RaiContentFilterListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + location=location, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RaiContentFilterListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get(self, location: str, filter_name: str, **kwargs: Any) -> _models.RaiContentFilter: + """Get Content Filters by Name. + + :param location: Resource location. Required. + :type location: str + :param filter_name: The name of the RAI Content Filter. Required. + :type filter_name: str + :return: RaiContentFilter or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiContentFilter + :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.RaiContentFilter] = kwargs.pop("cls", None) + + _request = build_get_request( + location=location, + filter_name=filter_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiContentFilter", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_rai_policies_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_rai_policies_operations.py new file mode 100644 index 000000000000..bf33aae3b66b --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_rai_policies_operations.py @@ -0,0 +1,472 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ...operations._rai_policies_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RaiPoliciesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.aio.CognitiveServicesManagementClient`'s + :attr:`rai_policies` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> AsyncIterable["_models.RaiPolicy"]: + """Gets the content filters associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :return: An iterator like instance of either RaiPolicy or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.RaiPolicy] + :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.RaiPolicyListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RaiPolicyListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get( + self, resource_group_name: str, account_name: str, rai_policy_name: str, **kwargs: Any + ) -> _models.RaiPolicy: + """Gets the specified Content Filters associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_policy_name: The name of the RaiPolicy associated with the Cognitive Services + Account. Required. + :type rai_policy_name: str + :return: RaiPolicy or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiPolicy + :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.RaiPolicy] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_policy_name=rai_policy_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiPolicy", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_policy_name: str, + rai_policy: _models.RaiPolicy, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiPolicy: + """Update the state of specified Content Filters associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_policy_name: The name of the RaiPolicy associated with the Cognitive Services + Account. Required. + :type rai_policy_name: str + :param rai_policy: Properties describing the Content Filters. Required. + :type rai_policy: ~azure.mgmt.cognitiveservices.models.RaiPolicy + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiPolicy or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_policy_name: str, + rai_policy: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiPolicy: + """Update the state of specified Content Filters associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_policy_name: The name of the RaiPolicy associated with the Cognitive Services + Account. Required. + :type rai_policy_name: str + :param rai_policy: Properties describing the Content Filters. Required. + :type rai_policy: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiPolicy or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_policy_name: str, + rai_policy: Union[_models.RaiPolicy, IO[bytes]], + **kwargs: Any + ) -> _models.RaiPolicy: + """Update the state of specified Content Filters associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_policy_name: The name of the RaiPolicy associated with the Cognitive Services + Account. Required. + :type rai_policy_name: str + :param rai_policy: Properties describing the Content Filters. Is either a RaiPolicy type or a + IO[bytes] type. Required. + :type rai_policy: ~azure.mgmt.cognitiveservices.models.RaiPolicy or IO[bytes] + :return: RaiPolicy or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiPolicy + :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 = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RaiPolicy] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(rai_policy, (IOBase, bytes)): + _content = rai_policy + else: + _json = self._serialize.body(rai_policy, "RaiPolicy") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_policy_name=rai_policy_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiPolicy", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _delete_initial( + self, resource_group_name: str, account_name: str, rai_policy_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + 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[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_policy_name=rai_policy_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, account_name: str, rai_policy_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the specified Content Filters associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_policy_name: The name of the RaiPolicy associated with the Cognitive Services + Account. Required. + :type rai_policy_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :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[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + rai_policy_name=rai_policy_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_resource_skus_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_resource_skus_operations.py index 30fa90771446..7e1f28a2e878 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_resource_skus_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_resource_skus_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -19,17 +20,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._resource_skus_operations import build_list_request -from .._vendor import CognitiveServicesManagementClientMixinABC +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -57,7 +59,6 @@ def __init__(self, *args, **kwargs) -> None: def list(self, **kwargs: Any) -> AsyncIterable["_models.ResourceSku"]: """Gets the list of Microsoft.CognitiveServices SKUs available for your Subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ResourceSku or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.ResourceSku] @@ -69,7 +70,7 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.ResourceSku"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ResourceSkuListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -80,15 +81,13 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.ResourceSku"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -100,13 +99,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ResourceSkuListResult", pipeline_response) @@ -116,11 +114,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -132,5 +130,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/skus"} diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_usages_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_usages_operations.py index 87c0837daa99..7e512e322353 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_usages_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/aio/operations/_usages_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -19,17 +20,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request from ...operations._usages_operations import build_list_request -from .._vendor import CognitiveServicesManagementClientMixinABC +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -63,7 +65,6 @@ def list(self, location: str, filter: Optional[str] = None, **kwargs: Any) -> As supported parameter is name.value (name of the metric, can have an or of multiple names). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Usage or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cognitiveservices.models.Usage] :raises ~azure.core.exceptions.HttpResponseError: @@ -74,7 +75,7 @@ def list(self, location: str, filter: Optional[str] = None, **kwargs: Any) -> As api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.UsageListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -85,17 +86,15 @@ def list(self, location: str, filter: Optional[str] = None, **kwargs: Any) -> As def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( location=location, subscription_id=self._config.subscription_id, filter=filter, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -107,13 +106,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("UsageListResult", pipeline_response) @@ -123,11 +121,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -139,7 +137,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/usages" - } diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/models/__init__.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/models/__init__.py index 5b9928198255..db9ddda03068 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/models/__init__.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/models/__init__.py @@ -17,6 +17,10 @@ from ._models_py3 import ApiKeys from ._models_py3 import ApiProperties from ._models_py3 import AzureEntityResource +from ._models_py3 import BillingMeterInfo +from ._models_py3 import CalculateModelCapacityParameter +from ._models_py3 import CalculateModelCapacityResult +from ._models_py3 import CalculateModelCapacityResultEstimatedCapacity from ._models_py3 import CallRateLimit from ._models_py3 import CapacityConfig from ._models_py3 import CheckDomainAvailabilityParameter @@ -32,13 +36,21 @@ from ._models_py3 import CommitmentQuota from ._models_py3 import CommitmentTier from ._models_py3 import CommitmentTierListResult +from ._models_py3 import CustomBlocklistConfig +from ._models_py3 import DefenderForAISetting +from ._models_py3 import DefenderForAISettingResult from ._models_py3 import Deployment +from ._models_py3 import DeploymentCapacitySettings from ._models_py3 import DeploymentListResult from ._models_py3 import DeploymentModel from ._models_py3 import DeploymentProperties from ._models_py3 import DeploymentScaleSettings +from ._models_py3 import DeploymentSkuListResult from ._models_py3 import DomainAvailability from ._models_py3 import Encryption +from ._models_py3 import EncryptionScope +from ._models_py3 import EncryptionScopeListResult +from ._models_py3 import EncryptionScopeProperties from ._models_py3 import ErrorAdditionalInfo from ._models_py3 import ErrorDetail from ._models_py3 import ErrorResponse @@ -47,11 +59,25 @@ from ._models_py3 import KeyVaultProperties from ._models_py3 import MetricName from ._models_py3 import Model +from ._models_py3 import ModelCapacityCalculatorWorkload +from ._models_py3 import ModelCapacityCalculatorWorkloadRequestParam +from ._models_py3 import ModelCapacityListResult +from ._models_py3 import ModelCapacityListResultValueItem from ._models_py3 import ModelDeprecationInfo from ._models_py3 import ModelListResult from ._models_py3 import ModelSku +from ._models_py3 import ModelSkuCapacityProperties from ._models_py3 import MultiRegionSettings from ._models_py3 import NetworkRuleSet +from ._models_py3 import NetworkSecurityPerimeter +from ._models_py3 import NetworkSecurityPerimeterAccessRule +from ._models_py3 import NetworkSecurityPerimeterAccessRuleProperties +from ._models_py3 import NetworkSecurityPerimeterAccessRulePropertiesSubscriptionsItem +from ._models_py3 import NetworkSecurityPerimeterConfiguration +from ._models_py3 import NetworkSecurityPerimeterConfigurationAssociationInfo +from ._models_py3 import NetworkSecurityPerimeterConfigurationList +from ._models_py3 import NetworkSecurityPerimeterConfigurationProperties +from ._models_py3 import NetworkSecurityPerimeterProfileInfo from ._models_py3 import Operation from ._models_py3 import OperationDisplay from ._models_py3 import OperationListResult @@ -65,8 +91,26 @@ from ._models_py3 import PrivateLinkResourceListResult from ._models_py3 import PrivateLinkResourceProperties from ._models_py3 import PrivateLinkServiceConnectionState +from ._models_py3 import ProvisioningIssue +from ._models_py3 import ProvisioningIssueProperties from ._models_py3 import ProxyResource from ._models_py3 import QuotaLimit +from ._models_py3 import RaiBlockListItemsResult +from ._models_py3 import RaiBlockListResult +from ._models_py3 import RaiBlocklist +from ._models_py3 import RaiBlocklistConfig +from ._models_py3 import RaiBlocklistItem +from ._models_py3 import RaiBlocklistItemBulkRequest +from ._models_py3 import RaiBlocklistItemProperties +from ._models_py3 import RaiBlocklistProperties +from ._models_py3 import RaiContentFilter +from ._models_py3 import RaiContentFilterListResult +from ._models_py3 import RaiContentFilterProperties +from ._models_py3 import RaiMonitorConfig +from ._models_py3 import RaiPolicy +from ._models_py3 import RaiPolicyContentFilter +from ._models_py3 import RaiPolicyListResult +from ._models_py3 import RaiPolicyProperties from ._models_py3 import RegenerateKeyParameters from ._models_py3 import RegionSetting from ._models_py3 import RequestMatchPattern @@ -80,32 +124,43 @@ from ._models_py3 import SkuAvailabilityListResult from ._models_py3 import SkuCapability from ._models_py3 import SkuChangeInfo +from ._models_py3 import SkuResource from ._models_py3 import SystemData from ._models_py3 import ThrottlingRule from ._models_py3 import Usage from ._models_py3 import UsageListResult from ._models_py3 import UserAssignedIdentity +from ._models_py3 import UserOwnedAmlWorkspace from ._models_py3 import UserOwnedStorage from ._models_py3 import VirtualNetworkRule from ._cognitive_services_management_client_enums import AbusePenaltyAction from ._cognitive_services_management_client_enums import ActionType +from ._cognitive_services_management_client_enums import ByPassSelection from ._cognitive_services_management_client_enums import CommitmentPlanProvisioningState +from ._cognitive_services_management_client_enums import ContentLevel from ._cognitive_services_management_client_enums import CreatedByType +from ._cognitive_services_management_client_enums import DefenderForAISettingState from ._cognitive_services_management_client_enums import DeploymentModelVersionUpgradeOption from ._cognitive_services_management_client_enums import DeploymentProvisioningState from ._cognitive_services_management_client_enums import DeploymentScaleType +from ._cognitive_services_management_client_enums import EncryptionScopeProvisioningState +from ._cognitive_services_management_client_enums import EncryptionScopeState from ._cognitive_services_management_client_enums import HostingModel from ._cognitive_services_management_client_enums import KeyName from ._cognitive_services_management_client_enums import KeySource from ._cognitive_services_management_client_enums import ModelLifecycleStatus from ._cognitive_services_management_client_enums import NetworkRuleAction +from ._cognitive_services_management_client_enums import NspAccessRuleDirection from ._cognitive_services_management_client_enums import Origin from ._cognitive_services_management_client_enums import PrivateEndpointConnectionProvisioningState from ._cognitive_services_management_client_enums import PrivateEndpointServiceConnectionStatus from ._cognitive_services_management_client_enums import ProvisioningState from ._cognitive_services_management_client_enums import PublicNetworkAccess from ._cognitive_services_management_client_enums import QuotaUsageStatus +from ._cognitive_services_management_client_enums import RaiPolicyContentSource +from ._cognitive_services_management_client_enums import RaiPolicyMode +from ._cognitive_services_management_client_enums import RaiPolicyType from ._cognitive_services_management_client_enums import ResourceIdentityType from ._cognitive_services_management_client_enums import ResourceSkuRestrictionsReasonCode from ._cognitive_services_management_client_enums import ResourceSkuRestrictionsType @@ -128,6 +183,10 @@ "ApiKeys", "ApiProperties", "AzureEntityResource", + "BillingMeterInfo", + "CalculateModelCapacityParameter", + "CalculateModelCapacityResult", + "CalculateModelCapacityResultEstimatedCapacity", "CallRateLimit", "CapacityConfig", "CheckDomainAvailabilityParameter", @@ -143,13 +202,21 @@ "CommitmentQuota", "CommitmentTier", "CommitmentTierListResult", + "CustomBlocklistConfig", + "DefenderForAISetting", + "DefenderForAISettingResult", "Deployment", + "DeploymentCapacitySettings", "DeploymentListResult", "DeploymentModel", "DeploymentProperties", "DeploymentScaleSettings", + "DeploymentSkuListResult", "DomainAvailability", "Encryption", + "EncryptionScope", + "EncryptionScopeListResult", + "EncryptionScopeProperties", "ErrorAdditionalInfo", "ErrorDetail", "ErrorResponse", @@ -158,11 +225,25 @@ "KeyVaultProperties", "MetricName", "Model", + "ModelCapacityCalculatorWorkload", + "ModelCapacityCalculatorWorkloadRequestParam", + "ModelCapacityListResult", + "ModelCapacityListResultValueItem", "ModelDeprecationInfo", "ModelListResult", "ModelSku", + "ModelSkuCapacityProperties", "MultiRegionSettings", "NetworkRuleSet", + "NetworkSecurityPerimeter", + "NetworkSecurityPerimeterAccessRule", + "NetworkSecurityPerimeterAccessRuleProperties", + "NetworkSecurityPerimeterAccessRulePropertiesSubscriptionsItem", + "NetworkSecurityPerimeterConfiguration", + "NetworkSecurityPerimeterConfigurationAssociationInfo", + "NetworkSecurityPerimeterConfigurationList", + "NetworkSecurityPerimeterConfigurationProperties", + "NetworkSecurityPerimeterProfileInfo", "Operation", "OperationDisplay", "OperationListResult", @@ -176,8 +257,26 @@ "PrivateLinkResourceListResult", "PrivateLinkResourceProperties", "PrivateLinkServiceConnectionState", + "ProvisioningIssue", + "ProvisioningIssueProperties", "ProxyResource", "QuotaLimit", + "RaiBlockListItemsResult", + "RaiBlockListResult", + "RaiBlocklist", + "RaiBlocklistConfig", + "RaiBlocklistItem", + "RaiBlocklistItemBulkRequest", + "RaiBlocklistItemProperties", + "RaiBlocklistProperties", + "RaiContentFilter", + "RaiContentFilterListResult", + "RaiContentFilterProperties", + "RaiMonitorConfig", + "RaiPolicy", + "RaiPolicyContentFilter", + "RaiPolicyListResult", + "RaiPolicyProperties", "RegenerateKeyParameters", "RegionSetting", "RequestMatchPattern", @@ -191,31 +290,42 @@ "SkuAvailabilityListResult", "SkuCapability", "SkuChangeInfo", + "SkuResource", "SystemData", "ThrottlingRule", "Usage", "UsageListResult", "UserAssignedIdentity", + "UserOwnedAmlWorkspace", "UserOwnedStorage", "VirtualNetworkRule", "AbusePenaltyAction", "ActionType", + "ByPassSelection", "CommitmentPlanProvisioningState", + "ContentLevel", "CreatedByType", + "DefenderForAISettingState", "DeploymentModelVersionUpgradeOption", "DeploymentProvisioningState", "DeploymentScaleType", + "EncryptionScopeProvisioningState", + "EncryptionScopeState", "HostingModel", "KeyName", "KeySource", "ModelLifecycleStatus", "NetworkRuleAction", + "NspAccessRuleDirection", "Origin", "PrivateEndpointConnectionProvisioningState", "PrivateEndpointServiceConnectionStatus", "ProvisioningState", "PublicNetworkAccess", "QuotaUsageStatus", + "RaiPolicyContentSource", + "RaiPolicyMode", + "RaiPolicyType", "ResourceIdentityType", "ResourceSkuRestrictionsReasonCode", "ResourceSkuRestrictionsType", diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/models/_cognitive_services_management_client_enums.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/models/_cognitive_services_management_client_enums.py index 487963207201..dd6c2d3b7c4d 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/models/_cognitive_services_management_client_enums.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/models/_cognitive_services_management_client_enums.py @@ -23,6 +23,13 @@ class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): INTERNAL = "Internal" +class ByPassSelection(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Setting for trusted services.""" + + NONE = "None" + AZURE_SERVICES = "AzureServices" + + class CommitmentPlanProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Gets the status of the resource at the time the operation was called.""" @@ -35,6 +42,14 @@ class CommitmentPlanProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMe CANCELED = "Canceled" +class ContentLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Level at which content is filtered.""" + + LOW = "Low" + MEDIUM = "Medium" + HIGH = "High" + + class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of identity that created the resource.""" @@ -44,6 +59,13 @@ class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): KEY = "Key" +class DefenderForAISettingState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Defender for AI state on the AI resource.""" + + DISABLED = "Disabled" + ENABLED = "Enabled" + + class DeploymentModelVersionUpgradeOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Deployment model version upgrade option.""" @@ -72,6 +94,25 @@ class DeploymentScaleType(str, Enum, metaclass=CaseInsensitiveEnumMeta): MANUAL = "Manual" +class EncryptionScopeProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Gets the status of the resource at the time the operation was called.""" + + ACCEPTED = "Accepted" + CREATING = "Creating" + DELETING = "Deleting" + MOVING = "Moving" + FAILED = "Failed" + SUCCEEDED = "Succeeded" + CANCELED = "Canceled" + + +class EncryptionScopeState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The encryptionScope state.""" + + DISABLED = "Disabled" + ENABLED = "Enabled" + + class HostingModel(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Account hosting model.""" @@ -98,8 +139,11 @@ class KeySource(str, Enum, metaclass=CaseInsensitiveEnumMeta): class ModelLifecycleStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Model lifecycle status.""" - GENERALLY_AVAILABLE = "GenerallyAvailable" + STABLE = "Stable" PREVIEW = "Preview" + GENERALLY_AVAILABLE = "GenerallyAvailable" + DEPRECATING = "Deprecating" + DEPRECATED = "Deprecated" class NetworkRuleAction(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -111,6 +155,13 @@ class NetworkRuleAction(str, Enum, metaclass=CaseInsensitiveEnumMeta): DENY = "Deny" +class NspAccessRuleDirection(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Direction of Access Rule.""" + + INBOUND = "Inbound" + OUTBOUND = "Outbound" + + class Origin(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is "user,system". @@ -166,6 +217,32 @@ class QuotaUsageStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): UNKNOWN = "Unknown" +class RaiPolicyContentSource(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Content source to apply the Content Filters.""" + + PROMPT = "Prompt" + COMPLETION = "Completion" + + +class RaiPolicyMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Rai policy mode. The enum value mapping is as below: Default = 0, Deferred=1, Blocking=2, + Asynchronous_filter =3. Please use 'Asynchronous_filter' after 2024-10-01. It is the same as + 'Deferred' in previous version. + """ + + DEFAULT = "Default" + DEFERRED = "Deferred" + BLOCKING = "Blocking" + ASYNCHRONOUS_FILTER = "Asynchronous_filter" + + +class RaiPolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Content Filters policy type.""" + + USER_MANAGED = "UserManaged" + SYSTEM_MANAGED = "SystemManaged" + + class ResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The identity type.""" diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/models/_models_py3.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/models/_models_py3.py index e336054b57c8..832cd00a6a3f 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/models/_models_py3.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/models/_models_py3.py @@ -69,7 +69,7 @@ class Resource(_serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -104,7 +104,7 @@ class AzureEntityResource(Resource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -142,7 +142,7 @@ class Account(AzureEntityResource): # pylint: disable=too-many-instance-attribu Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -259,6 +259,8 @@ class DeploymentModel(_serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. + :ivar publisher: Deployment model publisher. + :vartype publisher: str :ivar format: Deployment model format. :vartype format: str :ivar name: Deployment model name. @@ -270,6 +272,9 @@ class DeploymentModel(_serialization.Model): :vartype version: str :ivar source: Optional. Deployment model source ARM resource ID. :vartype source: str + :ivar source_account: Optional. Source of the model, another Microsoft.CognitiveServices + accounts ARM resource ID. + :vartype source_account: str :ivar call_rate_limit: The call rate limit Cognitive Services account. :vartype call_rate_limit: ~azure.mgmt.cognitiveservices.models.CallRateLimit """ @@ -279,23 +284,29 @@ class DeploymentModel(_serialization.Model): } _attribute_map = { + "publisher": {"key": "publisher", "type": "str"}, "format": {"key": "format", "type": "str"}, "name": {"key": "name", "type": "str"}, "version": {"key": "version", "type": "str"}, "source": {"key": "source", "type": "str"}, + "source_account": {"key": "sourceAccount", "type": "str"}, "call_rate_limit": {"key": "callRateLimit", "type": "CallRateLimit"}, } def __init__( self, *, + publisher: Optional[str] = None, format: Optional[str] = None, name: Optional[str] = None, version: Optional[str] = None, source: Optional[str] = None, + source_account: Optional[str] = None, **kwargs: Any ) -> None: """ + :keyword publisher: Deployment model publisher. + :paramtype publisher: str :keyword format: Deployment model format. :paramtype format: str :keyword name: Deployment model name. @@ -307,12 +318,17 @@ def __init__( :paramtype version: str :keyword source: Optional. Deployment model source ARM resource ID. :paramtype source: str + :keyword source_account: Optional. Source of the model, another Microsoft.CognitiveServices + accounts ARM resource ID. + :paramtype source_account: str """ super().__init__(**kwargs) + self.publisher = publisher self.format = format self.name = name self.version = version self.source = source + self.source_account = source_account self.call_rate_limit = None @@ -321,6 +337,8 @@ class AccountModel(DeploymentModel): # pylint: disable=too-many-instance-attrib Variables are only populated by the server, and will be ignored when sending a request. + :ivar publisher: Deployment model publisher. + :vartype publisher: str :ivar format: Deployment model format. :vartype format: str :ivar name: Deployment model name. @@ -332,9 +350,12 @@ class AccountModel(DeploymentModel): # pylint: disable=too-many-instance-attrib :vartype version: str :ivar source: Optional. Deployment model source ARM resource ID. :vartype source: str + :ivar source_account: Optional. Source of the model, another Microsoft.CognitiveServices + accounts ARM resource ID. + :vartype source_account: str :ivar call_rate_limit: The call rate limit Cognitive Services account. :vartype call_rate_limit: ~azure.mgmt.cognitiveservices.models.CallRateLimit - :ivar base_model: Base Model Identifier. + :ivar base_model: Properties of Cognitive Services account deployment model. :vartype base_model: ~azure.mgmt.cognitiveservices.models.DeploymentModel :ivar is_default_version: If the model is default version. :vartype is_default_version: bool @@ -348,8 +369,8 @@ class AccountModel(DeploymentModel): # pylint: disable=too-many-instance-attrib :vartype finetune_capabilities: dict[str, str] :ivar deprecation: Cognitive Services account ModelDeprecationInfo. :vartype deprecation: ~azure.mgmt.cognitiveservices.models.ModelDeprecationInfo - :ivar lifecycle_status: Model lifecycle status. Known values are: "GenerallyAvailable" and - "Preview". + :ivar lifecycle_status: Model lifecycle status. Known values are: "Stable", "Preview", + "GenerallyAvailable", "Deprecating", and "Deprecated". :vartype lifecycle_status: str or ~azure.mgmt.cognitiveservices.models.ModelLifecycleStatus :ivar system_data: Metadata pertaining to creation and last modification of the resource. :vartype system_data: ~azure.mgmt.cognitiveservices.models.SystemData @@ -361,10 +382,12 @@ class AccountModel(DeploymentModel): # pylint: disable=too-many-instance-attrib } _attribute_map = { + "publisher": {"key": "publisher", "type": "str"}, "format": {"key": "format", "type": "str"}, "name": {"key": "name", "type": "str"}, "version": {"key": "version", "type": "str"}, "source": {"key": "source", "type": "str"}, + "source_account": {"key": "sourceAccount", "type": "str"}, "call_rate_limit": {"key": "callRateLimit", "type": "CallRateLimit"}, "base_model": {"key": "baseModel", "type": "DeploymentModel"}, "is_default_version": {"key": "isDefaultVersion", "type": "bool"}, @@ -380,10 +403,12 @@ class AccountModel(DeploymentModel): # pylint: disable=too-many-instance-attrib def __init__( self, *, + publisher: Optional[str] = None, format: Optional[str] = None, name: Optional[str] = None, version: Optional[str] = None, source: Optional[str] = None, + source_account: Optional[str] = None, base_model: Optional["_models.DeploymentModel"] = None, is_default_version: Optional[bool] = None, skus: Optional[List["_models.ModelSku"]] = None, @@ -395,6 +420,8 @@ def __init__( **kwargs: Any ) -> None: """ + :keyword publisher: Deployment model publisher. + :paramtype publisher: str :keyword format: Deployment model format. :paramtype format: str :keyword name: Deployment model name. @@ -406,7 +433,10 @@ def __init__( :paramtype version: str :keyword source: Optional. Deployment model source ARM resource ID. :paramtype source: str - :keyword base_model: Base Model Identifier. + :keyword source_account: Optional. Source of the model, another Microsoft.CognitiveServices + accounts ARM resource ID. + :paramtype source_account: str + :keyword base_model: Properties of Cognitive Services account deployment model. :paramtype base_model: ~azure.mgmt.cognitiveservices.models.DeploymentModel :keyword is_default_version: If the model is default version. :paramtype is_default_version: bool @@ -420,11 +450,19 @@ def __init__( :paramtype finetune_capabilities: dict[str, str] :keyword deprecation: Cognitive Services account ModelDeprecationInfo. :paramtype deprecation: ~azure.mgmt.cognitiveservices.models.ModelDeprecationInfo - :keyword lifecycle_status: Model lifecycle status. Known values are: "GenerallyAvailable" and - "Preview". + :keyword lifecycle_status: Model lifecycle status. Known values are: "Stable", "Preview", + "GenerallyAvailable", "Deprecating", and "Deprecated". :paramtype lifecycle_status: str or ~azure.mgmt.cognitiveservices.models.ModelLifecycleStatus """ - super().__init__(format=format, name=name, version=version, source=source, **kwargs) + super().__init__( + publisher=publisher, + format=format, + name=name, + version=version, + source=source, + source_account=source_account, + **kwargs + ) self.base_model = base_model self.is_default_version = is_default_version self.skus = skus @@ -496,6 +534,8 @@ class AccountProperties(_serialization.Model): # pylint: disable=too-many-insta :vartype encryption: ~azure.mgmt.cognitiveservices.models.Encryption :ivar user_owned_storage: The storage accounts for this resource. :vartype user_owned_storage: list[~azure.mgmt.cognitiveservices.models.UserOwnedStorage] + :ivar aml_workspace: The user owned AML workspace properties. + :vartype aml_workspace: ~azure.mgmt.cognitiveservices.models.UserOwnedAmlWorkspace :ivar private_endpoint_connections: The private endpoint connection associated with the Cognitive Services account. :vartype private_endpoint_connections: @@ -535,6 +575,8 @@ class AccountProperties(_serialization.Model): # pylint: disable=too-many-insta list[~azure.mgmt.cognitiveservices.models.CommitmentPlanAssociation] :ivar abuse_penalty: The abuse penalty. :vartype abuse_penalty: ~azure.mgmt.cognitiveservices.models.AbusePenalty + :ivar rai_monitor_config: Cognitive Services Rai Monitor Config. + :vartype rai_monitor_config: ~azure.mgmt.cognitiveservices.models.RaiMonitorConfig """ _validation = { @@ -567,6 +609,7 @@ class AccountProperties(_serialization.Model): # pylint: disable=too-many-insta "network_acls": {"key": "networkAcls", "type": "NetworkRuleSet"}, "encryption": {"key": "encryption", "type": "Encryption"}, "user_owned_storage": {"key": "userOwnedStorage", "type": "[UserOwnedStorage]"}, + "aml_workspace": {"key": "amlWorkspace", "type": "UserOwnedAmlWorkspace"}, "private_endpoint_connections": {"key": "privateEndpointConnections", "type": "[PrivateEndpointConnection]"}, "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, "api_properties": {"key": "apiProperties", "type": "ApiProperties"}, @@ -584,6 +627,7 @@ class AccountProperties(_serialization.Model): # pylint: disable=too-many-insta "locations": {"key": "locations", "type": "MultiRegionSettings"}, "commitment_plan_associations": {"key": "commitmentPlanAssociations", "type": "[CommitmentPlanAssociation]"}, "abuse_penalty": {"key": "abusePenalty", "type": "AbusePenalty"}, + "rai_monitor_config": {"key": "raiMonitorConfig", "type": "RaiMonitorConfig"}, } def __init__( # pylint: disable=too-many-locals @@ -594,6 +638,7 @@ def __init__( # pylint: disable=too-many-locals network_acls: Optional["_models.NetworkRuleSet"] = None, encryption: Optional["_models.Encryption"] = None, user_owned_storage: Optional[List["_models.UserOwnedStorage"]] = None, + aml_workspace: Optional["_models.UserOwnedAmlWorkspace"] = None, public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, api_properties: Optional["_models.ApiProperties"] = None, dynamic_throttling_enabled: Optional[bool] = None, @@ -602,6 +647,7 @@ def __init__( # pylint: disable=too-many-locals disable_local_auth: Optional[bool] = None, restore: Optional[bool] = None, locations: Optional["_models.MultiRegionSettings"] = None, + rai_monitor_config: Optional["_models.RaiMonitorConfig"] = None, **kwargs: Any ) -> None: """ @@ -616,6 +662,8 @@ def __init__( # pylint: disable=too-many-locals :paramtype encryption: ~azure.mgmt.cognitiveservices.models.Encryption :keyword user_owned_storage: The storage accounts for this resource. :paramtype user_owned_storage: list[~azure.mgmt.cognitiveservices.models.UserOwnedStorage] + :keyword aml_workspace: The user owned AML workspace properties. + :paramtype aml_workspace: ~azure.mgmt.cognitiveservices.models.UserOwnedAmlWorkspace :keyword public_network_access: Whether or not public endpoint access is allowed for this account. Known values are: "Enabled" and "Disabled". :paramtype public_network_access: str or @@ -634,6 +682,8 @@ def __init__( # pylint: disable=too-many-locals :paramtype restore: bool :keyword locations: The multiregion settings of Cognitive Services account. :paramtype locations: ~azure.mgmt.cognitiveservices.models.MultiRegionSettings + :keyword rai_monitor_config: Cognitive Services Rai Monitor Config. + :paramtype rai_monitor_config: ~azure.mgmt.cognitiveservices.models.RaiMonitorConfig """ super().__init__(**kwargs) self.provisioning_state = None @@ -647,6 +697,7 @@ def __init__( # pylint: disable=too-many-locals self.network_acls = network_acls self.encryption = encryption self.user_owned_storage = user_owned_storage + self.aml_workspace = aml_workspace self.private_endpoint_connections = None self.public_network_access = public_network_access self.api_properties = api_properties @@ -664,6 +715,7 @@ def __init__( # pylint: disable=too-many-locals self.locations = locations self.commitment_plan_associations = None self.abuse_penalty = None + self.rai_monitor_config = rai_monitor_config class AccountSku(_serialization.Model): @@ -858,6 +910,147 @@ def __init__( self.website_name = website_name +class BillingMeterInfo(_serialization.Model): + """BillingMeterInfo. + + :ivar name: + :vartype name: str + :ivar meter_id: + :vartype meter_id: str + :ivar unit: + :vartype unit: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "meter_id": {"key": "meterId", "type": "str"}, + "unit": {"key": "unit", "type": "str"}, + } + + def __init__( + self, *, name: Optional[str] = None, meter_id: Optional[str] = None, unit: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword name: + :paramtype name: str + :keyword meter_id: + :paramtype meter_id: str + :keyword unit: + :paramtype unit: str + """ + super().__init__(**kwargs) + self.name = name + self.meter_id = meter_id + self.unit = unit + + +class CalculateModelCapacityParameter(_serialization.Model): + """Calculate Model Capacity parameter. + + :ivar model: Properties of Cognitive Services account deployment model. + :vartype model: ~azure.mgmt.cognitiveservices.models.DeploymentModel + :ivar sku_name: The name of SKU. + :vartype sku_name: str + :ivar workloads: List of Model Capacity Calculator Workload. + :vartype workloads: list[~azure.mgmt.cognitiveservices.models.ModelCapacityCalculatorWorkload] + """ + + _attribute_map = { + "model": {"key": "model", "type": "DeploymentModel"}, + "sku_name": {"key": "skuName", "type": "str"}, + "workloads": {"key": "workloads", "type": "[ModelCapacityCalculatorWorkload]"}, + } + + def __init__( + self, + *, + model: Optional["_models.DeploymentModel"] = None, + sku_name: Optional[str] = None, + workloads: Optional[List["_models.ModelCapacityCalculatorWorkload"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword model: Properties of Cognitive Services account deployment model. + :paramtype model: ~azure.mgmt.cognitiveservices.models.DeploymentModel + :keyword sku_name: The name of SKU. + :paramtype sku_name: str + :keyword workloads: List of Model Capacity Calculator Workload. + :paramtype workloads: + list[~azure.mgmt.cognitiveservices.models.ModelCapacityCalculatorWorkload] + """ + super().__init__(**kwargs) + self.model = model + self.sku_name = sku_name + self.workloads = workloads + + +class CalculateModelCapacityResult(_serialization.Model): + """Calculate Model Capacity result. + + :ivar model: Properties of Cognitive Services account deployment model. + :vartype model: ~azure.mgmt.cognitiveservices.models.DeploymentModel + :ivar sku_name: + :vartype sku_name: str + :ivar estimated_capacity: Model Estimated Capacity. + :vartype estimated_capacity: + ~azure.mgmt.cognitiveservices.models.CalculateModelCapacityResultEstimatedCapacity + """ + + _attribute_map = { + "model": {"key": "model", "type": "DeploymentModel"}, + "sku_name": {"key": "skuName", "type": "str"}, + "estimated_capacity": {"key": "estimatedCapacity", "type": "CalculateModelCapacityResultEstimatedCapacity"}, + } + + def __init__( + self, + *, + model: Optional["_models.DeploymentModel"] = None, + sku_name: Optional[str] = None, + estimated_capacity: Optional["_models.CalculateModelCapacityResultEstimatedCapacity"] = None, + **kwargs: Any + ) -> None: + """ + :keyword model: Properties of Cognitive Services account deployment model. + :paramtype model: ~azure.mgmt.cognitiveservices.models.DeploymentModel + :keyword sku_name: + :paramtype sku_name: str + :keyword estimated_capacity: Model Estimated Capacity. + :paramtype estimated_capacity: + ~azure.mgmt.cognitiveservices.models.CalculateModelCapacityResultEstimatedCapacity + """ + super().__init__(**kwargs) + self.model = model + self.sku_name = sku_name + self.estimated_capacity = estimated_capacity + + +class CalculateModelCapacityResultEstimatedCapacity(_serialization.Model): # pylint: disable=name-too-long + """Model Estimated Capacity. + + :ivar value: + :vartype value: int + :ivar deployable_value: + :vartype deployable_value: int + """ + + _attribute_map = { + "value": {"key": "value", "type": "int"}, + "deployable_value": {"key": "deployableValue", "type": "int"}, + } + + def __init__(self, *, value: Optional[int] = None, deployable_value: Optional[int] = None, **kwargs: Any) -> None: + """ + :keyword value: + :paramtype value: int + :keyword deployable_value: + :paramtype deployable_value: int + """ + super().__init__(**kwargs) + self.value = value + self.deployable_value = deployable_value + + class CallRateLimit(_serialization.Model): """The call rate limit Cognitive Services account. @@ -908,6 +1101,8 @@ class CapacityConfig(_serialization.Model): :vartype step: int :ivar default: The default capacity. :vartype default: int + :ivar allowed_values: The array of allowed values for capacity. + :vartype allowed_values: list[int] """ _attribute_map = { @@ -915,6 +1110,7 @@ class CapacityConfig(_serialization.Model): "maximum": {"key": "maximum", "type": "int"}, "step": {"key": "step", "type": "int"}, "default": {"key": "default", "type": "int"}, + "allowed_values": {"key": "allowedValues", "type": "[int]"}, } def __init__( @@ -924,6 +1120,7 @@ def __init__( maximum: Optional[int] = None, step: Optional[int] = None, default: Optional[int] = None, + allowed_values: Optional[List[int]] = None, **kwargs: Any ) -> None: """ @@ -935,18 +1132,21 @@ def __init__( :paramtype step: int :keyword default: The default capacity. :paramtype default: int + :keyword allowed_values: The array of allowed values for capacity. + :paramtype allowed_values: list[int] """ super().__init__(**kwargs) self.minimum = minimum self.maximum = maximum self.step = step self.default = default + self.allowed_values = allowed_values class CheckDomainAvailabilityParameter(_serialization.Model): """Check Domain availability parameter. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar subdomain_name: The subdomain name to use. Required. :vartype subdomain_name: str @@ -985,11 +1185,11 @@ def __init__(self, *, subdomain_name: str, type: str, kind: Optional[str] = None class CheckSkuAvailabilityParameter(_serialization.Model): """Check SKU availability parameter. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar skus: The SKU of the resource. Required. :vartype skus: list[str] - :ivar kind: The Kind of the resource. Required. + :ivar kind: The kind (type) of cognitive service account. Required. :vartype kind: str :ivar type: The Type of the resource. Required. :vartype type: str @@ -1011,7 +1211,7 @@ def __init__(self, *, skus: List[str], kind: str, type: str, **kwargs: Any) -> N """ :keyword skus: The SKU of the resource. Required. :paramtype skus: list[str] - :keyword kind: The Kind of the resource. Required. + :keyword kind: The kind (type) of cognitive service account. Required. :paramtype kind: str :keyword type: The Type of the resource. Required. :paramtype type: str @@ -1103,7 +1303,7 @@ class ProxyResource(Resource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -1112,22 +1312,6 @@ class ProxyResource(Resource): :vartype type: str """ - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - class CommitmentPlan(ProxyResource): """Cognitive Services account commitment plan. @@ -1135,7 +1319,7 @@ class CommitmentPlan(ProxyResource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -1217,7 +1401,7 @@ class CommitmentPlanAccountAssociation(ProxyResource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -1228,6 +1412,8 @@ class CommitmentPlanAccountAssociation(ProxyResource): :vartype system_data: ~azure.mgmt.cognitiveservices.models.SystemData :ivar etag: Resource Etag. :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] :ivar account_id: The Azure resource id of the account. :vartype account_id: str """ @@ -1246,21 +1432,27 @@ class CommitmentPlanAccountAssociation(ProxyResource): "type": {"key": "type", "type": "str"}, "system_data": {"key": "systemData", "type": "SystemData"}, "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, "account_id": {"key": "properties.accountId", "type": "str"}, } - def __init__(self, *, account_id: Optional[str] = None, **kwargs: Any) -> None: + def __init__( + self, *, tags: Optional[Dict[str, str]] = None, account_id: Optional[str] = None, **kwargs: Any + ) -> None: """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] :keyword account_id: The Azure resource id of the account. :paramtype account_id: str """ super().__init__(**kwargs) self.system_data = None self.etag = None + self.tags = tags self.account_id = account_id -class CommitmentPlanAccountAssociationListResult(_serialization.Model): +class CommitmentPlanAccountAssociationListResult(_serialization.Model): # pylint: disable=name-too-long """The list of cognitive services Commitment Plan Account Association operation response. Variables are only populated by the server, and will be ignored when sending a request. @@ -1566,13 +1758,173 @@ def __init__(self, *, next_link: Optional[str] = None, **kwargs: Any) -> None: self.value = None +class RaiBlocklistConfig(_serialization.Model): + """Azure OpenAI blocklist config. + + :ivar blocklist_name: Name of ContentFilter. + :vartype blocklist_name: str + :ivar blocking: If blocking would occur. + :vartype blocking: bool + """ + + _attribute_map = { + "blocklist_name": {"key": "blocklistName", "type": "str"}, + "blocking": {"key": "blocking", "type": "bool"}, + } + + def __init__(self, *, blocklist_name: Optional[str] = None, blocking: Optional[bool] = None, **kwargs: Any) -> None: + """ + :keyword blocklist_name: Name of ContentFilter. + :paramtype blocklist_name: str + :keyword blocking: If blocking would occur. + :paramtype blocking: bool + """ + super().__init__(**kwargs) + self.blocklist_name = blocklist_name + self.blocking = blocking + + +class CustomBlocklistConfig(RaiBlocklistConfig): + """Gets or sets the source to which filter applies. + + :ivar blocklist_name: Name of ContentFilter. + :vartype blocklist_name: str + :ivar blocking: If blocking would occur. + :vartype blocking: bool + :ivar source: Content source to apply the Content Filters. Known values are: "Prompt" and + "Completion". + :vartype source: str or ~azure.mgmt.cognitiveservices.models.RaiPolicyContentSource + """ + + _attribute_map = { + "blocklist_name": {"key": "blocklistName", "type": "str"}, + "blocking": {"key": "blocking", "type": "bool"}, + "source": {"key": "source", "type": "str"}, + } + + def __init__( + self, + *, + blocklist_name: Optional[str] = None, + blocking: Optional[bool] = None, + source: Optional[Union[str, "_models.RaiPolicyContentSource"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword blocklist_name: Name of ContentFilter. + :paramtype blocklist_name: str + :keyword blocking: If blocking would occur. + :paramtype blocking: bool + :keyword source: Content source to apply the Content Filters. Known values are: "Prompt" and + "Completion". + :paramtype source: str or ~azure.mgmt.cognitiveservices.models.RaiPolicyContentSource + """ + super().__init__(blocklist_name=blocklist_name, blocking=blocking, **kwargs) + self.source = source + + +class DefenderForAISetting(ProxyResource): + """The Defender for AI resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Metadata pertaining to creation and last modification of the resource. + :vartype system_data: ~azure.mgmt.cognitiveservices.models.SystemData + :ivar etag: Resource Etag. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar state: Defender for AI state on the AI resource. Known values are: "Disabled" and + "Enabled". + :vartype state: str or ~azure.mgmt.cognitiveservices.models.DefenderForAISettingState + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "etag": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "state": {"key": "properties.state", "type": "str"}, + } + + def __init__( + self, + *, + tags: Optional[Dict[str, str]] = None, + state: Optional[Union[str, "_models.DefenderForAISettingState"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword state: Defender for AI state on the AI resource. Known values are: "Disabled" and + "Enabled". + :paramtype state: str or ~azure.mgmt.cognitiveservices.models.DefenderForAISettingState + """ + super().__init__(**kwargs) + self.system_data = None + self.etag = None + self.tags = tags + self.state = state + + +class DefenderForAISettingResult(_serialization.Model): + """The list of cognitive services Defender for AI Settings. + + :ivar next_link: The link used to get the next page of Defender for AI Settings. + :vartype next_link: str + :ivar value: The list of Defender for AI Settings. + :vartype value: list[~azure.mgmt.cognitiveservices.models.DefenderForAISetting] + """ + + _attribute_map = { + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[DefenderForAISetting]"}, + } + + def __init__( + self, + *, + next_link: Optional[str] = None, + value: Optional[List["_models.DefenderForAISetting"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword next_link: The link used to get the next page of Defender for AI Settings. + :paramtype next_link: str + :keyword value: The list of Defender for AI Settings. + :paramtype value: list[~azure.mgmt.cognitiveservices.models.DefenderForAISetting] + """ + super().__init__(**kwargs) + self.next_link = next_link + self.value = value + + class Deployment(ProxyResource): """Cognitive Services account deployment. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -1585,6 +1937,8 @@ class Deployment(ProxyResource): :vartype system_data: ~azure.mgmt.cognitiveservices.models.SystemData :ivar etag: Resource Etag. :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] :ivar properties: Properties of Cognitive Services account deployment. :vartype properties: ~azure.mgmt.cognitiveservices.models.DeploymentProperties """ @@ -1604,6 +1958,7 @@ class Deployment(ProxyResource): "sku": {"key": "sku", "type": "Sku"}, "system_data": {"key": "systemData", "type": "SystemData"}, "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, "properties": {"key": "properties", "type": "DeploymentProperties"}, } @@ -1611,12 +1966,15 @@ def __init__( self, *, sku: Optional["_models.Sku"] = None, + tags: Optional[Dict[str, str]] = None, properties: Optional["_models.DeploymentProperties"] = None, **kwargs: Any ) -> None: """ :keyword sku: The resource model definition representing SKU. :paramtype sku: ~azure.mgmt.cognitiveservices.models.Sku + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] :keyword properties: Properties of Cognitive Services account deployment. :paramtype properties: ~azure.mgmt.cognitiveservices.models.DeploymentProperties """ @@ -1624,9 +1982,43 @@ def __init__( self.sku = sku self.system_data = None self.etag = None + self.tags = tags self.properties = properties +class DeploymentCapacitySettings(_serialization.Model): + """Internal use only. + + :ivar designated_capacity: The designated capacity. + :vartype designated_capacity: int + :ivar priority: The priority of this capacity setting. + :vartype priority: int + """ + + _validation = { + "designated_capacity": {"minimum": 0}, + "priority": {"minimum": 0}, + } + + _attribute_map = { + "designated_capacity": {"key": "designatedCapacity", "type": "int"}, + "priority": {"key": "priority", "type": "int"}, + } + + def __init__( + self, *, designated_capacity: Optional[int] = None, priority: Optional[int] = None, **kwargs: Any + ) -> None: + """ + :keyword designated_capacity: The designated capacity. + :paramtype designated_capacity: int + :keyword priority: The priority of this capacity setting. + :paramtype priority: int + """ + super().__init__(**kwargs) + self.designated_capacity = designated_capacity + self.priority = priority + + class DeploymentListResult(_serialization.Model): """The list of cognitive services accounts operation response. @@ -1657,7 +2049,7 @@ def __init__(self, *, next_link: Optional[str] = None, **kwargs: Any) -> None: self.value = None -class DeploymentProperties(_serialization.Model): +class DeploymentProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes """Properties of Cognitive Services account deployment. Variables are only populated by the server, and will be ignored when sending a request. @@ -1669,7 +2061,8 @@ class DeploymentProperties(_serialization.Model): ~azure.mgmt.cognitiveservices.models.DeploymentProvisioningState :ivar model: Properties of Cognitive Services account deployment model. :vartype model: ~azure.mgmt.cognitiveservices.models.DeploymentModel - :ivar scale_settings: Properties of Cognitive Services account deployment model. + :ivar scale_settings: Properties of Cognitive Services account deployment model. (Deprecated, + please use Deployment.sku instead.). :vartype scale_settings: ~azure.mgmt.cognitiveservices.models.DeploymentScaleSettings :ivar capabilities: The capabilities. :vartype capabilities: dict[str, str] @@ -1683,6 +2076,14 @@ class DeploymentProperties(_serialization.Model): "OnceNewDefaultVersionAvailable", "OnceCurrentVersionExpired", and "NoAutoUpgrade". :vartype version_upgrade_option: str or ~azure.mgmt.cognitiveservices.models.DeploymentModelVersionUpgradeOption + :ivar dynamic_throttling_enabled: If the dynamic throttling is enabled. + :vartype dynamic_throttling_enabled: bool + :ivar current_capacity: The current capacity. + :vartype current_capacity: int + :ivar capacity_settings: Internal use only. + :vartype capacity_settings: ~azure.mgmt.cognitiveservices.models.DeploymentCapacitySettings + :ivar parent_deployment_name: The name of parent deployment. + :vartype parent_deployment_name: str """ _validation = { @@ -1690,6 +2091,7 @@ class DeploymentProperties(_serialization.Model): "capabilities": {"readonly": True}, "call_rate_limit": {"readonly": True}, "rate_limits": {"readonly": True}, + "dynamic_throttling_enabled": {"readonly": True}, } _attribute_map = { @@ -1701,6 +2103,10 @@ class DeploymentProperties(_serialization.Model): "call_rate_limit": {"key": "callRateLimit", "type": "CallRateLimit"}, "rate_limits": {"key": "rateLimits", "type": "[ThrottlingRule]"}, "version_upgrade_option": {"key": "versionUpgradeOption", "type": "str"}, + "dynamic_throttling_enabled": {"key": "dynamicThrottlingEnabled", "type": "bool"}, + "current_capacity": {"key": "currentCapacity", "type": "int"}, + "capacity_settings": {"key": "capacitySettings", "type": "DeploymentCapacitySettings"}, + "parent_deployment_name": {"key": "parentDeploymentName", "type": "str"}, } def __init__( @@ -1710,12 +2116,16 @@ def __init__( scale_settings: Optional["_models.DeploymentScaleSettings"] = None, rai_policy_name: Optional[str] = None, version_upgrade_option: Optional[Union[str, "_models.DeploymentModelVersionUpgradeOption"]] = None, + current_capacity: Optional[int] = None, + capacity_settings: Optional["_models.DeploymentCapacitySettings"] = None, + parent_deployment_name: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword model: Properties of Cognitive Services account deployment model. :paramtype model: ~azure.mgmt.cognitiveservices.models.DeploymentModel :keyword scale_settings: Properties of Cognitive Services account deployment model. + (Deprecated, please use Deployment.sku instead.). :paramtype scale_settings: ~azure.mgmt.cognitiveservices.models.DeploymentScaleSettings :keyword rai_policy_name: The name of RAI policy. :paramtype rai_policy_name: str @@ -1723,6 +2133,12 @@ def __init__( "OnceNewDefaultVersionAvailable", "OnceCurrentVersionExpired", and "NoAutoUpgrade". :paramtype version_upgrade_option: str or ~azure.mgmt.cognitiveservices.models.DeploymentModelVersionUpgradeOption + :keyword current_capacity: The current capacity. + :paramtype current_capacity: int + :keyword capacity_settings: Internal use only. + :paramtype capacity_settings: ~azure.mgmt.cognitiveservices.models.DeploymentCapacitySettings + :keyword parent_deployment_name: The name of parent deployment. + :paramtype parent_deployment_name: str """ super().__init__(**kwargs) self.provisioning_state = None @@ -1733,10 +2149,15 @@ def __init__( self.call_rate_limit = None self.rate_limits = None self.version_upgrade_option = version_upgrade_option + self.dynamic_throttling_enabled = None + self.current_capacity = current_capacity + self.capacity_settings = capacity_settings + self.parent_deployment_name = parent_deployment_name class DeploymentScaleSettings(_serialization.Model): - """Properties of Cognitive Services account deployment model. + """Properties of Cognitive Services account deployment model. (Deprecated, please use + Deployment.sku instead.). Variables are only populated by the server, and will be ignored when sending a request. @@ -1778,19 +2199,49 @@ def __init__( self.active_capacity = None -class DomainAvailability(_serialization.Model): - """Domain availability. +class DeploymentSkuListResult(_serialization.Model): + """The list of cognitive services accounts operation response. - :ivar is_subdomain_available: Indicates the given SKU is available or not. - :vartype is_subdomain_available: bool - :ivar reason: Reason why the SKU is not available. - :vartype reason: str - :ivar subdomain_name: The subdomain name to use. - :vartype subdomain_name: str - :ivar type: The Type of the resource. - :vartype type: str - :ivar kind: The Kind of the resource. - :vartype kind: str + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar next_link: The link used to get the next page of deployment skus. + :vartype next_link: str + :ivar value: Gets the list of Cognitive Services accounts deployment skus. + :vartype value: list[~azure.mgmt.cognitiveservices.models.SkuResource] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[SkuResource]"}, + } + + def __init__(self, *, next_link: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword next_link: The link used to get the next page of deployment skus. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.next_link = next_link + self.value = None + + +class DomainAvailability(_serialization.Model): + """Domain availability. + + :ivar is_subdomain_available: Indicates the given SKU is available or not. + :vartype is_subdomain_available: bool + :ivar reason: Reason why the SKU is not available. + :vartype reason: str + :ivar subdomain_name: The subdomain name to use. + :vartype subdomain_name: str + :ivar type: The Type of the resource. + :vartype type: str + :ivar kind: The Kind of the resource. + :vartype kind: str """ _attribute_map = { @@ -1865,6 +2316,147 @@ def __init__( self.key_source = key_source +class EncryptionScope(ProxyResource): + """Cognitive Services EncryptionScope. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Metadata pertaining to creation and last modification of the resource. + :vartype system_data: ~azure.mgmt.cognitiveservices.models.SystemData + :ivar etag: Resource Etag. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar properties: Properties of Cognitive Services EncryptionScope. + :vartype properties: ~azure.mgmt.cognitiveservices.models.EncryptionScopeProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "etag": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "properties": {"key": "properties", "type": "EncryptionScopeProperties"}, + } + + def __init__( + self, + *, + tags: Optional[Dict[str, str]] = None, + properties: Optional["_models.EncryptionScopeProperties"] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword properties: Properties of Cognitive Services EncryptionScope. + :paramtype properties: ~azure.mgmt.cognitiveservices.models.EncryptionScopeProperties + """ + super().__init__(**kwargs) + self.system_data = None + self.etag = None + self.tags = tags + self.properties = properties + + +class EncryptionScopeListResult(_serialization.Model): + """The list of cognitive services EncryptionScopes. + + :ivar next_link: The link used to get the next page of EncryptionScope. + :vartype next_link: str + :ivar value: The list of EncryptionScope. + :vartype value: list[~azure.mgmt.cognitiveservices.models.EncryptionScope] + """ + + _attribute_map = { + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[EncryptionScope]"}, + } + + def __init__( + self, *, next_link: Optional[str] = None, value: Optional[List["_models.EncryptionScope"]] = None, **kwargs: Any + ) -> None: + """ + :keyword next_link: The link used to get the next page of EncryptionScope. + :paramtype next_link: str + :keyword value: The list of EncryptionScope. + :paramtype value: list[~azure.mgmt.cognitiveservices.models.EncryptionScope] + """ + super().__init__(**kwargs) + self.next_link = next_link + self.value = value + + +class EncryptionScopeProperties(Encryption): + """Properties to EncryptionScope. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar key_vault_properties: Properties of KeyVault. + :vartype key_vault_properties: ~azure.mgmt.cognitiveservices.models.KeyVaultProperties + :ivar key_source: Enumerates the possible value of keySource for Encryption. Known values are: + "Microsoft.CognitiveServices" and "Microsoft.KeyVault". + :vartype key_source: str or ~azure.mgmt.cognitiveservices.models.KeySource + :ivar provisioning_state: Gets the status of the resource at the time the operation was called. + Known values are: "Accepted", "Creating", "Deleting", "Moving", "Failed", "Succeeded", and + "Canceled". + :vartype provisioning_state: str or + ~azure.mgmt.cognitiveservices.models.EncryptionScopeProvisioningState + :ivar state: The encryptionScope state. Known values are: "Disabled" and "Enabled". + :vartype state: str or ~azure.mgmt.cognitiveservices.models.EncryptionScopeState + """ + + _validation = { + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "key_vault_properties": {"key": "keyVaultProperties", "type": "KeyVaultProperties"}, + "key_source": {"key": "keySource", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "state": {"key": "state", "type": "str"}, + } + + def __init__( + self, + *, + key_vault_properties: Optional["_models.KeyVaultProperties"] = None, + key_source: Union[str, "_models.KeySource"] = "Microsoft.KeyVault", + state: Optional[Union[str, "_models.EncryptionScopeState"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword key_vault_properties: Properties of KeyVault. + :paramtype key_vault_properties: ~azure.mgmt.cognitiveservices.models.KeyVaultProperties + :keyword key_source: Enumerates the possible value of keySource for Encryption. Known values + are: "Microsoft.CognitiveServices" and "Microsoft.KeyVault". + :paramtype key_source: str or ~azure.mgmt.cognitiveservices.models.KeySource + :keyword state: The encryptionScope state. Known values are: "Disabled" and "Enabled". + :paramtype state: str or ~azure.mgmt.cognitiveservices.models.EncryptionScopeState + """ + super().__init__(key_vault_properties=key_vault_properties, key_source=key_source, **kwargs) + self.provisioning_state = None + self.state = state + + class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. @@ -1971,7 +2563,7 @@ class Identity(_serialization.Model): :vartype principal_id: str :ivar user_assigned_identities: The list of user assigned identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. # pylint: disable=line-too-long :vartype user_assigned_identities: dict[str, ~azure.mgmt.cognitiveservices.models.UserAssignedIdentity] """ @@ -2001,7 +2593,7 @@ def __init__( :paramtype type: str or ~azure.mgmt.cognitiveservices.models.ResourceIdentityType :keyword user_assigned_identities: The list of user assigned identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. # pylint: disable=line-too-long :paramtype user_assigned_identities: dict[str, ~azure.mgmt.cognitiveservices.models.UserAssignedIdentity] """ @@ -2015,7 +2607,7 @@ def __init__( class IpRule(_serialization.Model): """A rule governing the accessibility from a specific ip address or ip range. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar value: An IPv4 address range in CIDR notation, such as '124.56.78.91' (simple IP address) or '124.56.78.0/24' (all addresses that start with 124.56.78). Required. @@ -2115,18 +2707,21 @@ def __init__(self, *, value: Optional[str] = None, localized_value: Optional[str class Model(_serialization.Model): """Cognitive Services Model. - :ivar model: Model Metadata. + :ivar model: Cognitive Services account Model. :vartype model: ~azure.mgmt.cognitiveservices.models.AccountModel - :ivar kind: The Kind of the Model. + :ivar kind: The kind (type) of cognitive service account. :vartype kind: str - :ivar sku_name: The SKU of the Model. + :ivar sku_name: The name of SKU. :vartype sku_name: str + :ivar description: The description of the model. + :vartype description: str """ _attribute_map = { "model": {"key": "model", "type": "AccountModel"}, "kind": {"key": "kind", "type": "str"}, "sku_name": {"key": "skuName", "type": "str"}, + "description": {"key": "description", "type": "str"}, } def __init__( @@ -2135,20 +2730,169 @@ def __init__( model: Optional["_models.AccountModel"] = None, kind: Optional[str] = None, sku_name: Optional[str] = None, + description: Optional[str] = None, **kwargs: Any ) -> None: """ - :keyword model: Model Metadata. + :keyword model: Cognitive Services account Model. :paramtype model: ~azure.mgmt.cognitiveservices.models.AccountModel - :keyword kind: The Kind of the Model. + :keyword kind: The kind (type) of cognitive service account. :paramtype kind: str - :keyword sku_name: The SKU of the Model. + :keyword sku_name: The name of SKU. :paramtype sku_name: str + :keyword description: The description of the model. + :paramtype description: str """ super().__init__(**kwargs) self.model = model self.kind = kind self.sku_name = sku_name + self.description = description + + +class ModelCapacityCalculatorWorkload(_serialization.Model): + """Model Capacity Calculator Workload. + + :ivar request_per_minute: Request per minute. + :vartype request_per_minute: int + :ivar request_parameters: Dictionary, Model Capacity Calculator Workload Parameters. + :vartype request_parameters: + ~azure.mgmt.cognitiveservices.models.ModelCapacityCalculatorWorkloadRequestParam + """ + + _attribute_map = { + "request_per_minute": {"key": "requestPerMinute", "type": "int"}, + "request_parameters": {"key": "requestParameters", "type": "ModelCapacityCalculatorWorkloadRequestParam"}, + } + + def __init__( + self, + *, + request_per_minute: Optional[int] = None, + request_parameters: Optional["_models.ModelCapacityCalculatorWorkloadRequestParam"] = None, + **kwargs: Any + ) -> None: + """ + :keyword request_per_minute: Request per minute. + :paramtype request_per_minute: int + :keyword request_parameters: Dictionary, Model Capacity Calculator Workload Parameters. + :paramtype request_parameters: + ~azure.mgmt.cognitiveservices.models.ModelCapacityCalculatorWorkloadRequestParam + """ + super().__init__(**kwargs) + self.request_per_minute = request_per_minute + self.request_parameters = request_parameters + + +class ModelCapacityCalculatorWorkloadRequestParam(_serialization.Model): # pylint: disable=name-too-long + """Dictionary, Model Capacity Calculator Workload Parameters. + + :ivar avg_prompt_tokens: Average prompt tokens. + :vartype avg_prompt_tokens: int + :ivar avg_generated_tokens: Average generated tokens. + :vartype avg_generated_tokens: int + """ + + _attribute_map = { + "avg_prompt_tokens": {"key": "avgPromptTokens", "type": "int"}, + "avg_generated_tokens": {"key": "avgGeneratedTokens", "type": "int"}, + } + + def __init__( + self, *, avg_prompt_tokens: Optional[int] = None, avg_generated_tokens: Optional[int] = None, **kwargs: Any + ) -> None: + """ + :keyword avg_prompt_tokens: Average prompt tokens. + :paramtype avg_prompt_tokens: int + :keyword avg_generated_tokens: Average generated tokens. + :paramtype avg_generated_tokens: int + """ + super().__init__(**kwargs) + self.avg_prompt_tokens = avg_prompt_tokens + self.avg_generated_tokens = avg_generated_tokens + + +class ModelCapacityListResult(_serialization.Model): + """The list of cognitive services accounts operation response. + + :ivar next_link: The link used to get the next page of ModelSkuCapacity. + :vartype next_link: str + :ivar value: Gets the list of Cognitive Services accounts ModelSkuCapacity. + :vartype value: list[~azure.mgmt.cognitiveservices.models.ModelCapacityListResultValueItem] + """ + + _attribute_map = { + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[ModelCapacityListResultValueItem]"}, + } + + def __init__( + self, + *, + next_link: Optional[str] = None, + value: Optional[List["_models.ModelCapacityListResultValueItem"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword next_link: The link used to get the next page of ModelSkuCapacity. + :paramtype next_link: str + :keyword value: Gets the list of Cognitive Services accounts ModelSkuCapacity. + :paramtype value: list[~azure.mgmt.cognitiveservices.models.ModelCapacityListResultValueItem] + """ + super().__init__(**kwargs) + self.next_link = next_link + self.value = value + + +class ModelCapacityListResultValueItem(ProxyResource): + """ModelCapacityListResultValueItem. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar location: The location of the Model Sku Capacity. + :vartype location: str + :ivar properties: Cognitive Services account ModelSkuCapacity. + :vartype properties: ~azure.mgmt.cognitiveservices.models.ModelSkuCapacityProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "properties": {"key": "properties", "type": "ModelSkuCapacityProperties"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + properties: Optional["_models.ModelSkuCapacityProperties"] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: The location of the Model Sku Capacity. + :paramtype location: str + :keyword properties: Cognitive Services account ModelSkuCapacity. + :paramtype properties: ~azure.mgmt.cognitiveservices.models.ModelSkuCapacityProperties + """ + super().__init__(**kwargs) + self.location = location + self.properties = properties class ModelDeprecationInfo(_serialization.Model): @@ -2218,6 +2962,8 @@ class ModelSku(_serialization.Model): :vartype capacity: ~azure.mgmt.cognitiveservices.models.CapacityConfig :ivar rate_limits: The list of rateLimit. :vartype rate_limits: list[~azure.mgmt.cognitiveservices.models.CallRateLimit] + :ivar cost: The list of billing meter info. + :vartype cost: list[~azure.mgmt.cognitiveservices.models.BillingMeterInfo] """ _attribute_map = { @@ -2226,6 +2972,7 @@ class ModelSku(_serialization.Model): "deprecation_date": {"key": "deprecationDate", "type": "iso-8601"}, "capacity": {"key": "capacity", "type": "CapacityConfig"}, "rate_limits": {"key": "rateLimits", "type": "[CallRateLimit]"}, + "cost": {"key": "cost", "type": "[BillingMeterInfo]"}, } def __init__( @@ -2236,6 +2983,7 @@ def __init__( deprecation_date: Optional[datetime.datetime] = None, capacity: Optional["_models.CapacityConfig"] = None, rate_limits: Optional[List["_models.CallRateLimit"]] = None, + cost: Optional[List["_models.BillingMeterInfo"]] = None, **kwargs: Any ) -> None: """ @@ -2249,6 +2997,8 @@ def __init__( :paramtype capacity: ~azure.mgmt.cognitiveservices.models.CapacityConfig :keyword rate_limits: The list of rateLimit. :paramtype rate_limits: list[~azure.mgmt.cognitiveservices.models.CallRateLimit] + :keyword cost: The list of billing meter info. + :paramtype cost: list[~azure.mgmt.cognitiveservices.models.BillingMeterInfo] """ super().__init__(**kwargs) self.name = name @@ -2256,21 +3006,70 @@ def __init__( self.deprecation_date = deprecation_date self.capacity = capacity self.rate_limits = rate_limits + self.cost = cost -class MultiRegionSettings(_serialization.Model): - """The multiregion settings Cognitive Services account. +class ModelSkuCapacityProperties(_serialization.Model): + """Cognitive Services account ModelSkuCapacity. - :ivar routing_method: Multiregion routing methods. Known values are: "Priority", "Weighted", - and "Performance". - :vartype routing_method: str or ~azure.mgmt.cognitiveservices.models.RoutingMethods - :ivar regions: - :vartype regions: list[~azure.mgmt.cognitiveservices.models.RegionSetting] + :ivar model: Properties of Cognitive Services account deployment model. + :vartype model: ~azure.mgmt.cognitiveservices.models.DeploymentModel + :ivar sku_name: + :vartype sku_name: str + :ivar available_capacity: The available capacity for deployment with this model and sku. + :vartype available_capacity: float + :ivar available_finetune_capacity: The available capacity for deployment with a fine-tune + version of this model and sku. + :vartype available_finetune_capacity: float """ _attribute_map = { - "routing_method": {"key": "routingMethod", "type": "str"}, - "regions": {"key": "regions", "type": "[RegionSetting]"}, + "model": {"key": "model", "type": "DeploymentModel"}, + "sku_name": {"key": "skuName", "type": "str"}, + "available_capacity": {"key": "availableCapacity", "type": "float"}, + "available_finetune_capacity": {"key": "availableFinetuneCapacity", "type": "float"}, + } + + def __init__( + self, + *, + model: Optional["_models.DeploymentModel"] = None, + sku_name: Optional[str] = None, + available_capacity: Optional[float] = None, + available_finetune_capacity: Optional[float] = None, + **kwargs: Any + ) -> None: + """ + :keyword model: Properties of Cognitive Services account deployment model. + :paramtype model: ~azure.mgmt.cognitiveservices.models.DeploymentModel + :keyword sku_name: + :paramtype sku_name: str + :keyword available_capacity: The available capacity for deployment with this model and sku. + :paramtype available_capacity: float + :keyword available_finetune_capacity: The available capacity for deployment with a fine-tune + version of this model and sku. + :paramtype available_finetune_capacity: float + """ + super().__init__(**kwargs) + self.model = model + self.sku_name = sku_name + self.available_capacity = available_capacity + self.available_finetune_capacity = available_finetune_capacity + + +class MultiRegionSettings(_serialization.Model): + """The multiregion settings Cognitive Services account. + + :ivar routing_method: Multiregion routing methods. Known values are: "Priority", "Weighted", + and "Performance". + :vartype routing_method: str or ~azure.mgmt.cognitiveservices.models.RoutingMethods + :ivar regions: + :vartype regions: list[~azure.mgmt.cognitiveservices.models.RegionSetting] + """ + + _attribute_map = { + "routing_method": {"key": "routingMethod", "type": "str"}, + "regions": {"key": "regions", "type": "[RegionSetting]"}, } def __init__( @@ -2299,6 +3098,8 @@ class NetworkRuleSet(_serialization.Model): match. This is only used after the bypass property has been evaluated. Known values are: "Allow" and "Deny". :vartype default_action: str or ~azure.mgmt.cognitiveservices.models.NetworkRuleAction + :ivar bypass: Setting for trusted services. Known values are: "None" and "AzureServices". + :vartype bypass: str or ~azure.mgmt.cognitiveservices.models.ByPassSelection :ivar ip_rules: The list of IP address rules. :vartype ip_rules: list[~azure.mgmt.cognitiveservices.models.IpRule] :ivar virtual_network_rules: The list of virtual network rules. @@ -2307,6 +3108,7 @@ class NetworkRuleSet(_serialization.Model): _attribute_map = { "default_action": {"key": "defaultAction", "type": "str"}, + "bypass": {"key": "bypass", "type": "str"}, "ip_rules": {"key": "ipRules", "type": "[IpRule]"}, "virtual_network_rules": {"key": "virtualNetworkRules", "type": "[VirtualNetworkRule]"}, } @@ -2315,6 +3117,7 @@ def __init__( self, *, default_action: Optional[Union[str, "_models.NetworkRuleAction"]] = None, + bypass: Optional[Union[str, "_models.ByPassSelection"]] = None, ip_rules: Optional[List["_models.IpRule"]] = None, virtual_network_rules: Optional[List["_models.VirtualNetworkRule"]] = None, **kwargs: Any @@ -2324,6 +3127,8 @@ def __init__( virtualNetworkRules match. This is only used after the bypass property has been evaluated. Known values are: "Allow" and "Deny". :paramtype default_action: str or ~azure.mgmt.cognitiveservices.models.NetworkRuleAction + :keyword bypass: Setting for trusted services. Known values are: "None" and "AzureServices". + :paramtype bypass: str or ~azure.mgmt.cognitiveservices.models.ByPassSelection :keyword ip_rules: The list of IP address rules. :paramtype ip_rules: list[~azure.mgmt.cognitiveservices.models.IpRule] :keyword virtual_network_rules: The list of virtual network rules. @@ -2331,10 +3136,388 @@ def __init__( """ super().__init__(**kwargs) self.default_action = default_action + self.bypass = bypass self.ip_rules = ip_rules self.virtual_network_rules = virtual_network_rules +class NetworkSecurityPerimeter(_serialization.Model): + """Information about a linked Network Security Perimeter. + + :ivar id: Fully qualified identifier of the resource. + :vartype id: str + :ivar perimeter_guid: Guid of the resource. + :vartype perimeter_guid: str + :ivar location: Location of the resource. + :vartype location: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "perimeter_guid": {"key": "perimeterGuid", "type": "str"}, + "location": {"key": "location", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + perimeter_guid: Optional[str] = None, + location: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Fully qualified identifier of the resource. + :paramtype id: str + :keyword perimeter_guid: Guid of the resource. + :paramtype perimeter_guid: str + :keyword location: Location of the resource. + :paramtype location: str + """ + super().__init__(**kwargs) + self.id = id + self.perimeter_guid = perimeter_guid + self.location = location + + +class NetworkSecurityPerimeterAccessRule(_serialization.Model): + """Network Security Perimeter Access Rule. + + :ivar name: Network Security Perimeter Access Rule Name. + :vartype name: str + :ivar properties: Properties of Network Security Perimeter Access Rule. + :vartype properties: + ~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterAccessRuleProperties + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "properties": {"key": "properties", "type": "NetworkSecurityPerimeterAccessRuleProperties"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + properties: Optional["_models.NetworkSecurityPerimeterAccessRuleProperties"] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: Network Security Perimeter Access Rule Name. + :paramtype name: str + :keyword properties: Properties of Network Security Perimeter Access Rule. + :paramtype properties: + ~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterAccessRuleProperties + """ + super().__init__(**kwargs) + self.name = name + self.properties = properties + + +class NetworkSecurityPerimeterAccessRuleProperties(_serialization.Model): # pylint: disable=name-too-long + """The Properties of Network Security Perimeter Rule. + + :ivar direction: Direction of Access Rule. Known values are: "Inbound" and "Outbound". + :vartype direction: str or ~azure.mgmt.cognitiveservices.models.NspAccessRuleDirection + :ivar address_prefixes: Address prefixes for inbound rules. + :vartype address_prefixes: list[str] + :ivar subscriptions: Subscriptions for inbound rules. + :vartype subscriptions: + list[~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterAccessRulePropertiesSubscriptionsItem] + :ivar network_security_perimeters: NetworkSecurityPerimeters for inbound rules. + :vartype network_security_perimeters: + list[~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeter] + :ivar fully_qualified_domain_names: Fully qualified domain name for outbound rules. + :vartype fully_qualified_domain_names: list[str] + """ + + _attribute_map = { + "direction": {"key": "direction", "type": "str"}, + "address_prefixes": {"key": "addressPrefixes", "type": "[str]"}, + "subscriptions": { + "key": "subscriptions", + "type": "[NetworkSecurityPerimeterAccessRulePropertiesSubscriptionsItem]", + }, + "network_security_perimeters": {"key": "networkSecurityPerimeters", "type": "[NetworkSecurityPerimeter]"}, + "fully_qualified_domain_names": {"key": "fullyQualifiedDomainNames", "type": "[str]"}, + } + + def __init__( + self, + *, + direction: Optional[Union[str, "_models.NspAccessRuleDirection"]] = None, + address_prefixes: Optional[List[str]] = None, + subscriptions: Optional[List["_models.NetworkSecurityPerimeterAccessRulePropertiesSubscriptionsItem"]] = None, + network_security_perimeters: Optional[List["_models.NetworkSecurityPerimeter"]] = None, + fully_qualified_domain_names: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword direction: Direction of Access Rule. Known values are: "Inbound" and "Outbound". + :paramtype direction: str or ~azure.mgmt.cognitiveservices.models.NspAccessRuleDirection + :keyword address_prefixes: Address prefixes for inbound rules. + :paramtype address_prefixes: list[str] + :keyword subscriptions: Subscriptions for inbound rules. + :paramtype subscriptions: + list[~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterAccessRulePropertiesSubscriptionsItem] + :keyword network_security_perimeters: NetworkSecurityPerimeters for inbound rules. + :paramtype network_security_perimeters: + list[~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeter] + :keyword fully_qualified_domain_names: Fully qualified domain name for outbound rules. + :paramtype fully_qualified_domain_names: list[str] + """ + super().__init__(**kwargs) + self.direction = direction + self.address_prefixes = address_prefixes + self.subscriptions = subscriptions + self.network_security_perimeters = network_security_perimeters + self.fully_qualified_domain_names = fully_qualified_domain_names + + +class NetworkSecurityPerimeterAccessRulePropertiesSubscriptionsItem( + _serialization.Model +): # pylint: disable=name-too-long + """Subscription for inbound rule. + + :ivar id: Fully qualified identifier of subscription. + :vartype id: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + } + + def __init__(self, *, id: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword id: Fully qualified identifier of subscription. + :paramtype id: str + """ + super().__init__(**kwargs) + self.id = id + + +class NetworkSecurityPerimeterConfiguration(ProxyResource): + """NSP Configuration for an Cognitive Services account. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar properties: NSP Configuration properties. + :vartype properties: + ~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterConfigurationProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "NetworkSecurityPerimeterConfigurationProperties"}, + } + + def __init__( + self, *, properties: Optional["_models.NetworkSecurityPerimeterConfigurationProperties"] = None, **kwargs: Any + ) -> None: + """ + :keyword properties: NSP Configuration properties. + :paramtype properties: + ~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterConfigurationProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class NetworkSecurityPerimeterConfigurationAssociationInfo(_serialization.Model): # pylint: disable=name-too-long + """Network Security Perimeter Configuration Association Information. + + :ivar name: Name of the resource association. + :vartype name: str + :ivar access_mode: Access Mode of the resource association. + :vartype access_mode: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "access_mode": {"key": "accessMode", "type": "str"}, + } + + def __init__(self, *, name: Optional[str] = None, access_mode: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword name: Name of the resource association. + :paramtype name: str + :keyword access_mode: Access Mode of the resource association. + :paramtype access_mode: str + """ + super().__init__(**kwargs) + self.name = name + self.access_mode = access_mode + + +class NetworkSecurityPerimeterConfigurationList(_serialization.Model): # pylint: disable=name-too-long + """A list of NSP configurations for an Cognitive Services account. + + :ivar value: Array of NSP configurations List Result for an Cognitive Services account. + :vartype value: + list[~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterConfiguration] + :ivar next_link: Link to retrieve next page of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[NetworkSecurityPerimeterConfiguration]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.NetworkSecurityPerimeterConfiguration"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: Array of NSP configurations List Result for an Cognitive Services account. + :paramtype value: + list[~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterConfiguration] + :keyword next_link: Link to retrieve next page of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class NetworkSecurityPerimeterConfigurationProperties(_serialization.Model): # pylint: disable=name-too-long + """The properties of an NSP Configuration. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provisioning_state: Provisioning state of NetworkSecurityPerimeter configuration. + :vartype provisioning_state: str + :ivar provisioning_issues: List of Provisioning Issues. + :vartype provisioning_issues: list[~azure.mgmt.cognitiveservices.models.ProvisioningIssue] + :ivar network_security_perimeter: Information about a linked Network Security Perimeter. + :vartype network_security_perimeter: + ~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeter + :ivar resource_association: Network Security Perimeter Configuration Association Information. + :vartype resource_association: + ~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterConfigurationAssociationInfo + :ivar profile: Network Security Perimeter Profile Information. + :vartype profile: ~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterProfileInfo + """ + + _validation = { + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "provisioning_issues": {"key": "provisioningIssues", "type": "[ProvisioningIssue]"}, + "network_security_perimeter": {"key": "networkSecurityPerimeter", "type": "NetworkSecurityPerimeter"}, + "resource_association": { + "key": "resourceAssociation", + "type": "NetworkSecurityPerimeterConfigurationAssociationInfo", + }, + "profile": {"key": "profile", "type": "NetworkSecurityPerimeterProfileInfo"}, + } + + def __init__( + self, + *, + provisioning_issues: Optional[List["_models.ProvisioningIssue"]] = None, + network_security_perimeter: Optional["_models.NetworkSecurityPerimeter"] = None, + resource_association: Optional["_models.NetworkSecurityPerimeterConfigurationAssociationInfo"] = None, + profile: Optional["_models.NetworkSecurityPerimeterProfileInfo"] = None, + **kwargs: Any + ) -> None: + """ + :keyword provisioning_issues: List of Provisioning Issues. + :paramtype provisioning_issues: list[~azure.mgmt.cognitiveservices.models.ProvisioningIssue] + :keyword network_security_perimeter: Information about a linked Network Security Perimeter. + :paramtype network_security_perimeter: + ~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeter + :keyword resource_association: Network Security Perimeter Configuration Association + Information. + :paramtype resource_association: + ~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterConfigurationAssociationInfo + :keyword profile: Network Security Perimeter Profile Information. + :paramtype profile: ~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterProfileInfo + """ + super().__init__(**kwargs) + self.provisioning_state = None + self.provisioning_issues = provisioning_issues + self.network_security_perimeter = network_security_perimeter + self.resource_association = resource_association + self.profile = profile + + +class NetworkSecurityPerimeterProfileInfo(_serialization.Model): + """Network Security Perimeter Profile Information. + + :ivar name: Name of the resource profile. + :vartype name: str + :ivar access_rules_version: Access rules version of the resource profile. + :vartype access_rules_version: int + :ivar access_rules: + :vartype access_rules: + list[~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterAccessRule] + :ivar diagnostic_settings_version: Current diagnostic settings version. + :vartype diagnostic_settings_version: int + :ivar enabled_log_categories: List of enabled log categories. + :vartype enabled_log_categories: list[str] + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "access_rules_version": {"key": "accessRulesVersion", "type": "int"}, + "access_rules": {"key": "accessRules", "type": "[NetworkSecurityPerimeterAccessRule]"}, + "diagnostic_settings_version": {"key": "diagnosticSettingsVersion", "type": "int"}, + "enabled_log_categories": {"key": "enabledLogCategories", "type": "[str]"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + access_rules_version: Optional[int] = None, + access_rules: Optional[List["_models.NetworkSecurityPerimeterAccessRule"]] = None, + diagnostic_settings_version: Optional[int] = None, + enabled_log_categories: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: Name of the resource profile. + :paramtype name: str + :keyword access_rules_version: Access rules version of the resource profile. + :paramtype access_rules_version: int + :keyword access_rules: + :paramtype access_rules: + list[~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterAccessRule] + :keyword diagnostic_settings_version: Current diagnostic settings version. + :paramtype diagnostic_settings_version: int + :keyword enabled_log_categories: List of enabled log categories. + :paramtype enabled_log_categories: list[str] + """ + super().__init__(**kwargs) + self.name = name + self.access_rules_version = access_rules_version + self.access_rules = access_rules + self.diagnostic_settings_version = diagnostic_settings_version + self.enabled_log_categories = enabled_log_categories + + class Operation(_serialization.Model): """Details of a REST API operation, returned from the Resource Provider Operations API. @@ -2533,7 +3716,7 @@ class PrivateEndpointConnection(AzureEntityResource): Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -2612,7 +3795,7 @@ class PrivateEndpointConnectionProperties(_serialization.Model): 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 Azure. + All required parameters must be populated in order to send to server. :ivar private_endpoint: The resource of private end point. :vartype private_endpoint: ~azure.mgmt.cognitiveservices.models.PrivateEndpoint @@ -2646,216 +3829,915 @@ class PrivateEndpointConnectionProperties(_serialization.Model): def __init__( self, *, - private_link_service_connection_state: "_models.PrivateLinkServiceConnectionState", - private_endpoint: Optional["_models.PrivateEndpoint"] = None, - group_ids: Optional[List[str]] = None, + private_link_service_connection_state: "_models.PrivateLinkServiceConnectionState", + private_endpoint: Optional["_models.PrivateEndpoint"] = None, + group_ids: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword private_endpoint: The resource of private end point. + :paramtype private_endpoint: ~azure.mgmt.cognitiveservices.models.PrivateEndpoint + :keyword private_link_service_connection_state: A collection of information about the state of + the connection between service consumer and provider. Required. + :paramtype private_link_service_connection_state: + ~azure.mgmt.cognitiveservices.models.PrivateLinkServiceConnectionState + :keyword group_ids: The private link resource group ids. + :paramtype group_ids: list[str] + """ + super().__init__(**kwargs) + self.private_endpoint = private_endpoint + self.private_link_service_connection_state = private_link_service_connection_state + self.provisioning_state = None + self.group_ids = group_ids + + +class PrivateLinkResource(Resource): + """A private link resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar properties: Resource properties. + :vartype properties: ~azure.mgmt.cognitiveservices.models.PrivateLinkResourceProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "PrivateLinkResourceProperties"}, + } + + def __init__(self, *, properties: Optional["_models.PrivateLinkResourceProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: Resource properties. + :paramtype properties: ~azure.mgmt.cognitiveservices.models.PrivateLinkResourceProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class PrivateLinkResourceListResult(_serialization.Model): + """A list of private link resources. + + :ivar value: Array of private link resources. + :vartype value: list[~azure.mgmt.cognitiveservices.models.PrivateLinkResource] + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PrivateLinkResource]"}, + } + + def __init__(self, *, value: Optional[List["_models.PrivateLinkResource"]] = None, **kwargs: Any) -> None: + """ + :keyword value: Array of private link resources. + :paramtype value: list[~azure.mgmt.cognitiveservices.models.PrivateLinkResource] + """ + super().__init__(**kwargs) + self.value = value + + +class PrivateLinkResourceProperties(_serialization.Model): + """Properties of a private link resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar group_id: The private link resource group id. + :vartype group_id: str + :ivar required_members: The private link resource required member names. + :vartype required_members: list[str] + :ivar required_zone_names: The private link resource Private link DNS zone name. + :vartype required_zone_names: list[str] + :ivar display_name: The private link resource display name. + :vartype display_name: str + """ + + _validation = { + "group_id": {"readonly": True}, + "required_members": {"readonly": True}, + "display_name": {"readonly": True}, + } + + _attribute_map = { + "group_id": {"key": "groupId", "type": "str"}, + "required_members": {"key": "requiredMembers", "type": "[str]"}, + "required_zone_names": {"key": "requiredZoneNames", "type": "[str]"}, + "display_name": {"key": "displayName", "type": "str"}, + } + + def __init__(self, *, required_zone_names: Optional[List[str]] = None, **kwargs: Any) -> None: + """ + :keyword required_zone_names: The private link resource Private link DNS zone name. + :paramtype required_zone_names: list[str] + """ + super().__init__(**kwargs) + self.group_id = None + self.required_members = None + self.required_zone_names = required_zone_names + self.display_name = None + + +class PrivateLinkServiceConnectionState(_serialization.Model): + """A collection of information about the state of the connection between service consumer and + provider. + + :ivar status: Indicates whether the connection has been Approved/Rejected/Removed by the owner + of the service. Known values are: "Pending", "Approved", and "Rejected". + :vartype status: str or + ~azure.mgmt.cognitiveservices.models.PrivateEndpointServiceConnectionStatus + :ivar description: The reason for approval/rejection of the connection. + :vartype description: str + :ivar actions_required: A message indicating if changes on the service provider require any + updates on the consumer. + :vartype actions_required: str + """ + + _attribute_map = { + "status": {"key": "status", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "actions_required": {"key": "actionsRequired", "type": "str"}, + } + + def __init__( + self, + *, + status: Optional[Union[str, "_models.PrivateEndpointServiceConnectionStatus"]] = None, + description: Optional[str] = None, + actions_required: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword status: Indicates whether the connection has been Approved/Rejected/Removed by the + owner of the service. Known values are: "Pending", "Approved", and "Rejected". + :paramtype status: str or + ~azure.mgmt.cognitiveservices.models.PrivateEndpointServiceConnectionStatus + :keyword description: The reason for approval/rejection of the connection. + :paramtype description: str + :keyword actions_required: A message indicating if changes on the service provider require any + updates on the consumer. + :paramtype actions_required: str + """ + super().__init__(**kwargs) + self.status = status + self.description = description + self.actions_required = actions_required + + +class ProvisioningIssue(_serialization.Model): + """ProvisioningIssue. + + :ivar name: Name of the NSP provisioning issue. + :vartype name: str + :ivar properties: Properties of Provisioning Issue. + :vartype properties: ~azure.mgmt.cognitiveservices.models.ProvisioningIssueProperties + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "properties": {"key": "properties", "type": "ProvisioningIssueProperties"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + properties: Optional["_models.ProvisioningIssueProperties"] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: Name of the NSP provisioning issue. + :paramtype name: str + :keyword properties: Properties of Provisioning Issue. + :paramtype properties: ~azure.mgmt.cognitiveservices.models.ProvisioningIssueProperties + """ + super().__init__(**kwargs) + self.name = name + self.properties = properties + + +class ProvisioningIssueProperties(_serialization.Model): + """Properties of Provisioning Issue. + + :ivar issue_type: Type of Issue. + :vartype issue_type: str + :ivar severity: Severity of the issue. + :vartype severity: str + :ivar description: Description of the issue. + :vartype description: str + :ivar suggested_resource_ids: IDs of resources that can be associated to the same perimeter to + remediate the issue. + :vartype suggested_resource_ids: list[str] + :ivar suggested_access_rules: Optional array, suggested access rules. + :vartype suggested_access_rules: + list[~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterAccessRule] + """ + + _attribute_map = { + "issue_type": {"key": "issueType", "type": "str"}, + "severity": {"key": "severity", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "suggested_resource_ids": {"key": "suggestedResourceIds", "type": "[str]"}, + "suggested_access_rules": {"key": "suggestedAccessRules", "type": "[NetworkSecurityPerimeterAccessRule]"}, + } + + def __init__( + self, + *, + issue_type: Optional[str] = None, + severity: Optional[str] = None, + description: Optional[str] = None, + suggested_resource_ids: Optional[List[str]] = None, + suggested_access_rules: Optional[List["_models.NetworkSecurityPerimeterAccessRule"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword issue_type: Type of Issue. + :paramtype issue_type: str + :keyword severity: Severity of the issue. + :paramtype severity: str + :keyword description: Description of the issue. + :paramtype description: str + :keyword suggested_resource_ids: IDs of resources that can be associated to the same perimeter + to remediate the issue. + :paramtype suggested_resource_ids: list[str] + :keyword suggested_access_rules: Optional array, suggested access rules. + :paramtype suggested_access_rules: + list[~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterAccessRule] + """ + super().__init__(**kwargs) + self.issue_type = issue_type + self.severity = severity + self.description = description + self.suggested_resource_ids = suggested_resource_ids + self.suggested_access_rules = suggested_access_rules + + +class QuotaLimit(_serialization.Model): + """QuotaLimit. + + :ivar count: + :vartype count: float + :ivar renewal_period: + :vartype renewal_period: float + :ivar rules: + :vartype rules: list[~azure.mgmt.cognitiveservices.models.ThrottlingRule] + """ + + _attribute_map = { + "count": {"key": "count", "type": "float"}, + "renewal_period": {"key": "renewalPeriod", "type": "float"}, + "rules": {"key": "rules", "type": "[ThrottlingRule]"}, + } + + def __init__( + self, + *, + count: Optional[float] = None, + renewal_period: Optional[float] = None, + rules: Optional[List["_models.ThrottlingRule"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword count: + :paramtype count: float + :keyword renewal_period: + :paramtype renewal_period: float + :keyword rules: + :paramtype rules: list[~azure.mgmt.cognitiveservices.models.ThrottlingRule] + """ + super().__init__(**kwargs) + self.count = count + self.renewal_period = renewal_period + self.rules = rules + + +class RaiBlocklist(ProxyResource): + """Cognitive Services RaiBlocklist. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Metadata pertaining to creation and last modification of the resource. + :vartype system_data: ~azure.mgmt.cognitiveservices.models.SystemData + :ivar etag: Resource Etag. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar properties: Properties of Cognitive Services RaiBlocklist. + :vartype properties: ~azure.mgmt.cognitiveservices.models.RaiBlocklistProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "etag": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "properties": {"key": "properties", "type": "RaiBlocklistProperties"}, + } + + def __init__( + self, + *, + tags: Optional[Dict[str, str]] = None, + properties: Optional["_models.RaiBlocklistProperties"] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword properties: Properties of Cognitive Services RaiBlocklist. + :paramtype properties: ~azure.mgmt.cognitiveservices.models.RaiBlocklistProperties + """ + super().__init__(**kwargs) + self.system_data = None + self.etag = None + self.tags = tags + self.properties = properties + + +class RaiBlocklistItem(ProxyResource): + """Cognitive Services RaiBlocklist Item. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Metadata pertaining to creation and last modification of the resource. + :vartype system_data: ~azure.mgmt.cognitiveservices.models.SystemData + :ivar etag: Resource Etag. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar properties: Properties of Cognitive Services RaiBlocklist Item. + :vartype properties: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItemProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "etag": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "properties": {"key": "properties", "type": "RaiBlocklistItemProperties"}, + } + + def __init__( + self, + *, + tags: Optional[Dict[str, str]] = None, + properties: Optional["_models.RaiBlocklistItemProperties"] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword properties: Properties of Cognitive Services RaiBlocklist Item. + :paramtype properties: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItemProperties + """ + super().__init__(**kwargs) + self.system_data = None + self.etag = None + self.tags = tags + self.properties = properties + + +class RaiBlocklistItemBulkRequest(_serialization.Model): + """The Cognitive Services RaiBlocklist Item request body. + + :ivar name: + :vartype name: str + :ivar properties: Properties of Cognitive Services RaiBlocklist Item. + :vartype properties: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItemProperties + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "properties": {"key": "properties", "type": "RaiBlocklistItemProperties"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + properties: Optional["_models.RaiBlocklistItemProperties"] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: + :paramtype name: str + :keyword properties: Properties of Cognitive Services RaiBlocklist Item. + :paramtype properties: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItemProperties + """ + super().__init__(**kwargs) + self.name = name + self.properties = properties + + +class RaiBlocklistItemProperties(_serialization.Model): + """RAI Custom Blocklist Item properties. + + :ivar pattern: Pattern to match against. + :vartype pattern: str + :ivar is_regex: If the pattern is a regex pattern. + :vartype is_regex: bool + """ + + _attribute_map = { + "pattern": {"key": "pattern", "type": "str"}, + "is_regex": {"key": "isRegex", "type": "bool"}, + } + + def __init__(self, *, pattern: Optional[str] = None, is_regex: Optional[bool] = None, **kwargs: Any) -> None: + """ + :keyword pattern: Pattern to match against. + :paramtype pattern: str + :keyword is_regex: If the pattern is a regex pattern. + :paramtype is_regex: bool + """ + super().__init__(**kwargs) + self.pattern = pattern + self.is_regex = is_regex + + +class RaiBlockListItemsResult(_serialization.Model): + """The list of cognitive services RAI Blocklist Items. + + :ivar next_link: The link used to get the next page of RaiBlocklistItems. + :vartype next_link: str + :ivar value: The list of RaiBlocklistItems. + :vartype value: list[~azure.mgmt.cognitiveservices.models.RaiBlocklistItem] + """ + + _attribute_map = { + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[RaiBlocklistItem]"}, + } + + def __init__( + self, + *, + next_link: Optional[str] = None, + value: Optional[List["_models.RaiBlocklistItem"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword next_link: The link used to get the next page of RaiBlocklistItems. + :paramtype next_link: str + :keyword value: The list of RaiBlocklistItems. + :paramtype value: list[~azure.mgmt.cognitiveservices.models.RaiBlocklistItem] + """ + super().__init__(**kwargs) + self.next_link = next_link + self.value = value + + +class RaiBlocklistProperties(_serialization.Model): + """RAI Custom Blocklist properties. + + :ivar description: Description of the block list. + :vartype description: str + """ + + _attribute_map = { + "description": {"key": "description", "type": "str"}, + } + + def __init__(self, *, description: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword description: Description of the block list. + :paramtype description: str + """ + super().__init__(**kwargs) + self.description = description + + +class RaiBlockListResult(_serialization.Model): + """The list of cognitive services RAI Blocklists. + + :ivar next_link: The link used to get the next page of RaiBlocklists. + :vartype next_link: str + :ivar value: The list of RaiBlocklist. + :vartype value: list[~azure.mgmt.cognitiveservices.models.RaiBlocklist] + """ + + _attribute_map = { + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[RaiBlocklist]"}, + } + + def __init__( + self, *, next_link: Optional[str] = None, value: Optional[List["_models.RaiBlocklist"]] = None, **kwargs: Any + ) -> None: + """ + :keyword next_link: The link used to get the next page of RaiBlocklists. + :paramtype next_link: str + :keyword value: The list of RaiBlocklist. + :paramtype value: list[~azure.mgmt.cognitiveservices.models.RaiBlocklist] + """ + super().__init__(**kwargs) + self.next_link = next_link + self.value = value + + +class RaiContentFilter(ProxyResource): + """Azure OpenAI Content Filter. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar properties: Azure OpenAI Content Filter Properties. + :vartype properties: ~azure.mgmt.cognitiveservices.models.RaiContentFilterProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "RaiContentFilterProperties"}, + } + + def __init__(self, *, properties: Optional["_models.RaiContentFilterProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: Azure OpenAI Content Filter Properties. + :paramtype properties: ~azure.mgmt.cognitiveservices.models.RaiContentFilterProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class RaiContentFilterListResult(_serialization.Model): + """The list of Content Filters. + + :ivar next_link: The link used to get the next page of Content Filters. + :vartype next_link: str + :ivar value: The list of RaiContentFilter. + :vartype value: list[~azure.mgmt.cognitiveservices.models.RaiContentFilter] + """ + + _attribute_map = { + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[RaiContentFilter]"}, + } + + def __init__( + self, + *, + next_link: Optional[str] = None, + value: Optional[List["_models.RaiContentFilter"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword next_link: The link used to get the next page of Content Filters. + :paramtype next_link: str + :keyword value: The list of RaiContentFilter. + :paramtype value: list[~azure.mgmt.cognitiveservices.models.RaiContentFilter] + """ + super().__init__(**kwargs) + self.next_link = next_link + self.value = value + + +class RaiContentFilterProperties(_serialization.Model): + """Azure OpenAI Content Filter Properties. + + :ivar name: Name of Content Filter. + :vartype name: str + :ivar is_multi_level_filter: If the Content Filter has multi severity levels(Low, Medium, or + High). + :vartype is_multi_level_filter: bool + :ivar source: Content source to apply the Content Filters. Known values are: "Prompt" and + "Completion". + :vartype source: str or ~azure.mgmt.cognitiveservices.models.RaiPolicyContentSource + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "is_multi_level_filter": {"key": "isMultiLevelFilter", "type": "bool"}, + "source": {"key": "source", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + is_multi_level_filter: Optional[bool] = None, + source: Optional[Union[str, "_models.RaiPolicyContentSource"]] = None, **kwargs: Any ) -> None: """ - :keyword private_endpoint: The resource of private end point. - :paramtype private_endpoint: ~azure.mgmt.cognitiveservices.models.PrivateEndpoint - :keyword private_link_service_connection_state: A collection of information about the state of - the connection between service consumer and provider. Required. - :paramtype private_link_service_connection_state: - ~azure.mgmt.cognitiveservices.models.PrivateLinkServiceConnectionState - :keyword group_ids: The private link resource group ids. - :paramtype group_ids: list[str] + :keyword name: Name of Content Filter. + :paramtype name: str + :keyword is_multi_level_filter: If the Content Filter has multi severity levels(Low, Medium, or + High). + :paramtype is_multi_level_filter: bool + :keyword source: Content source to apply the Content Filters. Known values are: "Prompt" and + "Completion". + :paramtype source: str or ~azure.mgmt.cognitiveservices.models.RaiPolicyContentSource """ super().__init__(**kwargs) - self.private_endpoint = private_endpoint - self.private_link_service_connection_state = private_link_service_connection_state - self.provisioning_state = None - self.group_ids = group_ids + self.name = name + self.is_multi_level_filter = is_multi_level_filter + self.source = source -class PrivateLinkResource(Resource): - """A private link resource. +class RaiMonitorConfig(_serialization.Model): + """Cognitive Services Rai Monitor Config. + + :ivar adx_storage_resource_id: The storage resource Id. + :vartype adx_storage_resource_id: str + :ivar identity_client_id: The identity client Id to access the storage. + :vartype identity_client_id: str + """ + + _attribute_map = { + "adx_storage_resource_id": {"key": "adxStorageResourceId", "type": "str"}, + "identity_client_id": {"key": "identityClientId", "type": "str"}, + } + + def __init__( + self, *, adx_storage_resource_id: Optional[str] = None, identity_client_id: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword adx_storage_resource_id: The storage resource Id. + :paramtype adx_storage_resource_id: str + :keyword identity_client_id: The identity client Id to access the storage. + :paramtype identity_client_id: str + """ + super().__init__(**kwargs) + self.adx_storage_resource_id = adx_storage_resource_id + self.identity_client_id = identity_client_id + + +class RaiPolicy(ProxyResource): + """Cognitive Services RaiPolicy. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :ivar properties: Resource properties. - :vartype properties: ~azure.mgmt.cognitiveservices.models.PrivateLinkResourceProperties + :ivar system_data: Metadata pertaining to creation and last modification of the resource. + :vartype system_data: ~azure.mgmt.cognitiveservices.models.SystemData + :ivar etag: Resource Etag. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar properties: Properties of Cognitive Services RaiPolicy. + :vartype properties: ~azure.mgmt.cognitiveservices.models.RaiPolicyProperties """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, + "system_data": {"readonly": True}, + "etag": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, - "properties": {"key": "properties", "type": "PrivateLinkResourceProperties"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "properties": {"key": "properties", "type": "RaiPolicyProperties"}, } - def __init__(self, *, properties: Optional["_models.PrivateLinkResourceProperties"] = None, **kwargs: Any) -> None: + def __init__( + self, + *, + tags: Optional[Dict[str, str]] = None, + properties: Optional["_models.RaiPolicyProperties"] = None, + **kwargs: Any + ) -> None: """ - :keyword properties: Resource properties. - :paramtype properties: ~azure.mgmt.cognitiveservices.models.PrivateLinkResourceProperties + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword properties: Properties of Cognitive Services RaiPolicy. + :paramtype properties: ~azure.mgmt.cognitiveservices.models.RaiPolicyProperties """ super().__init__(**kwargs) + self.system_data = None + self.etag = None + self.tags = tags self.properties = properties -class PrivateLinkResourceListResult(_serialization.Model): - """A list of private link resources. - - :ivar value: Array of private link resources. - :vartype value: list[~azure.mgmt.cognitiveservices.models.PrivateLinkResource] - """ - - _attribute_map = { - "value": {"key": "value", "type": "[PrivateLinkResource]"}, - } - - def __init__(self, *, value: Optional[List["_models.PrivateLinkResource"]] = None, **kwargs: Any) -> None: - """ - :keyword value: Array of private link resources. - :paramtype value: list[~azure.mgmt.cognitiveservices.models.PrivateLinkResource] - """ - super().__init__(**kwargs) - self.value = value - - -class PrivateLinkResourceProperties(_serialization.Model): - """Properties of a private link resource. - - Variables are only populated by the server, and will be ignored when sending a request. +class RaiPolicyContentFilter(_serialization.Model): + """Azure OpenAI Content Filter. - :ivar group_id: The private link resource group id. - :vartype group_id: str - :ivar required_members: The private link resource required member names. - :vartype required_members: list[str] - :ivar required_zone_names: The private link resource Private link DNS zone name. - :vartype required_zone_names: list[str] - :ivar display_name: The private link resource display name. - :vartype display_name: str + :ivar name: Name of ContentFilter. + :vartype name: str + :ivar enabled: If the ContentFilter is enabled. + :vartype enabled: bool + :ivar severity_threshold: Level at which content is filtered. Known values are: "Low", + "Medium", and "High". + :vartype severity_threshold: str or ~azure.mgmt.cognitiveservices.models.ContentLevel + :ivar blocking: If blocking would occur. + :vartype blocking: bool + :ivar source: Content source to apply the Content Filters. Known values are: "Prompt" and + "Completion". + :vartype source: str or ~azure.mgmt.cognitiveservices.models.RaiPolicyContentSource """ - _validation = { - "group_id": {"readonly": True}, - "required_members": {"readonly": True}, - "display_name": {"readonly": True}, - } - _attribute_map = { - "group_id": {"key": "groupId", "type": "str"}, - "required_members": {"key": "requiredMembers", "type": "[str]"}, - "required_zone_names": {"key": "requiredZoneNames", "type": "[str]"}, - "display_name": {"key": "displayName", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "enabled": {"key": "enabled", "type": "bool"}, + "severity_threshold": {"key": "severityThreshold", "type": "str"}, + "blocking": {"key": "blocking", "type": "bool"}, + "source": {"key": "source", "type": "str"}, } - def __init__(self, *, required_zone_names: Optional[List[str]] = None, **kwargs: Any) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + enabled: Optional[bool] = None, + severity_threshold: Optional[Union[str, "_models.ContentLevel"]] = None, + blocking: Optional[bool] = None, + source: Optional[Union[str, "_models.RaiPolicyContentSource"]] = None, + **kwargs: Any + ) -> None: """ - :keyword required_zone_names: The private link resource Private link DNS zone name. - :paramtype required_zone_names: list[str] + :keyword name: Name of ContentFilter. + :paramtype name: str + :keyword enabled: If the ContentFilter is enabled. + :paramtype enabled: bool + :keyword severity_threshold: Level at which content is filtered. Known values are: "Low", + "Medium", and "High". + :paramtype severity_threshold: str or ~azure.mgmt.cognitiveservices.models.ContentLevel + :keyword blocking: If blocking would occur. + :paramtype blocking: bool + :keyword source: Content source to apply the Content Filters. Known values are: "Prompt" and + "Completion". + :paramtype source: str or ~azure.mgmt.cognitiveservices.models.RaiPolicyContentSource """ super().__init__(**kwargs) - self.group_id = None - self.required_members = None - self.required_zone_names = required_zone_names - self.display_name = None + self.name = name + self.enabled = enabled + self.severity_threshold = severity_threshold + self.blocking = blocking + self.source = source -class PrivateLinkServiceConnectionState(_serialization.Model): - """A collection of information about the state of the connection between service consumer and - provider. +class RaiPolicyListResult(_serialization.Model): + """The list of cognitive services RaiPolicies. - :ivar status: Indicates whether the connection has been Approved/Rejected/Removed by the owner - of the service. Known values are: "Pending", "Approved", and "Rejected". - :vartype status: str or - ~azure.mgmt.cognitiveservices.models.PrivateEndpointServiceConnectionStatus - :ivar description: The reason for approval/rejection of the connection. - :vartype description: str - :ivar actions_required: A message indicating if changes on the service provider require any - updates on the consumer. - :vartype actions_required: str + :ivar next_link: The link used to get the next page of RaiPolicy. + :vartype next_link: str + :ivar value: The list of RaiPolicy. + :vartype value: list[~azure.mgmt.cognitiveservices.models.RaiPolicy] """ _attribute_map = { - "status": {"key": "status", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "actions_required": {"key": "actionsRequired", "type": "str"}, + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[RaiPolicy]"}, } def __init__( - self, - *, - status: Optional[Union[str, "_models.PrivateEndpointServiceConnectionStatus"]] = None, - description: Optional[str] = None, - actions_required: Optional[str] = None, - **kwargs: Any + self, *, next_link: Optional[str] = None, value: Optional[List["_models.RaiPolicy"]] = None, **kwargs: Any ) -> None: """ - :keyword status: Indicates whether the connection has been Approved/Rejected/Removed by the - owner of the service. Known values are: "Pending", "Approved", and "Rejected". - :paramtype status: str or - ~azure.mgmt.cognitiveservices.models.PrivateEndpointServiceConnectionStatus - :keyword description: The reason for approval/rejection of the connection. - :paramtype description: str - :keyword actions_required: A message indicating if changes on the service provider require any - updates on the consumer. - :paramtype actions_required: str + :keyword next_link: The link used to get the next page of RaiPolicy. + :paramtype next_link: str + :keyword value: The list of RaiPolicy. + :paramtype value: list[~azure.mgmt.cognitiveservices.models.RaiPolicy] """ super().__init__(**kwargs) - self.status = status - self.description = description - self.actions_required = actions_required + self.next_link = next_link + self.value = value -class QuotaLimit(_serialization.Model): - """QuotaLimit. +class RaiPolicyProperties(_serialization.Model): + """Azure OpenAI Content Filters properties. - :ivar count: - :vartype count: float - :ivar renewal_period: - :vartype renewal_period: float - :ivar rules: - :vartype rules: list[~azure.mgmt.cognitiveservices.models.ThrottlingRule] + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: Content Filters policy type. Known values are: "UserManaged" and "SystemManaged". + :vartype type: str or ~azure.mgmt.cognitiveservices.models.RaiPolicyType + :ivar mode: Rai policy mode. The enum value mapping is as below: Default = 0, Deferred=1, + Blocking=2, Asynchronous_filter =3. Please use 'Asynchronous_filter' after 2024-10-01. It is + the same as 'Deferred' in previous version. Known values are: "Default", "Deferred", + "Blocking", and "Asynchronous_filter". + :vartype mode: str or ~azure.mgmt.cognitiveservices.models.RaiPolicyMode + :ivar base_policy_name: Name of Rai policy. + :vartype base_policy_name: str + :ivar content_filters: The list of Content Filters. + :vartype content_filters: list[~azure.mgmt.cognitiveservices.models.RaiPolicyContentFilter] + :ivar custom_blocklists: The list of custom Blocklist. + :vartype custom_blocklists: list[~azure.mgmt.cognitiveservices.models.CustomBlocklistConfig] """ + _validation = { + "type": {"readonly": True}, + } + _attribute_map = { - "count": {"key": "count", "type": "float"}, - "renewal_period": {"key": "renewalPeriod", "type": "float"}, - "rules": {"key": "rules", "type": "[ThrottlingRule]"}, + "type": {"key": "type", "type": "str"}, + "mode": {"key": "mode", "type": "str"}, + "base_policy_name": {"key": "basePolicyName", "type": "str"}, + "content_filters": {"key": "contentFilters", "type": "[RaiPolicyContentFilter]"}, + "custom_blocklists": {"key": "customBlocklists", "type": "[CustomBlocklistConfig]"}, } def __init__( self, *, - count: Optional[float] = None, - renewal_period: Optional[float] = None, - rules: Optional[List["_models.ThrottlingRule"]] = None, + mode: Optional[Union[str, "_models.RaiPolicyMode"]] = None, + base_policy_name: Optional[str] = None, + content_filters: Optional[List["_models.RaiPolicyContentFilter"]] = None, + custom_blocklists: Optional[List["_models.CustomBlocklistConfig"]] = None, **kwargs: Any ) -> None: """ - :keyword count: - :paramtype count: float - :keyword renewal_period: - :paramtype renewal_period: float - :keyword rules: - :paramtype rules: list[~azure.mgmt.cognitiveservices.models.ThrottlingRule] + :keyword mode: Rai policy mode. The enum value mapping is as below: Default = 0, Deferred=1, + Blocking=2, Asynchronous_filter =3. Please use 'Asynchronous_filter' after 2024-10-01. It is + the same as 'Deferred' in previous version. Known values are: "Default", "Deferred", + "Blocking", and "Asynchronous_filter". + :paramtype mode: str or ~azure.mgmt.cognitiveservices.models.RaiPolicyMode + :keyword base_policy_name: Name of Rai policy. + :paramtype base_policy_name: str + :keyword content_filters: The list of Content Filters. + :paramtype content_filters: list[~azure.mgmt.cognitiveservices.models.RaiPolicyContentFilter] + :keyword custom_blocklists: The list of custom Blocklist. + :paramtype custom_blocklists: list[~azure.mgmt.cognitiveservices.models.CustomBlocklistConfig] """ super().__init__(**kwargs) - self.count = count - self.renewal_period = renewal_period - self.rules = rules + self.type = None + self.mode = mode + self.base_policy_name = base_policy_name + self.content_filters = content_filters + self.custom_blocklists = custom_blocklists class RegenerateKeyParameters(_serialization.Model): """Regenerate key parameters. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar key_name: key name to generate (Key1|Key2). Required. Known values are: "Key1" and "Key2". @@ -3010,7 +4892,7 @@ def __init__( class ResourceSkuListResult(_serialization.Model): """The Get Skus operation response. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar value: The list of skus available for the subscription. Required. :vartype value: list[~azure.mgmt.cognitiveservices.models.ResourceSku] @@ -3122,7 +5004,7 @@ def __init__( class Sku(_serialization.Model): """The resource model definition representing SKU. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar name: The name of the SKU. Ex - P3. It is typically a letter+number code. Required. :vartype name: str @@ -3333,6 +5215,45 @@ def __init__( self.last_change_date = last_change_date +class SkuResource(_serialization.Model): + """Properties of Cognitive Services account resource sku resource properties. + + :ivar resource_type: The resource type name. + :vartype resource_type: str + :ivar sku: The resource model definition representing SKU. + :vartype sku: ~azure.mgmt.cognitiveservices.models.Sku + :ivar capacity: The capacity configuration. + :vartype capacity: ~azure.mgmt.cognitiveservices.models.CapacityConfig + """ + + _attribute_map = { + "resource_type": {"key": "resourceType", "type": "str"}, + "sku": {"key": "sku", "type": "Sku"}, + "capacity": {"key": "capacity", "type": "CapacityConfig"}, + } + + def __init__( + self, + *, + resource_type: Optional[str] = None, + sku: Optional["_models.Sku"] = None, + capacity: Optional["_models.CapacityConfig"] = None, + **kwargs: Any + ) -> None: + """ + :keyword resource_type: The resource type name. + :paramtype resource_type: str + :keyword sku: The resource model definition representing SKU. + :paramtype sku: ~azure.mgmt.cognitiveservices.models.Sku + :keyword capacity: The capacity configuration. + :paramtype capacity: ~azure.mgmt.cognitiveservices.models.CapacityConfig + """ + super().__init__(**kwargs) + self.resource_type = resource_type + self.sku = sku + self.capacity = capacity + + class SystemData(_serialization.Model): """Metadata pertaining to creation and last modification of the resource. @@ -3584,6 +5505,34 @@ def __init__(self, **kwargs: Any) -> None: self.client_id = None +class UserOwnedAmlWorkspace(_serialization.Model): + """The user owned AML workspace for Cognitive Services account. + + :ivar resource_id: Full resource id of a AML workspace resource. + :vartype resource_id: str + :ivar identity_client_id: Identity Client id of a AML workspace resource. + :vartype identity_client_id: str + """ + + _attribute_map = { + "resource_id": {"key": "resourceId", "type": "str"}, + "identity_client_id": {"key": "identityClientId", "type": "str"}, + } + + def __init__( + self, *, resource_id: Optional[str] = None, identity_client_id: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword resource_id: Full resource id of a AML workspace resource. + :paramtype resource_id: str + :keyword identity_client_id: Identity Client id of a AML workspace resource. + :paramtype identity_client_id: str + """ + super().__init__(**kwargs) + self.resource_id = resource_id + self.identity_client_id = identity_client_id + + class UserOwnedStorage(_serialization.Model): """The user owned storage for Cognitive Services account. @@ -3615,7 +5564,7 @@ def __init__( class VirtualNetworkRule(_serialization.Model): """A rule governing the accessibility from a specific virtual network. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar id: Full resource id of a vnet subnet, such as '/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1'. @@ -3647,7 +5596,7 @@ def __init__( ) -> None: """ :keyword id: Full resource id of a vnet subnet, such as - '/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1'. + '/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1'. # pylint: disable=line-too-long Required. :paramtype id: str :keyword state: Gets the state of virtual network rule. diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/__init__.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/__init__.py index 26043fb0a303..fdaa24c0f86a 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/__init__.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/__init__.py @@ -14,10 +14,19 @@ from ._cognitive_services_management_client_operations import CognitiveServicesManagementClientOperationsMixin from ._commitment_tiers_operations import CommitmentTiersOperations from ._models_operations import ModelsOperations +from ._location_based_model_capacities_operations import LocationBasedModelCapacitiesOperations +from ._model_capacities_operations import ModelCapacitiesOperations from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations from ._private_link_resources_operations import PrivateLinkResourcesOperations from ._deployments_operations import DeploymentsOperations from ._commitment_plans_operations import CommitmentPlansOperations +from ._encryption_scopes_operations import EncryptionScopesOperations +from ._rai_policies_operations import RaiPoliciesOperations +from ._rai_blocklists_operations import RaiBlocklistsOperations +from ._rai_blocklist_items_operations import RaiBlocklistItemsOperations +from ._rai_content_filters_operations import RaiContentFiltersOperations +from ._network_security_perimeter_configurations_operations import NetworkSecurityPerimeterConfigurationsOperations +from ._defender_for_ai_settings_operations import DefenderForAISettingsOperations from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import @@ -32,10 +41,19 @@ "CognitiveServicesManagementClientOperationsMixin", "CommitmentTiersOperations", "ModelsOperations", + "LocationBasedModelCapacitiesOperations", + "ModelCapacitiesOperations", "PrivateEndpointConnectionsOperations", "PrivateLinkResourcesOperations", "DeploymentsOperations", "CommitmentPlansOperations", + "EncryptionScopesOperations", + "RaiPoliciesOperations", + "RaiBlocklistsOperations", + "RaiBlocklistItemsOperations", + "RaiContentFiltersOperations", + "NetworkSecurityPerimeterConfigurationsOperations", + "DefenderForAISettingsOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_accounts_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_accounts_operations.py index 7f21631c2eda..5233db0f6856 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_accounts_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_accounts_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( @@ -16,13 +17,14 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat @@ -30,8 +32,11 @@ from .. import models as _models from .._serialization import Serializer -from .._vendor import CognitiveServicesManagementClientMixinABC, _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -45,7 +50,7 @@ def build_create_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -64,7 +69,7 @@ def build_create_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -83,7 +88,7 @@ def build_update_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -102,7 +107,7 @@ def build_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -121,7 +126,7 @@ def build_delete_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -139,7 +144,7 @@ def build_delete_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -154,7 +159,7 @@ def build_get_request(resource_group_name: str, account_name: str, subscription_ _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -172,7 +177,7 @@ def build_get_request(resource_group_name: str, account_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -187,7 +192,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -202,7 +207,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -217,7 +222,7 @@ def build_list_request(subscription_id: 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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -226,7 +231,7 @@ def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -243,7 +248,7 @@ def build_list_keys_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -261,7 +266,7 @@ def build_list_keys_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -278,7 +283,7 @@ def build_regenerate_key_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -297,7 +302,7 @@ def build_regenerate_key_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -316,7 +321,7 @@ def build_list_skus_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -334,7 +339,7 @@ def build_list_skus_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -351,7 +356,7 @@ def build_list_usages_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -369,7 +374,7 @@ def build_list_usages_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -388,7 +393,7 @@ def build_list_models_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -406,7 +411,7 @@ def build_list_models_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -437,9 +442,9 @@ def __init__(self, *args, **kwargs): self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") def _create_initial( - self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO], **kwargs: Any - ) -> _models.Account: - error_map = { + self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO[bytes]], **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -452,7 +457,7 @@ def _create_initial( 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.Account] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -462,7 +467,7 @@ def _create_initial( else: _json = self._serialize.body(account, "Account") - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, @@ -470,43 +475,35 @@ def _create_initial( content_type=content_type, json=_json, content=_content, - template_url=self._create_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("Account", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("Account", pipeline_response) - - if response.status_code == 202: - deserialized = self._deserialize("Account", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - _create_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" - } - @overload def begin_create( self, @@ -530,14 +527,6 @@ def begin_create( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either Account or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.Account] :raises ~azure.core.exceptions.HttpResponseError: @@ -548,7 +537,7 @@ def begin_create( self, resource_group_name: str, account_name: str, - account: IO, + account: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -562,18 +551,10 @@ def begin_create( :param account_name: The name of Cognitive Services account. Required. :type account_name: str :param account: The parameters to provide for the created account. Required. - :type account: IO + :type account: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either Account or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.Account] :raises ~azure.core.exceptions.HttpResponseError: @@ -581,7 +562,7 @@ def begin_create( @distributed_trace def begin_create( - self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO], **kwargs: Any + self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.Account]: """Create Cognitive Services Account. Accounts is a resource group wide resource type. It holds the keys for developer to access intelligent APIs. It's also the resource type for billing. @@ -592,19 +573,8 @@ def begin_create( :param account_name: The name of Cognitive Services account. Required. :type account_name: str :param account: The parameters to provide for the created account. Is either a Account type or - a IO type. Required. - :type account: ~azure.mgmt.cognitiveservices.models.Account or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + a IO[bytes] type. Required. + :type account: ~azure.mgmt.cognitiveservices.models.Account or IO[bytes] :return: An instance of LROPoller that returns either Account or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.Account] :raises ~azure.core.exceptions.HttpResponseError: @@ -630,12 +600,13 @@ def begin_create( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Account", pipeline_response) + deserialized = self._deserialize("Account", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -645,22 +616,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.Account].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" - } + return LROPoller[_models.Account]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _update_initial( - self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO], **kwargs: Any - ) -> _models.Account: - error_map = { + self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO[bytes]], **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -673,7 +642,7 @@ def _update_initial( 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.Account] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -683,7 +652,7 @@ def _update_initial( else: _json = self._serialize.body(account, "Account") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, @@ -691,40 +660,35 @@ def _update_initial( content_type=content_type, json=_json, content=_content, - template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("Account", pipeline_response) - - if response.status_code == 202: - deserialized = self._deserialize("Account", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - _update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" - } - @overload def begin_update( self, @@ -747,14 +711,6 @@ def begin_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either Account or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.Account] :raises ~azure.core.exceptions.HttpResponseError: @@ -765,7 +721,7 @@ def begin_update( self, resource_group_name: str, account_name: str, - account: IO, + account: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -778,18 +734,10 @@ def begin_update( :param account_name: The name of Cognitive Services account. Required. :type account_name: str :param account: The parameters to provide for the created account. Required. - :type account: IO + :type account: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either Account or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.Account] :raises ~azure.core.exceptions.HttpResponseError: @@ -797,7 +745,7 @@ def begin_update( @distributed_trace def begin_update( - self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO], **kwargs: Any + self, resource_group_name: str, account_name: str, account: Union[_models.Account, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.Account]: """Updates a Cognitive Services account. @@ -807,19 +755,8 @@ def begin_update( :param account_name: The name of Cognitive Services account. Required. :type account_name: str :param account: The parameters to provide for the created account. Is either a Account type or - a IO type. Required. - :type account: ~azure.mgmt.cognitiveservices.models.Account or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + a IO[bytes] type. Required. + :type account: ~azure.mgmt.cognitiveservices.models.Account or IO[bytes] :return: An instance of LROPoller that returns either Account or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.Account] :raises ~azure.core.exceptions.HttpResponseError: @@ -845,12 +782,13 @@ def begin_update( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Account", pipeline_response) + deserialized = self._deserialize("Account", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -860,22 +798,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.Account].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" - } + return LROPoller[_models.Account]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, account_name: str, **kwargs: Any - ) -> None: - error_map = { + def _delete_initial(self, resource_group_name: str, account_name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -887,38 +821,41 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements _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[None] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - _delete_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" - } + return deserialized # type: ignore @distributed_trace def begin_delete(self, resource_group_name: str, account_name: str, **kwargs: Any) -> LROPoller[None]: @@ -929,14 +866,6 @@ def begin_delete(self, resource_group_name: str, account_name: str, **kwargs: An :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -950,7 +879,7 @@ def begin_delete(self, resource_group_name: str, account_name: str, **kwargs: An lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( # type: ignore + raw_result = self._delete_initial( resource_group_name=resource_group_name, account_name=account_name, api_version=api_version, @@ -959,11 +888,12 @@ def begin_delete(self, resource_group_name: str, account_name: str, **kwargs: An params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) @@ -972,17 +902,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" - } + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def get(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _models.Account: @@ -993,12 +919,11 @@ def get(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _mo :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Account or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.Account :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1012,21 +937,19 @@ def get(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _mo api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Account] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1036,16 +959,12 @@ def get(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _mo error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Account", pipeline_response) + deserialized = self._deserialize("Account", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" - } + return deserialized # type: ignore @distributed_trace def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.Account"]: @@ -1054,7 +973,6 @@ def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Ite :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Account or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.Account] :raises ~azure.core.exceptions.HttpResponseError: @@ -1065,7 +983,7 @@ def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Ite api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AccountListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1076,16 +994,14 @@ def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Ite def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_group_request( + _request = build_list_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1097,13 +1013,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AccountListResult", pipeline_response) @@ -1113,11 +1028,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1130,15 +1045,10 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts" - } - @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.Account"]: """Returns all the resources of a particular type belonging to a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Account or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.Account] :raises ~azure.core.exceptions.HttpResponseError: @@ -1149,7 +1059,7 @@ def list(self, **kwargs: Any) -> Iterable["_models.Account"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AccountListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1160,15 +1070,13 @@ def list(self, **kwargs: Any) -> Iterable["_models.Account"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1180,13 +1088,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AccountListResult", pipeline_response) @@ -1196,11 +1103,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1213,8 +1120,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/accounts"} - @distributed_trace def list_keys(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _models.ApiKeys: """Lists the account keys for the specified Cognitive Services account. @@ -1224,12 +1129,11 @@ def list_keys(self, resource_group_name: str, account_name: str, **kwargs: Any) :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ApiKeys or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.ApiKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1243,21 +1147,19 @@ def list_keys(self, resource_group_name: str, account_name: str, **kwargs: Any) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ApiKeys] = kwargs.pop("cls", None) - request = build_list_keys_request( + _request = build_list_keys_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_keys.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1267,16 +1169,12 @@ def list_keys(self, resource_group_name: str, account_name: str, **kwargs: Any) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ApiKeys", pipeline_response) + deserialized = self._deserialize("ApiKeys", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list_keys.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/listKeys" - } + return deserialized # type: ignore @distributed_trace def regenerate_key( @@ -1292,12 +1190,11 @@ def regenerate_key( :param key_name: key name to generate (Key1|Key2). Known values are: "Key1" and "Key2". Required. :type key_name: str or ~azure.mgmt.cognitiveservices.models.KeyName - :keyword callable cls: A custom type or function that will be passed the direct response :return: ApiKeys or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.ApiKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1315,23 +1212,21 @@ def regenerate_key( _parameters = _models.RegenerateKeyParameters(key_name=key_name) _json = self._serialize.body(_parameters, "RegenerateKeyParameters") - request = build_regenerate_key_request( + _request = build_regenerate_key_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.regenerate_key.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1341,16 +1236,12 @@ def regenerate_key( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ApiKeys", pipeline_response) + deserialized = self._deserialize("ApiKeys", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - regenerate_key.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/regenerateKey" - } + return deserialized # type: ignore @distributed_trace def list_skus(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _models.AccountSkuListResult: @@ -1361,12 +1252,11 @@ def list_skus(self, resource_group_name: str, account_name: str, **kwargs: Any) :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AccountSkuListResult or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.AccountSkuListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1380,21 +1270,19 @@ def list_skus(self, resource_group_name: str, account_name: str, **kwargs: Any) api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AccountSkuListResult] = kwargs.pop("cls", None) - request = build_list_skus_request( + _request = build_list_skus_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_skus.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1404,16 +1292,12 @@ def list_skus(self, resource_group_name: str, account_name: str, **kwargs: Any) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AccountSkuListResult", pipeline_response) + deserialized = self._deserialize("AccountSkuListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list_skus.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/skus" - } + return deserialized # type: ignore @distributed_trace def list_usages( @@ -1430,12 +1314,11 @@ def list_usages( supported parameter is name.value (name of the metric, can have an or of multiple names). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: UsageListResult or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.UsageListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1449,22 +1332,20 @@ def list_usages( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.UsageListResult] = kwargs.pop("cls", None) - request = build_list_usages_request( + _request = build_list_usages_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, filter=filter, api_version=api_version, - template_url=self.list_usages.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1474,16 +1355,12 @@ def list_usages( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("UsageListResult", pipeline_response) + deserialized = self._deserialize("UsageListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list_usages.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/usages" - } + return deserialized # type: ignore @distributed_trace def list_models( @@ -1496,7 +1373,6 @@ def list_models( :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AccountModel or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.AccountModel] :raises ~azure.core.exceptions.HttpResponseError: @@ -1507,7 +1383,7 @@ def list_models( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AccountModelListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1518,17 +1394,15 @@ def list_models( def prepare_request(next_link=None): if not next_link: - request = build_list_models_request( + _request = build_list_models_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_models.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1540,13 +1414,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AccountModelListResult", pipeline_response) @@ -1556,11 +1429,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1572,7 +1445,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_models.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/models" - } diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_cognitive_services_management_client_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_cognitive_services_management_client_operations.py index 2ad07e47bcf0..411c651e4fed 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_cognitive_services_management_client_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_cognitive_services_management_client_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, List, Optional, TypeVar +import sys +from typing import Any, Callable, Dict, List, Optional, Type, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, @@ -17,16 +18,19 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import CognitiveServicesManagementClientMixinABC, _convert_request, _format_url_section +from .._vendor import CognitiveServicesManagementClientMixinABC +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -38,7 +42,7 @@ def build_check_sku_availability_request(location: str, subscription_id: str, ** _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -52,7 +56,7 @@ def build_check_sku_availability_request(location: str, subscription_id: str, ** "location": _SERIALIZER.url("location", location, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -69,7 +73,7 @@ def build_check_domain_availability_request(subscription_id: str, **kwargs: Any) _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -81,7 +85,7 @@ def build_check_domain_availability_request(subscription_id: str, **kwargs: Any) "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -94,7 +98,39 @@ def build_check_domain_availability_request(subscription_id: str, **kwargs: Any) return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -class CognitiveServicesManagementClientOperationsMixin(CognitiveServicesManagementClientMixinABC): +def build_calculate_model_capacity_request(subscription_id: 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", "2024-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/calculateModelCapacity" + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _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") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class CognitiveServicesManagementClientOperationsMixin( # pylint: disable=name-too-long + CognitiveServicesManagementClientMixinABC +): + @distributed_trace def check_sku_availability( self, location: str, skus: List[str], kind: str, type: str, **kwargs: Any @@ -105,16 +141,15 @@ def check_sku_availability( :type location: str :param skus: The SKU of the resource. Required. :type skus: list[str] - :param kind: The Kind of the resource. Required. + :param kind: The kind (type) of cognitive service account. Required. :type kind: str :param type: The Type of the resource. Required. :type type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: SkuAvailabilityListResult or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.SkuAvailabilityListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -132,22 +167,20 @@ def check_sku_availability( _parameters = _models.CheckSkuAvailabilityParameter(kind=kind, skus=skus, type=type) _json = self._serialize.body(_parameters, "CheckSkuAvailabilityParameter") - request = build_check_sku_availability_request( + _request = build_check_sku_availability_request( location=location, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_sku_availability.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -157,16 +190,12 @@ def check_sku_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SkuAvailabilityListResult", pipeline_response) + deserialized = self._deserialize("SkuAvailabilityListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - check_sku_availability.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/checkSkuAvailability" - } + return deserialized # type: ignore @distributed_trace def check_domain_availability( @@ -180,12 +209,11 @@ def check_domain_availability( :type type: str :param kind: The Kind of the resource. Default value is None. :type kind: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DomainAvailability or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.DomainAvailability :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -203,21 +231,19 @@ def check_domain_availability( _parameters = _models.CheckDomainAvailabilityParameter(kind=kind, subdomain_name=subdomain_name, type=type) _json = self._serialize.body(_parameters, "CheckDomainAvailabilityParameter") - request = build_check_domain_availability_request( + _request = build_check_domain_availability_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_domain_availability.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -227,13 +253,76 @@ def check_domain_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DomainAvailability", pipeline_response) + deserialized = self._deserialize("DomainAvailability", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore - check_domain_availability.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/checkDomainAvailability" - } + @distributed_trace + def calculate_model_capacity( + self, + model: Optional[_models.DeploymentModel] = None, + sku_name: Optional[str] = None, + workloads: Optional[List[_models.ModelCapacityCalculatorWorkload]] = None, + **kwargs: Any + ) -> _models.CalculateModelCapacityResult: + """Model capacity calculator. + + :param model: Properties of Cognitive Services account deployment model. Default value is None. + :type model: ~azure.mgmt.cognitiveservices.models.DeploymentModel + :param sku_name: The name of SKU. Default value is None. + :type sku_name: str + :param workloads: List of Model Capacity Calculator Workload. Default value is None. + :type workloads: list[~azure.mgmt.cognitiveservices.models.ModelCapacityCalculatorWorkload] + :return: CalculateModelCapacityResult or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.CalculateModelCapacityResult + :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 = 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", self._config.api_version)) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[_models.CalculateModelCapacityResult] = kwargs.pop("cls", None) + + _parameters = _models.CalculateModelCapacityParameter(model=model, sku_name=sku_name, workloads=workloads) + _json = self._serialize.body(_parameters, "CalculateModelCapacityParameter") + + _request = build_calculate_model_capacity_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CalculateModelCapacityResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_commitment_plans_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_commitment_plans_operations.py index 511bac31955f..1ad7dc62c8aa 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_commitment_plans_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_commitment_plans_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( @@ -16,13 +17,14 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat @@ -30,8 +32,11 @@ from .. import models as _models from .._serialization import Serializer -from .._vendor import CognitiveServicesManagementClientMixinABC, _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -43,7 +48,7 @@ def build_list_request(resource_group_name: str, account_name: str, subscription _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -61,7 +66,7 @@ def build_list_request(resource_group_name: str, account_name: str, subscription "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -78,7 +83,7 @@ def build_get_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -97,7 +102,7 @@ def build_get_request( "commitmentPlanName": _SERIALIZER.url("commitment_plan_name", commitment_plan_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -114,7 +119,7 @@ def build_create_or_update_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -134,7 +139,7 @@ def build_create_or_update_request( "commitmentPlanName": _SERIALIZER.url("commitment_plan_name", commitment_plan_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -153,7 +158,7 @@ def build_delete_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -172,7 +177,7 @@ def build_delete_request( "commitmentPlanName": _SERIALIZER.url("commitment_plan_name", commitment_plan_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -189,7 +194,7 @@ def build_create_or_update_plan_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -208,7 +213,7 @@ def build_create_or_update_plan_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -227,7 +232,7 @@ def build_update_plan_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -246,7 +251,7 @@ def build_update_plan_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -265,7 +270,7 @@ def build_delete_plan_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -283,7 +288,7 @@ def build_delete_plan_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -300,7 +305,7 @@ def build_get_plan_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -318,7 +323,7 @@ def build_get_plan_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -329,13 +334,13 @@ def build_get_plan_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_plans_by_resource_group_request( +def build_list_plans_by_resource_group_request( # pylint: disable=name-too-long resource_group_name: str, subscription_id: 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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -350,7 +355,7 @@ def build_list_plans_by_resource_group_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -365,7 +370,7 @@ def build_list_plans_by_subscription_request(subscription_id: str, **kwargs: Any _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -376,7 +381,7 @@ def build_list_plans_by_subscription_request(subscription_id: str, **kwargs: Any "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -393,7 +398,7 @@ def build_list_associations_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -411,7 +416,7 @@ def build_list_associations_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -432,7 +437,7 @@ def build_get_association_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -456,7 +461,7 @@ def build_get_association_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -467,7 +472,7 @@ def build_get_association_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_create_or_update_association_request( +def build_create_or_update_association_request( # pylint: disable=name-too-long resource_group_name: str, commitment_plan_name: str, commitment_plan_association_name: str, @@ -477,7 +482,7 @@ def build_create_or_update_association_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -502,7 +507,7 @@ def build_create_or_update_association_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -525,7 +530,7 @@ def build_delete_association_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -549,7 +554,7 @@ def build_delete_association_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -588,7 +593,6 @@ def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> It :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.CommitmentPlan] :raises ~azure.core.exceptions.HttpResponseError: @@ -599,7 +603,7 @@ def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> It api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentPlanListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -610,17 +614,15 @@ def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> It def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -632,13 +634,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("CommitmentPlanListResult", pipeline_response) @@ -648,11 +649,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -665,10 +666,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/commitmentPlans" - } - @distributed_trace def get( self, resource_group_name: str, account_name: str, commitment_plan_name: str, **kwargs: Any @@ -683,12 +680,11 @@ def get( :param commitment_plan_name: The name of the commitmentPlan associated with the Cognitive Services Account. Required. :type commitment_plan_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CommitmentPlan or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.CommitmentPlan :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -702,22 +698,20 @@ def get( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentPlan] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, commitment_plan_name=commitment_plan_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -727,16 +721,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CommitmentPlan", pipeline_response) + deserialized = self._deserialize("CommitmentPlan", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/commitmentPlans/{commitmentPlanName}" - } + return deserialized # type: ignore @overload def create_or_update( @@ -764,7 +754,6 @@ def create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CommitmentPlan or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.CommitmentPlan :raises ~azure.core.exceptions.HttpResponseError: @@ -776,7 +765,7 @@ def create_or_update( resource_group_name: str, account_name: str, commitment_plan_name: str, - commitment_plan: IO, + commitment_plan: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -792,11 +781,10 @@ def create_or_update( Services Account. Required. :type commitment_plan_name: str :param commitment_plan: The commitmentPlan properties. Required. - :type commitment_plan: IO + :type commitment_plan: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CommitmentPlan or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.CommitmentPlan :raises ~azure.core.exceptions.HttpResponseError: @@ -808,7 +796,7 @@ def create_or_update( resource_group_name: str, account_name: str, commitment_plan_name: str, - commitment_plan: Union[_models.CommitmentPlan, IO], + commitment_plan: Union[_models.CommitmentPlan, IO[bytes]], **kwargs: Any ) -> _models.CommitmentPlan: """Update the state of specified commitmentPlans associated with the Cognitive Services account. @@ -821,18 +809,14 @@ def create_or_update( :param commitment_plan_name: The name of the commitmentPlan associated with the Cognitive Services Account. Required. :type commitment_plan_name: str - :param commitment_plan: The commitmentPlan properties. Is either a CommitmentPlan type or a IO - type. Required. - :type commitment_plan: ~azure.mgmt.cognitiveservices.models.CommitmentPlan or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param commitment_plan: The commitmentPlan properties. Is either a CommitmentPlan type or a + IO[bytes] type. Required. + :type commitment_plan: ~azure.mgmt.cognitiveservices.models.CommitmentPlan or IO[bytes] :return: CommitmentPlan or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.CommitmentPlan :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -855,7 +839,7 @@ def create_or_update( else: _json = self._serialize.body(commitment_plan, "CommitmentPlan") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, account_name=account_name, commitment_plan_name=commitment_plan_name, @@ -864,16 +848,14 @@ def create_or_update( content_type=content_type, json=_json, content=_content, - template_url=self.create_or_update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -883,25 +865,17 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("CommitmentPlan", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("CommitmentPlan", pipeline_response) + deserialized = self._deserialize("CommitmentPlan", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/commitmentPlans/{commitmentPlanName}" - } - - def _delete_initial( # pylint: disable=inconsistent-return-statements + def _delete_initial( self, resource_group_name: str, account_name: str, commitment_plan_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -913,39 +887,42 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements _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[None] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, commitment_plan_name=commitment_plan_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - _delete_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/commitmentPlans/{commitmentPlanName}" - } + return deserialized # type: ignore @distributed_trace def begin_delete( @@ -961,14 +938,6 @@ def begin_delete( :param commitment_plan_name: The name of the commitmentPlan associated with the Cognitive Services Account. Required. :type commitment_plan_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -982,7 +951,7 @@ def begin_delete( lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( # type: ignore + raw_result = self._delete_initial( resource_group_name=resource_group_name, account_name=account_name, commitment_plan_name=commitment_plan_name, @@ -992,11 +961,12 @@ def begin_delete( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) @@ -1005,26 +975,22 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/commitmentPlans/{commitmentPlanName}" - } + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore def _create_or_update_plan_initial( self, resource_group_name: str, commitment_plan_name: str, - commitment_plan: Union[_models.CommitmentPlan, IO], + commitment_plan: Union[_models.CommitmentPlan, IO[bytes]], **kwargs: Any - ) -> _models.CommitmentPlan: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1037,7 +1003,7 @@ def _create_or_update_plan_initial( 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.CommitmentPlan] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -1047,7 +1013,7 @@ def _create_or_update_plan_initial( else: _json = self._serialize.body(commitment_plan, "CommitmentPlan") - request = build_create_or_update_plan_request( + _request = build_create_or_update_plan_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, subscription_id=self._config.subscription_id, @@ -1055,40 +1021,35 @@ def _create_or_update_plan_initial( content_type=content_type, json=_json, content=_content, - template_url=self._create_or_update_plan_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("CommitmentPlan", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("CommitmentPlan", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - _create_or_update_plan_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" - } - @overload def begin_create_or_update_plan( self, @@ -1112,14 +1073,6 @@ def begin_create_or_update_plan( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.CommitmentPlan] @@ -1131,7 +1084,7 @@ def begin_create_or_update_plan( self, resource_group_name: str, commitment_plan_name: str, - commitment_plan: IO, + commitment_plan: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1145,18 +1098,10 @@ def begin_create_or_update_plan( Services Account. Required. :type commitment_plan_name: str :param commitment_plan: The parameters to provide for the created commitment plan. Required. - :type commitment_plan: IO + :type commitment_plan: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.CommitmentPlan] @@ -1168,7 +1113,7 @@ def begin_create_or_update_plan( self, resource_group_name: str, commitment_plan_name: str, - commitment_plan: Union[_models.CommitmentPlan, IO], + commitment_plan: Union[_models.CommitmentPlan, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.CommitmentPlan]: """Create Cognitive Services commitment plan. @@ -1180,19 +1125,8 @@ def begin_create_or_update_plan( Services Account. Required. :type commitment_plan_name: str :param commitment_plan: The parameters to provide for the created commitment plan. Is either a - CommitmentPlan type or a IO type. Required. - :type commitment_plan: ~azure.mgmt.cognitiveservices.models.CommitmentPlan or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + CommitmentPlan type or a IO[bytes] type. Required. + :type commitment_plan: ~azure.mgmt.cognitiveservices.models.CommitmentPlan or IO[bytes] :return: An instance of LROPoller that returns either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.CommitmentPlan] @@ -1219,12 +1153,13 @@ def begin_create_or_update_plan( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CommitmentPlan", pipeline_response) + deserialized = self._deserialize("CommitmentPlan", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -1236,26 +1171,24 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.CommitmentPlan].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update_plan.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" - } + return LROPoller[_models.CommitmentPlan]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _update_plan_initial( self, resource_group_name: str, commitment_plan_name: str, - commitment_plan: Union[_models.PatchResourceTagsAndSku, IO], + commitment_plan: Union[_models.PatchResourceTagsAndSku, IO[bytes]], **kwargs: Any - ) -> Optional[_models.CommitmentPlan]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1268,7 +1201,7 @@ def _update_plan_initial( 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[Optional[_models.CommitmentPlan]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -1278,7 +1211,7 @@ def _update_plan_initial( else: _json = self._serialize.body(commitment_plan, "PatchResourceTagsAndSku") - request = build_update_plan_request( + _request = build_update_plan_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, subscription_id=self._config.subscription_id, @@ -1286,41 +1219,38 @@ def _update_plan_initial( content_type=content_type, json=_json, content=_content, - template_url=self._update_plan_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("CommitmentPlan", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _update_plan_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" - } + return deserialized # type: ignore @overload def begin_update_plan( @@ -1345,14 +1275,6 @@ def begin_update_plan( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.CommitmentPlan] @@ -1364,7 +1286,7 @@ def begin_update_plan( self, resource_group_name: str, commitment_plan_name: str, - commitment_plan: IO, + commitment_plan: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1378,18 +1300,10 @@ def begin_update_plan( Services Account. Required. :type commitment_plan_name: str :param commitment_plan: The parameters to provide for the created commitment plan. Required. - :type commitment_plan: IO + :type commitment_plan: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.CommitmentPlan] @@ -1401,7 +1315,7 @@ def begin_update_plan( self, resource_group_name: str, commitment_plan_name: str, - commitment_plan: Union[_models.PatchResourceTagsAndSku, IO], + commitment_plan: Union[_models.PatchResourceTagsAndSku, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.CommitmentPlan]: """Create Cognitive Services commitment plan. @@ -1413,19 +1327,9 @@ def begin_update_plan( Services Account. Required. :type commitment_plan_name: str :param commitment_plan: The parameters to provide for the created commitment plan. Is either a - PatchResourceTagsAndSku type or a IO type. Required. - :type commitment_plan: ~azure.mgmt.cognitiveservices.models.PatchResourceTagsAndSku or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + PatchResourceTagsAndSku type or a IO[bytes] type. Required. + :type commitment_plan: ~azure.mgmt.cognitiveservices.models.PatchResourceTagsAndSku or + IO[bytes] :return: An instance of LROPoller that returns either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.CommitmentPlan] @@ -1452,12 +1356,13 @@ def begin_update_plan( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CommitmentPlan", pipeline_response) + deserialized = self._deserialize("CommitmentPlan", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -1469,22 +1374,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.CommitmentPlan].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_update_plan.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" - } + return LROPoller[_models.CommitmentPlan]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - def _delete_plan_initial( # pylint: disable=inconsistent-return-statements + def _delete_plan_initial( self, resource_group_name: str, commitment_plan_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1496,28 +1399,31 @@ def _delete_plan_initial( # pylint: disable=inconsistent-return-statements _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[None] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_plan_request( + _request = build_delete_plan_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_plan_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) @@ -1526,12 +1432,12 @@ def _delete_plan_initial( # pylint: disable=inconsistent-return-statements if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _delete_plan_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" - } + return deserialized # type: ignore @distributed_trace def begin_delete_plan(self, resource_group_name: str, commitment_plan_name: str, **kwargs: Any) -> LROPoller[None]: @@ -1543,14 +1449,6 @@ def begin_delete_plan(self, resource_group_name: str, commitment_plan_name: str, :param commitment_plan_name: The name of the commitmentPlan associated with the Cognitive Services Account. Required. :type commitment_plan_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -1564,7 +1462,7 @@ def begin_delete_plan(self, resource_group_name: str, commitment_plan_name: str, lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_plan_initial( # type: ignore + raw_result = self._delete_plan_initial( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, api_version=api_version, @@ -1573,11 +1471,12 @@ def begin_delete_plan(self, resource_group_name: str, commitment_plan_name: str, params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: PollingMethod = cast( @@ -1588,17 +1487,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete_plan.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" - } + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def get_plan(self, resource_group_name: str, commitment_plan_name: str, **kwargs: Any) -> _models.CommitmentPlan: @@ -1610,12 +1505,11 @@ def get_plan(self, resource_group_name: str, commitment_plan_name: str, **kwargs :param commitment_plan_name: The name of the commitmentPlan associated with the Cognitive Services Account. Required. :type commitment_plan_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CommitmentPlan or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.CommitmentPlan :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1629,21 +1523,19 @@ def get_plan(self, resource_group_name: str, commitment_plan_name: str, **kwargs api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentPlan] = kwargs.pop("cls", None) - request = build_get_plan_request( + _request = build_get_plan_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_plan.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1653,16 +1545,12 @@ def get_plan(self, resource_group_name: str, commitment_plan_name: str, **kwargs error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CommitmentPlan", pipeline_response) + deserialized = self._deserialize("CommitmentPlan", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_plan.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" - } + return deserialized # type: ignore @distributed_trace def list_plans_by_resource_group( @@ -1673,7 +1561,6 @@ def list_plans_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.CommitmentPlan] :raises ~azure.core.exceptions.HttpResponseError: @@ -1684,7 +1571,7 @@ def list_plans_by_resource_group( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentPlanListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1695,16 +1582,14 @@ def list_plans_by_resource_group( def prepare_request(next_link=None): if not next_link: - request = build_list_plans_by_resource_group_request( + _request = build_list_plans_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_plans_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1716,13 +1601,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("CommitmentPlanListResult", pipeline_response) @@ -1732,11 +1616,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1749,15 +1633,10 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_plans_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans" - } - @distributed_trace def list_plans_by_subscription(self, **kwargs: Any) -> Iterable["_models.CommitmentPlan"]: """Returns all the resources of a particular type belonging to a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either CommitmentPlan or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.CommitmentPlan] :raises ~azure.core.exceptions.HttpResponseError: @@ -1768,7 +1647,7 @@ def list_plans_by_subscription(self, **kwargs: Any) -> Iterable["_models.Commitm api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentPlanListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1779,15 +1658,13 @@ def list_plans_by_subscription(self, **kwargs: Any) -> Iterable["_models.Commitm def prepare_request(next_link=None): if not next_link: - request = build_list_plans_by_subscription_request( + _request = build_list_plans_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_plans_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1799,13 +1676,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("CommitmentPlanListResult", pipeline_response) @@ -1815,11 +1691,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1832,10 +1708,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_plans_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/commitmentPlans" - } - @distributed_trace def list_associations( self, resource_group_name: str, commitment_plan_name: str, **kwargs: Any @@ -1848,7 +1720,6 @@ def list_associations( :param commitment_plan_name: The name of the commitmentPlan associated with the Cognitive Services Account. Required. :type commitment_plan_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either CommitmentPlanAccountAssociation or the result of cls(response) :rtype: @@ -1861,7 +1732,7 @@ def list_associations( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentPlanAccountAssociationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1872,17 +1743,15 @@ def list_associations( def prepare_request(next_link=None): if not next_link: - request = build_list_associations_request( + _request = build_list_associations_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_associations.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1894,13 +1763,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("CommitmentPlanAccountAssociationListResult", pipeline_response) @@ -1910,11 +1778,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1927,10 +1795,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_associations.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations" - } - @distributed_trace def get_association( self, resource_group_name: str, commitment_plan_name: str, commitment_plan_association_name: str, **kwargs: Any @@ -1946,12 +1810,11 @@ def get_association( :param commitment_plan_association_name: The name of the commitment plan association with the Cognitive Services Account. Required. :type commitment_plan_association_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: CommitmentPlanAccountAssociation or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.CommitmentPlanAccountAssociation :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1965,22 +1828,20 @@ def get_association( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentPlanAccountAssociation] = kwargs.pop("cls", None) - request = build_get_association_request( + _request = build_get_association_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, commitment_plan_association_name=commitment_plan_association_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_association.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1990,26 +1851,22 @@ def get_association( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CommitmentPlanAccountAssociation", pipeline_response) + deserialized = self._deserialize("CommitmentPlanAccountAssociation", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_association.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations/{commitmentPlanAssociationName}" - } + return deserialized # type: ignore def _create_or_update_association_initial( self, resource_group_name: str, commitment_plan_name: str, commitment_plan_association_name: str, - association: Union[_models.CommitmentPlanAccountAssociation, IO], + association: Union[_models.CommitmentPlanAccountAssociation, IO[bytes]], **kwargs: Any - ) -> _models.CommitmentPlanAccountAssociation: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2022,7 +1879,7 @@ def _create_or_update_association_initial( 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.CommitmentPlanAccountAssociation] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -2032,7 +1889,7 @@ def _create_or_update_association_initial( else: _json = self._serialize.body(association, "CommitmentPlanAccountAssociation") - request = build_create_or_update_association_request( + _request = build_create_or_update_association_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, commitment_plan_association_name=commitment_plan_association_name, @@ -2041,40 +1898,35 @@ def _create_or_update_association_initial( content_type=content_type, json=_json, content=_content, - template_url=self._create_or_update_association_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("CommitmentPlanAccountAssociation", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("CommitmentPlanAccountAssociation", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - _create_or_update_association_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations/{commitmentPlanAssociationName}" - } - @overload def begin_create_or_update_association( self, @@ -2102,14 +1954,6 @@ def begin_create_or_update_association( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either CommitmentPlanAccountAssociation or the result of cls(response) :rtype: @@ -2123,7 +1967,7 @@ def begin_create_or_update_association( resource_group_name: str, commitment_plan_name: str, commitment_plan_association_name: str, - association: IO, + association: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -2140,18 +1984,10 @@ def begin_create_or_update_association( Cognitive Services Account. Required. :type commitment_plan_association_name: str :param association: The commitmentPlan properties. Required. - :type association: IO + :type association: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either CommitmentPlanAccountAssociation or the result of cls(response) :rtype: @@ -2165,7 +2001,7 @@ def begin_create_or_update_association( resource_group_name: str, commitment_plan_name: str, commitment_plan_association_name: str, - association: Union[_models.CommitmentPlanAccountAssociation, IO], + association: Union[_models.CommitmentPlanAccountAssociation, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.CommitmentPlanAccountAssociation]: """Create or update the association of the Cognitive Services commitment plan. @@ -2180,19 +2016,9 @@ def begin_create_or_update_association( Cognitive Services Account. Required. :type commitment_plan_association_name: str :param association: The commitmentPlan properties. Is either a CommitmentPlanAccountAssociation - type or a IO type. Required. - :type association: ~azure.mgmt.cognitiveservices.models.CommitmentPlanAccountAssociation or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + type or a IO[bytes] type. Required. + :type association: ~azure.mgmt.cognitiveservices.models.CommitmentPlanAccountAssociation or + IO[bytes] :return: An instance of LROPoller that returns either CommitmentPlanAccountAssociation or the result of cls(response) :rtype: @@ -2221,12 +2047,13 @@ def begin_create_or_update_association( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CommitmentPlanAccountAssociation", pipeline_response) + deserialized = self._deserialize("CommitmentPlanAccountAssociation", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -2238,22 +2065,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.CommitmentPlanAccountAssociation].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update_association.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations/{commitmentPlanAssociationName}" - } + return LROPoller[_models.CommitmentPlanAccountAssociation]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - def _delete_association_initial( # pylint: disable=inconsistent-return-statements + def _delete_association_initial( self, resource_group_name: str, commitment_plan_name: str, commitment_plan_association_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2265,29 +2090,32 @@ def _delete_association_initial( # pylint: disable=inconsistent-return-statemen _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[None] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_association_request( + _request = build_delete_association_request( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, commitment_plan_association_name=commitment_plan_association_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_association_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) @@ -2296,12 +2124,12 @@ def _delete_association_initial( # pylint: disable=inconsistent-return-statemen if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _delete_association_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations/{commitmentPlanAssociationName}" - } + return deserialized # type: ignore @distributed_trace def begin_delete_association( @@ -2318,14 +2146,6 @@ def begin_delete_association( :param commitment_plan_association_name: The name of the commitment plan association with the Cognitive Services Account. Required. :type commitment_plan_association_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -2339,7 +2159,7 @@ def begin_delete_association( lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_association_initial( # type: ignore + raw_result = self._delete_association_initial( resource_group_name=resource_group_name, commitment_plan_name=commitment_plan_name, commitment_plan_association_name=commitment_plan_association_name, @@ -2349,11 +2169,12 @@ def begin_delete_association( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: PollingMethod = cast( @@ -2364,14 +2185,10 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete_association.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations/{commitmentPlanAssociationName}" - } + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_commitment_tiers_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_commitment_tiers_operations.py index 8856f976a8b4..250ff3bb6a0a 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_commitment_tiers_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_commitment_tiers_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar import urllib.parse from azure.core.exceptions import ( @@ -19,16 +20,18 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import CognitiveServicesManagementClientMixinABC, _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -40,7 +43,7 @@ def build_list_request(location: str, subscription_id: str, **kwargs: Any) -> Ht _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -53,7 +56,7 @@ def build_list_request(location: str, subscription_id: str, **kwargs: Any) -> Ht "location": _SERIALIZER.url("location", location, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -89,7 +92,6 @@ def list(self, location: str, **kwargs: Any) -> Iterable["_models.CommitmentTier :param location: Resource location. Required. :type location: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either CommitmentTier or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.CommitmentTier] :raises ~azure.core.exceptions.HttpResponseError: @@ -100,7 +102,7 @@ def list(self, location: str, **kwargs: Any) -> Iterable["_models.CommitmentTier api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.CommitmentTierListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -111,16 +113,14 @@ def list(self, location: str, **kwargs: Any) -> Iterable["_models.CommitmentTier def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( location=location, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -132,13 +132,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("CommitmentTierListResult", pipeline_response) @@ -148,11 +147,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -164,7 +163,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/commitmentTiers" - } diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_defender_for_ai_settings_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_defender_for_ai_settings_operations.py new file mode 100644 index 000000000000..e70dbebd2b8f --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_defender_for_ai_settings_operations.py @@ -0,0 +1,643 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, Type, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(resource_group_name: str, account_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/defenderForAISettings", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + resource_group_name: str, account_name: str, defender_for_ai_setting_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/defenderForAISettings/{defenderForAISettingName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "defenderForAISettingName": _SERIALIZER.url( + "defender_for_ai_setting_name", defender_for_ai_setting_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, account_name: str, defender_for_ai_setting_name: str, subscription_id: 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", "2024-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/defenderForAISettings/{defenderForAISettingName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "defenderForAISettingName": _SERIALIZER.url( + "defender_for_ai_setting_name", defender_for_ai_setting_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _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") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request( + resource_group_name: str, account_name: str, defender_for_ai_setting_name: str, subscription_id: 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", "2024-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/defenderForAISettings/{defenderForAISettingName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "defenderForAISettingName": _SERIALIZER.url( + "defender_for_ai_setting_name", defender_for_ai_setting_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _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") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +class DefenderForAISettingsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.CognitiveServicesManagementClient`'s + :attr:`defender_for_ai_settings` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.DefenderForAISetting"]: + """Lists the Defender for AI settings. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :return: An iterator like instance of either DefenderForAISetting or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.DefenderForAISetting] + :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.DefenderForAISettingResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DefenderForAISettingResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get( + self, resource_group_name: str, account_name: str, defender_for_ai_setting_name: str, **kwargs: Any + ) -> _models.DefenderForAISetting: + """Gets the specified Defender for AI setting by name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param defender_for_ai_setting_name: The name of the defender for AI setting. Required. + :type defender_for_ai_setting_name: str + :return: DefenderForAISetting or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :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.DefenderForAISetting] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + defender_for_ai_setting_name=defender_for_ai_setting_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DefenderForAISetting", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, + resource_group_name: str, + account_name: str, + defender_for_ai_setting_name: str, + defender_for_ai_settings: _models.DefenderForAISetting, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DefenderForAISetting: + """Creates or Updates the specified Defender for AI setting. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param defender_for_ai_setting_name: The name of the defender for AI setting. Required. + :type defender_for_ai_setting_name: str + :param defender_for_ai_settings: Properties describing the Defender for AI setting. Required. + :type defender_for_ai_settings: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: DefenderForAISetting or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + account_name: str, + defender_for_ai_setting_name: str, + defender_for_ai_settings: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DefenderForAISetting: + """Creates or Updates the specified Defender for AI setting. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param defender_for_ai_setting_name: The name of the defender for AI setting. Required. + :type defender_for_ai_setting_name: str + :param defender_for_ai_settings: Properties describing the Defender for AI setting. Required. + :type defender_for_ai_settings: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: DefenderForAISetting or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + account_name: str, + defender_for_ai_setting_name: str, + defender_for_ai_settings: Union[_models.DefenderForAISetting, IO[bytes]], + **kwargs: Any + ) -> _models.DefenderForAISetting: + """Creates or Updates the specified Defender for AI setting. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param defender_for_ai_setting_name: The name of the defender for AI setting. Required. + :type defender_for_ai_setting_name: str + :param defender_for_ai_settings: Properties describing the Defender for AI setting. Is either a + DefenderForAISetting type or a IO[bytes] type. Required. + :type defender_for_ai_settings: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting or + IO[bytes] + :return: DefenderForAISetting or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :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 = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DefenderForAISetting] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(defender_for_ai_settings, (IOBase, bytes)): + _content = defender_for_ai_settings + else: + _json = self._serialize.body(defender_for_ai_settings, "DefenderForAISetting") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + defender_for_ai_setting_name=defender_for_ai_setting_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DefenderForAISetting", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, + resource_group_name: str, + account_name: str, + defender_for_ai_setting_name: str, + defender_for_ai_settings: _models.DefenderForAISetting, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DefenderForAISetting: + """Updates the specified Defender for AI setting. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param defender_for_ai_setting_name: The name of the defender for AI setting. Required. + :type defender_for_ai_setting_name: str + :param defender_for_ai_settings: Properties describing the Defender for AI setting. Required. + :type defender_for_ai_settings: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: DefenderForAISetting or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + account_name: str, + defender_for_ai_setting_name: str, + defender_for_ai_settings: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DefenderForAISetting: + """Updates the specified Defender for AI setting. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param defender_for_ai_setting_name: The name of the defender for AI setting. Required. + :type defender_for_ai_setting_name: str + :param defender_for_ai_settings: Properties describing the Defender for AI setting. Required. + :type defender_for_ai_settings: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: DefenderForAISetting or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + resource_group_name: str, + account_name: str, + defender_for_ai_setting_name: str, + defender_for_ai_settings: Union[_models.DefenderForAISetting, IO[bytes]], + **kwargs: Any + ) -> _models.DefenderForAISetting: + """Updates the specified Defender for AI setting. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param defender_for_ai_setting_name: The name of the defender for AI setting. Required. + :type defender_for_ai_setting_name: str + :param defender_for_ai_settings: Properties describing the Defender for AI setting. Is either a + DefenderForAISetting type or a IO[bytes] type. Required. + :type defender_for_ai_settings: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting or + IO[bytes] + :return: DefenderForAISetting or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.DefenderForAISetting + :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 = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DefenderForAISetting] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(defender_for_ai_settings, (IOBase, bytes)): + _content = defender_for_ai_settings + else: + _json = self._serialize.body(defender_for_ai_settings, "DefenderForAISetting") + + _request = build_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + defender_for_ai_setting_name=defender_for_ai_setting_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DefenderForAISetting", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_deleted_accounts_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_deleted_accounts_operations.py index 8aedc3ed54de..8537120f87da 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_deleted_accounts_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_deleted_accounts_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast +import sys +from typing import Any, Callable, Dict, Iterable, Iterator, Optional, Type, TypeVar, Union, cast import urllib.parse from azure.core.exceptions import ( @@ -15,13 +16,14 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat @@ -29,8 +31,11 @@ from .. import models as _models from .._serialization import Serializer -from .._vendor import CognitiveServicesManagementClientMixinABC, _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -44,7 +49,7 @@ def build_get_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -63,7 +68,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -80,7 +85,7 @@ def build_purge_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -99,7 +104,7 @@ def build_purge_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -114,7 +119,7 @@ def build_list_request(subscription_id: 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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -125,7 +130,7 @@ def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -166,12 +171,11 @@ def get(self, location: str, resource_group_name: str, account_name: str, **kwar :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Account or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.Account :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -185,22 +189,20 @@ def get(self, location: str, resource_group_name: str, account_name: str, **kwar api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Account] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( location=location, resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -210,21 +212,17 @@ def get(self, location: str, resource_group_name: str, account_name: str, **kwar error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Account", pipeline_response) + deserialized = self._deserialize("Account", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/resourceGroups/{resourceGroupName}/deletedAccounts/{accountName}" - } - - def _purge_initial( # pylint: disable=inconsistent-return-statements + def _purge_initial( self, location: str, resource_group_name: str, account_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -236,39 +234,42 @@ def _purge_initial( # pylint: disable=inconsistent-return-statements _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[None] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_purge_request( + _request = build_purge_request( location=location, resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._purge_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - _purge_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/resourceGroups/{resourceGroupName}/deletedAccounts/{accountName}" - } + return deserialized # type: ignore @distributed_trace def begin_purge(self, location: str, resource_group_name: str, account_name: str, **kwargs: Any) -> LROPoller[None]: @@ -281,14 +282,6 @@ def begin_purge(self, location: str, resource_group_name: str, account_name: str :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -302,7 +295,7 @@ def begin_purge(self, location: str, resource_group_name: str, account_name: str lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._purge_initial( # type: ignore + raw_result = self._purge_initial( location=location, resource_group_name=resource_group_name, account_name=account_name, @@ -312,11 +305,12 @@ def begin_purge(self, location: str, resource_group_name: str, account_name: str params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) @@ -325,23 +319,18 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_purge.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/resourceGroups/{resourceGroupName}/deletedAccounts/{accountName}" - } + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.Account"]: """Returns all the resources of a particular type belonging to a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Account or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.Account] :raises ~azure.core.exceptions.HttpResponseError: @@ -352,7 +341,7 @@ def list(self, **kwargs: Any) -> Iterable["_models.Account"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AccountListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -363,15 +352,13 @@ def list(self, **kwargs: Any) -> Iterable["_models.Account"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -383,13 +370,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AccountListResult", pipeline_response) @@ -399,11 +385,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -415,5 +401,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/deletedAccounts"} diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_deployments_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_deployments_operations.py index 9e161dbdfcc6..d9f8d0f197d6 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_deployments_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_deployments_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( @@ -16,13 +17,14 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat @@ -30,8 +32,11 @@ from .. import models as _models from .._serialization import Serializer -from .._vendor import CognitiveServicesManagementClientMixinABC, _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -43,7 +48,7 @@ def build_list_request(resource_group_name: str, account_name: str, subscription _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -61,7 +66,7 @@ def build_list_request(resource_group_name: str, account_name: str, subscription "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -78,7 +83,7 @@ def build_get_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -97,7 +102,7 @@ def build_get_request( "deploymentName": _SERIALIZER.url("deployment_name", deployment_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -114,7 +119,7 @@ def build_create_or_update_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -134,7 +139,7 @@ def build_create_or_update_request( "deploymentName": _SERIALIZER.url("deployment_name", deployment_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -147,13 +152,52 @@ def build_create_or_update_request( return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) +def build_update_request( + resource_group_name: str, account_name: str, deployment_name: str, subscription_id: 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", "2024-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "deploymentName": _SERIALIZER.url("deployment_name", deployment_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _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") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + def build_delete_request( resource_group_name: str, account_name: str, deployment_name: str, subscription_id: 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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -172,7 +216,7 @@ def build_delete_request( "deploymentName": _SERIALIZER.url("deployment_name", deployment_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -183,6 +227,42 @@ def build_delete_request( return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) +def build_list_skus_request( + resource_group_name: str, account_name: str, deployment_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}/skus", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "deploymentName": _SERIALIZER.url("deployment_name", deployment_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + class DeploymentsOperations: """ .. warning:: @@ -211,7 +291,6 @@ def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> It :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Deployment or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.Deployment] :raises ~azure.core.exceptions.HttpResponseError: @@ -222,7 +301,7 @@ def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> It api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.DeploymentListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -233,17 +312,15 @@ def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> It def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -255,13 +332,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DeploymentListResult", pipeline_response) @@ -271,11 +347,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -288,10 +364,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments" - } - @distributed_trace def get( self, resource_group_name: str, account_name: str, deployment_name: str, **kwargs: Any @@ -306,12 +378,11 @@ def get( :param deployment_name: The name of the deployment associated with the Cognitive Services Account. Required. :type deployment_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Deployment or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.Deployment :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -325,22 +396,20 @@ def get( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Deployment] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, deployment_name=deployment_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -350,26 +419,22 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Deployment", pipeline_response) + deserialized = self._deserialize("Deployment", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}" - } + return deserialized # type: ignore def _create_or_update_initial( self, resource_group_name: str, account_name: str, deployment_name: str, - deployment: Union[_models.Deployment, IO], + deployment: Union[_models.Deployment, IO[bytes]], **kwargs: Any - ) -> _models.Deployment: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -382,7 +447,7 @@ def _create_or_update_initial( 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.Deployment] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -392,7 +457,7 @@ def _create_or_update_initial( else: _json = self._serialize.body(deployment, "Deployment") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, account_name=account_name, deployment_name=deployment_name, @@ -401,40 +466,35 @@ def _create_or_update_initial( content_type=content_type, json=_json, content=_content, - template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("Deployment", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("Deployment", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}" - } - @overload def begin_create_or_update( self, @@ -461,14 +521,6 @@ def begin_create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either Deployment or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.Deployment] :raises ~azure.core.exceptions.HttpResponseError: @@ -480,7 +532,7 @@ def begin_create_or_update( resource_group_name: str, account_name: str, deployment_name: str, - deployment: IO, + deployment: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -496,18 +548,10 @@ def begin_create_or_update( Account. Required. :type deployment_name: str :param deployment: The deployment properties. Required. - :type deployment: IO + :type deployment: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either Deployment or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.Deployment] :raises ~azure.core.exceptions.HttpResponseError: @@ -519,7 +563,7 @@ def begin_create_or_update( resource_group_name: str, account_name: str, deployment_name: str, - deployment: Union[_models.Deployment, IO], + deployment: Union[_models.Deployment, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.Deployment]: """Update the state of specified deployments associated with the Cognitive Services account. @@ -532,20 +576,9 @@ def begin_create_or_update( :param deployment_name: The name of the deployment associated with the Cognitive Services Account. Required. :type deployment_name: str - :param deployment: The deployment properties. Is either a Deployment type or a IO type. + :param deployment: The deployment properties. Is either a Deployment type or a IO[bytes] type. Required. - :type deployment: ~azure.mgmt.cognitiveservices.models.Deployment or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + :type deployment: ~azure.mgmt.cognitiveservices.models.Deployment or IO[bytes] :return: An instance of LROPoller that returns either Deployment or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.Deployment] :raises ~azure.core.exceptions.HttpResponseError: @@ -572,12 +605,13 @@ def begin_create_or_update( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Deployment", pipeline_response) + deserialized = self._deserialize("Deployment", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -589,22 +623,231 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.Deployment].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return LROPoller[_models.Deployment]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}" - } + def _update_initial( + self, + resource_group_name: str, + account_name: str, + deployment_name: str, + deployment: Union[_models.PatchResourceTagsAndSku, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _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", 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(deployment, (IOBase, bytes)): + _content = deployment + else: + _json = self._serialize.body(deployment, "PatchResourceTagsAndSku") + + _request = build_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + deployment_name=deployment_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + 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, 202]: + 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update( + self, + resource_group_name: str, + account_name: str, + deployment_name: str, + deployment: _models.PatchResourceTagsAndSku, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Deployment]: + """Update specified deployments associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param deployment_name: The name of the deployment associated with the Cognitive Services + Account. Required. + :type deployment_name: str + :param deployment: The deployment properties. Required. + :type deployment: ~azure.mgmt.cognitiveservices.models.PatchResourceTagsAndSku + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either Deployment or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.Deployment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + account_name: str, + deployment_name: str, + deployment: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Deployment]: + """Update specified deployments associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param deployment_name: The name of the deployment associated with the Cognitive Services + Account. Required. + :type deployment_name: str + :param deployment: The deployment properties. Required. + :type deployment: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either Deployment or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.Deployment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + account_name: str, + deployment_name: str, + deployment: Union[_models.PatchResourceTagsAndSku, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.Deployment]: + """Update specified deployments associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param deployment_name: The name of the deployment associated with the Cognitive Services + Account. Required. + :type deployment_name: str + :param deployment: The deployment properties. Is either a PatchResourceTagsAndSku type or a + IO[bytes] type. Required. + :type deployment: ~azure.mgmt.cognitiveservices.models.PatchResourceTagsAndSku or IO[bytes] + :return: An instance of LROPoller that returns either Deployment or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.Deployment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - def _delete_initial( # pylint: disable=inconsistent-return-statements + 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.Deployment] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + account_name=account_name, + deployment_name=deployment_name, + deployment=deployment, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Deployment", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.Deployment].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.Deployment]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial( self, resource_group_name: str, account_name: str, deployment_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -616,39 +859,42 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements _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[None] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, deployment_name=deployment_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - _delete_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}" - } + return deserialized # type: ignore @distributed_trace def begin_delete( @@ -664,14 +910,6 @@ def begin_delete( :param deployment_name: The name of the deployment associated with the Cognitive Services Account. Required. :type deployment_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -685,7 +923,7 @@ def begin_delete( lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( # type: ignore + raw_result = self._delete_initial( resource_group_name=resource_group_name, account_name=account_name, deployment_name=deployment_name, @@ -695,11 +933,12 @@ def begin_delete( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) @@ -708,14 +947,98 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}" - } + @distributed_trace + def list_skus( + self, resource_group_name: str, account_name: str, deployment_name: str, **kwargs: Any + ) -> Iterable["_models.SkuResource"]: + """Lists the specified deployments skus associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param deployment_name: The name of the deployment associated with the Cognitive Services + Account. Required. + :type deployment_name: str + :return: An iterator like instance of either SkuResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.SkuResource] + :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.DeploymentSkuListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_skus_request( + resource_group_name=resource_group_name, + account_name=account_name, + deployment_name=deployment_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DeploymentSkuListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_encryption_scopes_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_encryption_scopes_operations.py new file mode 100644 index 000000000000..b9070fe47ada --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_encryption_scopes_operations.py @@ -0,0 +1,617 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(resource_group_name: str, account_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/encryptionScopes", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + resource_group_name: str, account_name: str, encryption_scope_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/encryptionScopes/{encryptionScopeName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "encryptionScopeName": _SERIALIZER.url( + "encryption_scope_name", encryption_scope_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, account_name: str, encryption_scope_name: str, subscription_id: 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", "2024-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/encryptionScopes/{encryptionScopeName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "encryptionScopeName": _SERIALIZER.url( + "encryption_scope_name", encryption_scope_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _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") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, account_name: str, encryption_scope_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/encryptionScopes/{encryptionScopeName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "encryptionScopeName": _SERIALIZER.url( + "encryption_scope_name", encryption_scope_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class EncryptionScopesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.CognitiveServicesManagementClient`'s + :attr:`encryption_scopes` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> Iterable["_models.EncryptionScope"]: + """Gets the content filters associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :return: An iterator like instance of either EncryptionScope or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.EncryptionScope] + :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.EncryptionScopeListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("EncryptionScopeListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get( + self, resource_group_name: str, account_name: str, encryption_scope_name: str, **kwargs: Any + ) -> _models.EncryptionScope: + """Gets the specified EncryptionScope associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param encryption_scope_name: The name of the encryptionScope associated with the Cognitive + Services Account. Required. + :type encryption_scope_name: str + :return: EncryptionScope or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.EncryptionScope + :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.EncryptionScope] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + encryption_scope_name=encryption_scope_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("EncryptionScope", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, + resource_group_name: str, + account_name: str, + encryption_scope_name: str, + encryption_scope: _models.EncryptionScope, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EncryptionScope: + """Update the state of specified encryptionScope associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param encryption_scope_name: The name of the encryptionScope associated with the Cognitive + Services Account. Required. + :type encryption_scope_name: str + :param encryption_scope: The encryptionScope properties. Required. + :type encryption_scope: ~azure.mgmt.cognitiveservices.models.EncryptionScope + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EncryptionScope or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.EncryptionScope + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + account_name: str, + encryption_scope_name: str, + encryption_scope: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EncryptionScope: + """Update the state of specified encryptionScope associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param encryption_scope_name: The name of the encryptionScope associated with the Cognitive + Services Account. Required. + :type encryption_scope_name: str + :param encryption_scope: The encryptionScope properties. Required. + :type encryption_scope: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: EncryptionScope or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.EncryptionScope + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + account_name: str, + encryption_scope_name: str, + encryption_scope: Union[_models.EncryptionScope, IO[bytes]], + **kwargs: Any + ) -> _models.EncryptionScope: + """Update the state of specified encryptionScope associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param encryption_scope_name: The name of the encryptionScope associated with the Cognitive + Services Account. Required. + :type encryption_scope_name: str + :param encryption_scope: The encryptionScope properties. Is either a EncryptionScope type or a + IO[bytes] type. Required. + :type encryption_scope: ~azure.mgmt.cognitiveservices.models.EncryptionScope or IO[bytes] + :return: EncryptionScope or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.EncryptionScope + :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 = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.EncryptionScope] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(encryption_scope, (IOBase, bytes)): + _content = encryption_scope + else: + _json = self._serialize.body(encryption_scope, "EncryptionScope") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + encryption_scope_name=encryption_scope_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("EncryptionScope", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _delete_initial( + self, resource_group_name: str, account_name: str, encryption_scope_name: str, **kwargs: Any + ) -> Iterator[bytes]: + 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[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + encryption_scope_name=encryption_scope_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + 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 [202, 204]: + 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete( + self, resource_group_name: str, account_name: str, encryption_scope_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes the specified encryptionScope associated with the Cognitive Services account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param encryption_scope_name: The name of the encryptionScope associated with the Cognitive + Services Account. Required. + :type encryption_scope_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :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[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + encryption_scope_name=encryption_scope_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_location_based_model_capacities_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_location_based_model_capacities_operations.py new file mode 100644 index 000000000000..a15bd5a3df0c --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_location_based_model_capacities_operations.py @@ -0,0 +1,187 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + location: str, subscription_id: str, *, model_format: str, model_name: str, model_version: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/modelCapacities", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["modelFormat"] = _SERIALIZER.query( + "model_format", model_format, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ) + _params["modelName"] = _SERIALIZER.query("model_name", model_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$") + _params["modelVersion"] = _SERIALIZER.query( + "model_version", model_version, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class LocationBasedModelCapacitiesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.CognitiveServicesManagementClient`'s + :attr:`location_based_model_capacities` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, location: str, model_format: str, model_name: str, model_version: str, **kwargs: Any + ) -> Iterable["_models.ModelCapacityListResultValueItem"]: + """List Location Based ModelCapacities. + + :param location: Resource location. Required. + :type location: str + :param model_format: The format of the Model. Required. + :type model_format: str + :param model_name: The name of the Model. Required. + :type model_name: str + :param model_version: The version of the Model. Required. + :type model_version: str + :return: An iterator like instance of either ModelCapacityListResultValueItem or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.ModelCapacityListResultValueItem] + :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.ModelCapacityListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + location=location, + subscription_id=self._config.subscription_id, + model_format=model_format, + model_name=model_name, + model_version=model_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ModelCapacityListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_model_capacities_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_model_capacities_operations.py new file mode 100644 index 000000000000..08c80d5efe48 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_model_capacities_operations.py @@ -0,0 +1,182 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + subscription_id: str, *, model_format: str, model_name: str, model_version: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/modelCapacities" + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["modelFormat"] = _SERIALIZER.query( + "model_format", model_format, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ) + _params["modelName"] = _SERIALIZER.query("model_name", model_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$") + _params["modelVersion"] = _SERIALIZER.query( + "model_version", model_version, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ModelCapacitiesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.CognitiveServicesManagementClient`'s + :attr:`model_capacities` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, model_format: str, model_name: str, model_version: str, **kwargs: Any + ) -> Iterable["_models.ModelCapacityListResultValueItem"]: + """List ModelCapacities. + + :param model_format: The format of the Model. Required. + :type model_format: str + :param model_name: The name of the Model. Required. + :type model_name: str + :param model_version: The version of the Model. Required. + :type model_version: str + :return: An iterator like instance of either ModelCapacityListResultValueItem or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.ModelCapacityListResultValueItem] + :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.ModelCapacityListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + subscription_id=self._config.subscription_id, + model_format=model_format, + model_name=model_name, + model_version=model_version, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ModelCapacityListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_models_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_models_operations.py index ede90845c4f7..ba67f2b389cf 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_models_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_models_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar import urllib.parse from azure.core.exceptions import ( @@ -19,16 +20,18 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import CognitiveServicesManagementClientMixinABC, _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -40,7 +43,7 @@ def build_list_request(location: str, subscription_id: str, **kwargs: Any) -> Ht _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -53,7 +56,7 @@ def build_list_request(location: str, subscription_id: str, **kwargs: Any) -> Ht "location": _SERIALIZER.url("location", location, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -89,7 +92,6 @@ def list(self, location: str, **kwargs: Any) -> Iterable["_models.Model"]: :param location: Resource location. Required. :type location: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Model or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.Model] :raises ~azure.core.exceptions.HttpResponseError: @@ -100,7 +102,7 @@ def list(self, location: str, **kwargs: Any) -> Iterable["_models.Model"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ModelListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -111,16 +113,14 @@ def list(self, location: str, **kwargs: Any) -> Iterable["_models.Model"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( location=location, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -132,13 +132,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ModelListResult", pipeline_response) @@ -148,11 +147,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -164,7 +163,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/models" - } diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_network_security_perimeter_configurations_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_network_security_perimeter_configurations_operations.py new file mode 100644 index 000000000000..f7b825b1d952 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_network_security_perimeter_configurations_operations.py @@ -0,0 +1,441 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Iterator, Optional, Type, TypeVar, Union, cast +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(resource_group_name: str, account_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/networkSecurityPerimeterConfigurations", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + resource_group_name: str, account_name: str, nsp_configuration_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/networkSecurityPerimeterConfigurations/{nspConfigurationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "nspConfigurationName": _SERIALIZER.url( + "nsp_configuration_name", nsp_configuration_name, "str", pattern=r"^.*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reconcile_request( + resource_group_name: str, account_name: str, nsp_configuration_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/networkSecurityPerimeterConfigurations/{nspConfigurationName}/reconcile", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "nspConfigurationName": _SERIALIZER.url( + "nsp_configuration_name", nsp_configuration_name, "str", pattern=r"^.*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class NetworkSecurityPerimeterConfigurationsOperations: # pylint: disable=name-too-long + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.CognitiveServicesManagementClient`'s + :attr:`network_security_perimeter_configurations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, account_name: str, **kwargs: Any + ) -> Iterable["_models.NetworkSecurityPerimeterConfiguration"]: + """Gets a list of NSP configurations for an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :return: An iterator like instance of either NetworkSecurityPerimeterConfiguration or the + result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterConfiguration] + :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.NetworkSecurityPerimeterConfigurationList] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("NetworkSecurityPerimeterConfigurationList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get( + self, resource_group_name: str, account_name: str, nsp_configuration_name: str, **kwargs: Any + ) -> _models.NetworkSecurityPerimeterConfiguration: + """Gets the specified NSP configurations for an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param nsp_configuration_name: The name of the NSP Configuration. Required. + :type nsp_configuration_name: str + :return: NetworkSecurityPerimeterConfiguration or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterConfiguration + :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.NetworkSecurityPerimeterConfiguration] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + nsp_configuration_name=nsp_configuration_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("NetworkSecurityPerimeterConfiguration", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _reconcile_initial( + self, resource_group_name: str, account_name: str, nsp_configuration_name: str, **kwargs: Any + ) -> Iterator[bytes]: + 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[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_reconcile_request( + resource_group_name=resource_group_name, + account_name=account_name, + nsp_configuration_name=nsp_configuration_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + 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, 202]: + 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_reconcile( + self, resource_group_name: str, account_name: str, nsp_configuration_name: str, **kwargs: Any + ) -> LROPoller[_models.NetworkSecurityPerimeterConfiguration]: + """Reconcile the NSP configuration for an account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param nsp_configuration_name: The name of the NSP Configuration. Required. + :type nsp_configuration_name: str + :return: An instance of LROPoller that returns either NetworkSecurityPerimeterConfiguration or + the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.cognitiveservices.models.NetworkSecurityPerimeterConfiguration] + :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.NetworkSecurityPerimeterConfiguration] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._reconcile_initial( + resource_group_name=resource_group_name, + account_name=account_name, + nsp_configuration_name=nsp_configuration_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("NetworkSecurityPerimeterConfiguration", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.NetworkSecurityPerimeterConfiguration].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.NetworkSecurityPerimeterConfiguration]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_operations.py index d101497980fe..498d2fae7a7d 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar import urllib.parse from azure.core.exceptions import ( @@ -19,16 +20,18 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import CognitiveServicesManagementClientMixinABC, _convert_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -40,7 +43,7 @@ def build_list_request(**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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -78,7 +81,6 @@ def __init__(self, *args, **kwargs): def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists all the available Cognitive Services account operations. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: @@ -89,7 +91,7 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -100,14 +102,12 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -119,13 +119,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) @@ -135,11 +134,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -151,5 +150,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.CognitiveServices/operations"} diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_private_endpoint_connections_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_private_endpoint_connections_operations.py index 687324b670c7..d61ee9109250 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_private_endpoint_connections_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_private_endpoint_connections_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from io import IOBase -from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import sys +from typing import Any, Callable, Dict, IO, Iterator, Optional, Type, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -15,12 +16,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat @@ -28,8 +30,11 @@ from .. import models as _models from .._serialization import Serializer -from .._vendor import CognitiveServicesManagementClientMixinABC, _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -41,7 +46,7 @@ def build_list_request(resource_group_name: str, account_name: str, subscription _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -59,7 +64,7 @@ def build_list_request(resource_group_name: str, account_name: str, subscription "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -80,7 +85,7 @@ def build_get_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -101,7 +106,7 @@ def build_get_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -122,7 +127,7 @@ def build_create_or_update_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -144,7 +149,7 @@ def build_create_or_update_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -167,7 +172,7 @@ def build_delete_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -188,7 +193,7 @@ def build_delete_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -229,12 +234,11 @@ def list( :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateEndpointConnectionListResult or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.PrivateEndpointConnectionListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -248,21 +252,19 @@ def list( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PrivateEndpointConnectionListResult] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -272,16 +274,12 @@ def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections" - } + return deserialized # type: ignore @distributed_trace def get( @@ -297,12 +295,11 @@ def get( :param private_endpoint_connection_name: The name of the private endpoint connection associated with the Cognitive Services Account. Required. :type private_endpoint_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.PrivateEndpointConnection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -316,22 +313,20 @@ def get( api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -341,26 +336,22 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore def _create_or_update_initial( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, - properties: Union[_models.PrivateEndpointConnection, IO], + properties: Union[_models.PrivateEndpointConnection, IO[bytes]], **kwargs: Any - ) -> _models.PrivateEndpointConnection: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -373,7 +364,7 @@ def _create_or_update_initial( 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.PrivateEndpointConnection] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None @@ -383,7 +374,7 @@ def _create_or_update_initial( else: _json = self._serialize.body(properties, "PrivateEndpointConnection") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -392,40 +383,35 @@ def _create_or_update_initial( content_type=content_type, json=_json, content=_content, - template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) - - if response.status_code == 202: - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" - } - @overload def begin_create_or_update( self, @@ -453,14 +439,6 @@ def begin_create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: @@ -474,7 +452,7 @@ def begin_create_or_update( resource_group_name: str, account_name: str, private_endpoint_connection_name: str, - properties: IO, + properties: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -491,18 +469,10 @@ def begin_create_or_update( with the Cognitive Services Account. Required. :type private_endpoint_connection_name: str :param properties: The private endpoint connection properties. Required. - :type properties: IO + :type properties: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: @@ -516,7 +486,7 @@ def begin_create_or_update( resource_group_name: str, account_name: str, private_endpoint_connection_name: str, - properties: Union[_models.PrivateEndpointConnection, IO], + properties: Union[_models.PrivateEndpointConnection, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.PrivateEndpointConnection]: """Update the state of specified private endpoint connection associated with the Cognitive @@ -531,19 +501,8 @@ def begin_create_or_update( with the Cognitive Services Account. Required. :type private_endpoint_connection_name: str :param properties: The private endpoint connection properties. Is either a - PrivateEndpointConnection type or a IO type. Required. - :type properties: ~azure.mgmt.cognitiveservices.models.PrivateEndpointConnection or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + PrivateEndpointConnection type or a IO[bytes] type. Required. + :type properties: ~azure.mgmt.cognitiveservices.models.PrivateEndpointConnection or IO[bytes] :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: @@ -572,12 +531,13 @@ def begin_create_or_update( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -587,22 +547,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.PrivateEndpointConnection].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return LROPoller[_models.PrivateEndpointConnection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - def _delete_initial( # pylint: disable=inconsistent-return-statements + def _delete_initial( self, resource_group_name: str, account_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -614,39 +572,42 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements _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[None] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + 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.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - _delete_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore @distributed_trace def begin_delete( @@ -663,14 +624,6 @@ def begin_delete( :param private_endpoint_connection_name: The name of the private endpoint connection associated with the Cognitive Services Account. Required. :type private_endpoint_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -684,7 +637,7 @@ def begin_delete( lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( # type: ignore + raw_result = self._delete_initial( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -694,11 +647,12 @@ def begin_delete( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) @@ -707,14 +661,10 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_private_link_resources_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_private_link_resources_operations.py index f45b5a3b9a67..3ee1d266a568 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_private_link_resources_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_private_link_resources_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar +import sys +from typing import Any, Callable, Dict, Optional, Type, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, @@ -17,16 +18,18 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import CognitiveServicesManagementClientMixinABC, _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -38,7 +41,7 @@ def build_list_request(resource_group_name: str, account_name: str, subscription _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -56,7 +59,7 @@ def build_list_request(resource_group_name: str, account_name: str, subscription "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -95,12 +98,11 @@ def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _m :type resource_group_name: str :param account_name: The name of Cognitive Services account. Required. :type account_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateLinkResourceListResult or the result of cls(response) :rtype: ~azure.mgmt.cognitiveservices.models.PrivateLinkResourceListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -114,21 +116,19 @@ def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _m api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.PrivateLinkResourceListResult] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_group_name=resource_group_name, account_name=account_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -138,13 +138,9 @@ def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> _m error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) + deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateLinkResources" - } + return deserialized # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_rai_blocklist_items_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_rai_blocklist_items_operations.py new file mode 100644 index 000000000000..23b61f3156a0 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_rai_blocklist_items_operations.py @@ -0,0 +1,996 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, List, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + resource_group_name: str, account_name: str, rai_blocklist_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}/raiBlocklistItems", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "raiBlocklistName": _SERIALIZER.url( + "rai_blocklist_name", rai_blocklist_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_item_name: str, + subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}/raiBlocklistItems/{raiBlocklistItemName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "raiBlocklistName": _SERIALIZER.url( + "rai_blocklist_name", rai_blocklist_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "raiBlocklistItemName": _SERIALIZER.url( + "rai_blocklist_item_name", rai_blocklist_item_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_item_name: str, + subscription_id: 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", "2024-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}/raiBlocklistItems/{raiBlocklistItemName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "raiBlocklistName": _SERIALIZER.url( + "rai_blocklist_name", rai_blocklist_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "raiBlocklistItemName": _SERIALIZER.url( + "rai_blocklist_item_name", rai_blocklist_item_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _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") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_item_name: str, + subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}/raiBlocklistItems/{raiBlocklistItemName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "raiBlocklistName": _SERIALIZER.url( + "rai_blocklist_name", rai_blocklist_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "raiBlocklistItemName": _SERIALIZER.url( + "rai_blocklist_item_name", rai_blocklist_item_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_batch_add_request( + resource_group_name: str, account_name: str, rai_blocklist_name: str, subscription_id: 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", "2024-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}/addRaiBlocklistItems", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "raiBlocklistName": _SERIALIZER.url( + "rai_blocklist_name", rai_blocklist_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _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") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_batch_delete_request( + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + subscription_id: str, + *, + json: JSON, + **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", "2024-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}/deleteRaiBlocklistItems", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "raiBlocklistName": _SERIALIZER.url( + "rai_blocklist_name", rai_blocklist_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _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") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, json=json, **kwargs) + + +class RaiBlocklistItemsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.CognitiveServicesManagementClient`'s + :attr:`rai_blocklist_items` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, account_name: str, rai_blocklist_name: str, **kwargs: Any + ) -> Iterable["_models.RaiBlocklistItem"]: + """Gets the blocklist items associated with the custom blocklist. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :return: An iterator like instance of either RaiBlocklistItem or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.RaiBlocklistItem] + :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.RaiBlockListItemsResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RaiBlockListItemsResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_item_name: str, + **kwargs: Any + ) -> _models.RaiBlocklistItem: + """Gets the specified custom blocklist Item associated with the custom blocklist. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_item_name: The name of the RaiBlocklist Item associated with the custom + blocklist. Required. + :type rai_blocklist_item_name: str + :return: RaiBlocklistItem or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItem + :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.RaiBlocklistItem] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + rai_blocklist_item_name=rai_blocklist_item_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiBlocklistItem", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_item_name: str, + rai_blocklist_item: _models.RaiBlocklistItem, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiBlocklistItem: + """Update the state of specified blocklist item associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_item_name: The name of the RaiBlocklist Item associated with the custom + blocklist. Required. + :type rai_blocklist_item_name: str + :param rai_blocklist_item: Properties describing the custom blocklist. Required. + :type rai_blocklist_item: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItem + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiBlocklistItem or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItem + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_item_name: str, + rai_blocklist_item: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiBlocklistItem: + """Update the state of specified blocklist item associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_item_name: The name of the RaiBlocklist Item associated with the custom + blocklist. Required. + :type rai_blocklist_item_name: str + :param rai_blocklist_item: Properties describing the custom blocklist. Required. + :type rai_blocklist_item: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiBlocklistItem or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItem + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_item_name: str, + rai_blocklist_item: Union[_models.RaiBlocklistItem, IO[bytes]], + **kwargs: Any + ) -> _models.RaiBlocklistItem: + """Update the state of specified blocklist item associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_item_name: The name of the RaiBlocklist Item associated with the custom + blocklist. Required. + :type rai_blocklist_item_name: str + :param rai_blocklist_item: Properties describing the custom blocklist. Is either a + RaiBlocklistItem type or a IO[bytes] type. Required. + :type rai_blocklist_item: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItem or IO[bytes] + :return: RaiBlocklistItem or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklistItem + :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 = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RaiBlocklistItem] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(rai_blocklist_item, (IOBase, bytes)): + _content = rai_blocklist_item + else: + _json = self._serialize.body(rai_blocklist_item, "RaiBlocklistItem") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + rai_blocklist_item_name=rai_blocklist_item_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiBlocklistItem", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _delete_initial( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_item_name: str, + **kwargs: Any + ) -> Iterator[bytes]: + 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[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + rai_blocklist_item_name=rai_blocklist_item_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + 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 [202, 204]: + 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_item_name: str, + **kwargs: Any + ) -> LROPoller[None]: + """Deletes the specified blocklist Item associated with the custom blocklist. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_item_name: The name of the RaiBlocklist Item associated with the custom + blocklist. Required. + :type rai_blocklist_item_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :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[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + rai_blocklist_item_name=rai_blocklist_item_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @overload + def batch_add( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_items: List[_models.RaiBlocklistItemBulkRequest], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiBlocklist: + """Batch operation to add blocklist items. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_items: Properties describing the custom blocklist items. Required. + :type rai_blocklist_items: + list[~azure.mgmt.cognitiveservices.models.RaiBlocklistItemBulkRequest] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiBlocklist or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def batch_add( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_items: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiBlocklist: + """Batch operation to add blocklist items. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_items: Properties describing the custom blocklist items. Required. + :type rai_blocklist_items: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiBlocklist or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def batch_add( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_items: Union[List[_models.RaiBlocklistItemBulkRequest], IO[bytes]], + **kwargs: Any + ) -> _models.RaiBlocklist: + """Batch operation to add blocklist items. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_items: Properties describing the custom blocklist items. Is either a + [RaiBlocklistItemBulkRequest] type or a IO[bytes] type. Required. + :type rai_blocklist_items: + list[~azure.mgmt.cognitiveservices.models.RaiBlocklistItemBulkRequest] or IO[bytes] + :return: RaiBlocklist or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :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 = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RaiBlocklist] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(rai_blocklist_items, (IOBase, bytes)): + _content = rai_blocklist_items + else: + _json = self._serialize.body(rai_blocklist_items, "[RaiBlocklistItemBulkRequest]") + + _request = build_batch_add_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiBlocklist", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def batch_delete( # pylint: disable=inconsistent-return-statements + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist_items_names: JSON, + **kwargs: Any + ) -> None: + """Batch operation to delete blocklist items. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist_items_names: List of RAI Blocklist Items Names. Required. + :type rai_blocklist_items_names: JSON + :return: None or the result of cls(response) + :rtype: None + :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 = 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", self._config.api_version)) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _json = self._serialize.body(rai_blocklist_items_names, "object") + + _request = build_batch_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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 [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_rai_blocklists_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_rai_blocklists_operations.py new file mode 100644 index 000000000000..65f36bc9dbc5 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_rai_blocklists_operations.py @@ -0,0 +1,619 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(resource_group_name: str, account_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + resource_group_name: str, account_name: str, rai_blocklist_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "raiBlocklistName": _SERIALIZER.url( + "rai_blocklist_name", rai_blocklist_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, account_name: str, rai_blocklist_name: str, subscription_id: 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", "2024-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "raiBlocklistName": _SERIALIZER.url( + "rai_blocklist_name", rai_blocklist_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _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") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, account_name: str, rai_blocklist_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "raiBlocklistName": _SERIALIZER.url( + "rai_blocklist_name", rai_blocklist_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class RaiBlocklistsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.CognitiveServicesManagementClient`'s + :attr:`rai_blocklists` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> Iterable["_models.RaiBlocklist"]: + """Gets the custom blocklists associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :return: An iterator like instance of either RaiBlocklist or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.RaiBlocklist] + :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.RaiBlockListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RaiBlockListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get( + self, resource_group_name: str, account_name: str, rai_blocklist_name: str, **kwargs: Any + ) -> _models.RaiBlocklist: + """Gets the specified custom blocklist associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :return: RaiBlocklist or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :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.RaiBlocklist] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiBlocklist", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist: _models.RaiBlocklist, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiBlocklist: + """Update the state of specified blocklist associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist: Properties describing the custom blocklist. Required. + :type rai_blocklist: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiBlocklist or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiBlocklist: + """Update the state of specified blocklist associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist: Properties describing the custom blocklist. Required. + :type rai_blocklist: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiBlocklist or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_blocklist_name: str, + rai_blocklist: Union[_models.RaiBlocklist, IO[bytes]], + **kwargs: Any + ) -> _models.RaiBlocklist: + """Update the state of specified blocklist associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :param rai_blocklist: Properties describing the custom blocklist. Is either a RaiBlocklist type + or a IO[bytes] type. Required. + :type rai_blocklist: ~azure.mgmt.cognitiveservices.models.RaiBlocklist or IO[bytes] + :return: RaiBlocklist or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiBlocklist + :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 = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RaiBlocklist] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(rai_blocklist, (IOBase, bytes)): + _content = rai_blocklist + else: + _json = self._serialize.body(rai_blocklist, "RaiBlocklist") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiBlocklist", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _delete_initial( + self, resource_group_name: str, account_name: str, rai_blocklist_name: str, **kwargs: Any + ) -> Iterator[bytes]: + 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[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + 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 [202, 204]: + 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete( + self, resource_group_name: str, account_name: str, rai_blocklist_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes the specified custom blocklist associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_blocklist_name: The name of the RaiBlocklist associated with the Cognitive Services + Account. Required. + :type rai_blocklist_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :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[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + rai_blocklist_name=rai_blocklist_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_rai_content_filters_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_rai_content_filters_operations.py new file mode 100644 index 000000000000..5b762d57fc27 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_rai_content_filters_operations.py @@ -0,0 +1,249 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(location: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/raiContentFilters", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(location: str, filter_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/raiContentFilters/{filterName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str"), + "filterName": _SERIALIZER.url("filter_name", filter_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RaiContentFiltersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.CognitiveServicesManagementClient`'s + :attr:`rai_content_filters` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, location: str, **kwargs: Any) -> Iterable["_models.RaiContentFilter"]: + """List Content Filters types. + + :param location: Resource location. Required. + :type location: str + :return: An iterator like instance of either RaiContentFilter or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.RaiContentFilter] + :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.RaiContentFilterListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + location=location, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RaiContentFilterListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get(self, location: str, filter_name: str, **kwargs: Any) -> _models.RaiContentFilter: + """Get Content Filters by Name. + + :param location: Resource location. Required. + :type location: str + :param filter_name: The name of the RAI Content Filter. Required. + :type filter_name: str + :return: RaiContentFilter or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiContentFilter + :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.RaiContentFilter] = kwargs.pop("cls", None) + + _request = build_get_request( + location=location, + filter_name=filter_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiContentFilter", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_rai_policies_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_rai_policies_operations.py new file mode 100644 index 000000000000..30c660614d87 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_rai_policies_operations.py @@ -0,0 +1,619 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(resource_group_name: str, account_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiPolicies", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + resource_group_name: str, account_name: str, rai_policy_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiPolicies/{raiPolicyName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "raiPolicyName": _SERIALIZER.url( + "rai_policy_name", rai_policy_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, account_name: str, rai_policy_name: str, subscription_id: 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", "2024-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiPolicies/{raiPolicyName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "raiPolicyName": _SERIALIZER.url( + "rai_policy_name", rai_policy_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _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") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, account_name: str, rai_policy_name: str, subscription_id: 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", "2024-10-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiPolicies/{raiPolicyName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "accountName": _SERIALIZER.url( + "account_name", account_name, "str", max_length=64, min_length=2, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "raiPolicyName": _SERIALIZER.url( + "rai_policy_name", rai_policy_name, "str", pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class RaiPoliciesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.cognitiveservices.CognitiveServicesManagementClient`'s + :attr:`rai_policies` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, resource_group_name: str, account_name: str, **kwargs: Any) -> Iterable["_models.RaiPolicy"]: + """Gets the content filters associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :return: An iterator like instance of either RaiPolicy or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.RaiPolicy] + :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.RaiPolicyListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 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_list_request( + resource_group_name=resource_group_name, + account_name=account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + 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 + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RaiPolicyListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get( + self, resource_group_name: str, account_name: str, rai_policy_name: str, **kwargs: Any + ) -> _models.RaiPolicy: + """Gets the specified Content Filters associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_policy_name: The name of the RaiPolicy associated with the Cognitive Services + Account. Required. + :type rai_policy_name: str + :return: RaiPolicy or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiPolicy + :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.RaiPolicy] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_policy_name=rai_policy_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiPolicy", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_policy_name: str, + rai_policy: _models.RaiPolicy, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiPolicy: + """Update the state of specified Content Filters associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_policy_name: The name of the RaiPolicy associated with the Cognitive Services + Account. Required. + :type rai_policy_name: str + :param rai_policy: Properties describing the Content Filters. Required. + :type rai_policy: ~azure.mgmt.cognitiveservices.models.RaiPolicy + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiPolicy or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_policy_name: str, + rai_policy: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RaiPolicy: + """Update the state of specified Content Filters associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_policy_name: The name of the RaiPolicy associated with the Cognitive Services + Account. Required. + :type rai_policy_name: str + :param rai_policy: Properties describing the Content Filters. Required. + :type rai_policy: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RaiPolicy or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + account_name: str, + rai_policy_name: str, + rai_policy: Union[_models.RaiPolicy, IO[bytes]], + **kwargs: Any + ) -> _models.RaiPolicy: + """Update the state of specified Content Filters associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_policy_name: The name of the RaiPolicy associated with the Cognitive Services + Account. Required. + :type rai_policy_name: str + :param rai_policy: Properties describing the Content Filters. Is either a RaiPolicy type or a + IO[bytes] type. Required. + :type rai_policy: ~azure.mgmt.cognitiveservices.models.RaiPolicy or IO[bytes] + :return: RaiPolicy or the result of cls(response) + :rtype: ~azure.mgmt.cognitiveservices.models.RaiPolicy + :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 = 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", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RaiPolicy] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(rai_policy, (IOBase, bytes)): + _content = rai_policy + else: + _json = self._serialize.body(rai_policy, "RaiPolicy") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_policy_name=rai_policy_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _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, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RaiPolicy", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _delete_initial( + self, resource_group_name: str, account_name: str, rai_policy_name: str, **kwargs: Any + ) -> Iterator[bytes]: + 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[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + account_name=account_name, + rai_policy_name=rai_policy_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + 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 [202, 204]: + 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["location"] = self._deserialize("str", response.headers.get("location")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete( + self, resource_group_name: str, account_name: str, rai_policy_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes the specified Content Filters associated with the Azure OpenAI account. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param account_name: The name of Cognitive Services account. Required. + :type account_name: str + :param rai_policy_name: The name of the RaiPolicy associated with the Cognitive Services + Account. Required. + :type rai_policy_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :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[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + account_name=account_name, + rai_policy_name=rai_policy_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_resource_skus_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_resource_skus_operations.py index a30c5ca819a6..54248937d0f1 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_resource_skus_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_resource_skus_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar import urllib.parse from azure.core.exceptions import ( @@ -19,16 +20,18 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import CognitiveServicesManagementClientMixinABC, _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -40,7 +43,7 @@ def build_list_request(subscription_id: 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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -49,7 +52,7 @@ def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -83,7 +86,6 @@ def __init__(self, *args, **kwargs): def list(self, **kwargs: Any) -> Iterable["_models.ResourceSku"]: """Gets the list of Microsoft.CognitiveServices SKUs available for your Subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ResourceSku or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.ResourceSku] :raises ~azure.core.exceptions.HttpResponseError: @@ -94,7 +96,7 @@ def list(self, **kwargs: Any) -> Iterable["_models.ResourceSku"]: api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ResourceSkuListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -105,15 +107,13 @@ def list(self, **kwargs: Any) -> Iterable["_models.ResourceSku"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -125,13 +125,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ResourceSkuListResult", pipeline_response) @@ -141,11 +140,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -157,5 +156,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/skus"} diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_usages_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_usages_operations.py index 5ac6eac7b9cf..742bbd2ef2cb 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_usages_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_usages_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar import urllib.parse from azure.core.exceptions import ( @@ -19,16 +20,18 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models from .._serialization import Serializer -from .._vendor import CognitiveServicesManagementClientMixinABC, _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -42,7 +45,7 @@ def build_list_request( _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-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -55,7 +58,7 @@ def build_list_request( "location": _SERIALIZER.url("location", location, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -97,7 +100,6 @@ def list(self, location: str, filter: Optional[str] = None, **kwargs: Any) -> It supported parameter is name.value (name of the metric, can have an or of multiple names). Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Usage or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cognitiveservices.models.Usage] :raises ~azure.core.exceptions.HttpResponseError: @@ -108,7 +110,7 @@ def list(self, location: str, filter: Optional[str] = None, **kwargs: Any) -> It api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.UsageListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -119,17 +121,15 @@ def list(self, location: str, filter: Optional[str] = None, **kwargs: Any) -> It def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( location=location, subscription_id=self._config.subscription_id, filter=filter, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -141,13 +141,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("UsageListResult", pipeline_response) @@ -157,11 +156,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -173,7 +172,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/usages" - } diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/add_rai_blocklist_items.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/add_rai_blocklist_items.py new file mode 100644 index 000000000000..6c104e916adf --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/add_rai_blocklist_items.py @@ -0,0 +1,47 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python add_rai_blocklist_items.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.rai_blocklist_items.batch_add( + resource_group_name="resourceGroupName", + account_name="accountName", + rai_blocklist_name="myblocklist", + rai_blocklist_items=[ + {"name": "myblocklistitem1", "properties": {"isRegex": True, "pattern": "^[a-z0-9_-]{2,16}$"}}, + {"name": "myblocklistitem2", "properties": {"isRegex": False, "pattern": "blockwords"}}, + ], + ) + print(response) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/AddRaiBlocklistItems.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/calculate_model_capacity.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/calculate_model_capacity.py new file mode 100644 index 000000000000..8347b83e5028 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/calculate_model_capacity.py @@ -0,0 +1,39 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python calculate_model_capacity.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", + ) + + response = client.calculate_model_capacity() + print(response) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/CalculateModelCapacity.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_account.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_account.py index b7d83a6efc18..2a1c559e7847 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_account.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -57,6 +58,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/CreateAccount.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/CreateAccount.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_account_min.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_account_min.py index 4b387803291f..f2d26bd1dc40 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_account_min.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_account_min.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -43,6 +44,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/CreateAccountMin.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/CreateAccountMin.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_shared_commitment_plan.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_shared_commitment_plan.py index 55335a3bb966..04d2dd4e75ef 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_shared_commitment_plan.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_shared_commitment_plan.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -42,6 +43,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/CreateSharedCommitmentPlan.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/CreateSharedCommitmentPlan.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_shared_commitment_plan_association.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_shared_commitment_plan_association.py index ea81114d35ca..d11ac9afe703 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_shared_commitment_plan_association.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/create_shared_commitment_plan_association.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -42,6 +43,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/CreateSharedCommitmentPlanAssociation.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/CreateSharedCommitmentPlanAssociation.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_account.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_account.py index 9f757f111d3e..2d16752e4c32 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_account.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -35,6 +36,6 @@ def main(): ).result() -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/DeleteAccount.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/DeleteAccount.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_commitment_plan.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_commitment_plan.py index 5a00237f4a1b..19d717a8217f 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_commitment_plan.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_commitment_plan.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): ).result() -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/DeleteCommitmentPlan.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/DeleteCommitmentPlan.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_deployment.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_deployment.py index b202a2f9dd08..65f919209721 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_deployment.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_deployment.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): ).result() -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/DeleteDeployment.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/DeleteDeployment.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_encryption_scope.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_encryption_scope.py new file mode 100644 index 000000000000..192358b28d9d --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_encryption_scope.py @@ -0,0 +1,42 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python delete_encryption_scope.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + client.encryption_scopes.begin_delete( + resource_group_name="resourceGroupName", + account_name="accountName", + encryption_scope_name="encryptionScopeName", + ).result() + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/DeleteEncryptionScope.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_private_endpoint_connection.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_private_endpoint_connection.py index 4d89790032e4..8bea51f398d5 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_private_endpoint_connection.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_private_endpoint_connection.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): ).result() -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/DeletePrivateEndpointConnection.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/DeletePrivateEndpointConnection.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_rai_blocklist.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_rai_blocklist.py new file mode 100644 index 000000000000..6a5892bcf431 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_rai_blocklist.py @@ -0,0 +1,42 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python delete_rai_blocklist.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + client.rai_blocklists.begin_delete( + resource_group_name="resourceGroupName", + account_name="accountName", + rai_blocklist_name="raiBlocklistName", + ).result() + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/DeleteRaiBlocklist.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_rai_blocklist_item.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_rai_blocklist_item.py new file mode 100644 index 000000000000..c14a28aab878 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_rai_blocklist_item.py @@ -0,0 +1,43 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python delete_rai_blocklist_item.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + client.rai_blocklist_items.begin_delete( + resource_group_name="resourceGroupName", + account_name="accountName", + rai_blocklist_name="raiBlocklistName", + rai_blocklist_item_name="raiBlocklistItemName", + ).result() + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/DeleteRaiBlocklistItem.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_rai_blocklist_items.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_rai_blocklist_items.py new file mode 100644 index 000000000000..0d1028f5aa1d --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_rai_blocklist_items.py @@ -0,0 +1,43 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python delete_rai_blocklist_items.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + client.rai_blocklist_items.batch_delete( + resource_group_name="resourceGroupName", + account_name="accountName", + rai_blocklist_name="raiBlocklistName", + rai_blocklist_items_names=["myblocklistitem1", "myblocklistitem2"], + ) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/DeleteRaiBlocklistItems.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_rai_policy.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_rai_policy.py new file mode 100644 index 000000000000..e266c03dc601 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_rai_policy.py @@ -0,0 +1,42 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python delete_rai_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + client.rai_policies.begin_delete( + resource_group_name="resourceGroupName", + account_name="accountName", + rai_policy_name="raiPolicyName", + ).result() + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/DeleteRaiPolicy.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_shared_commitment_plan.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_shared_commitment_plan.py index d00ff5a24e6f..1791873f304a 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_shared_commitment_plan.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_shared_commitment_plan.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -35,6 +36,6 @@ def main(): ).result() -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/DeleteSharedCommitmentPlan.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/DeleteSharedCommitmentPlan.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_shared_commitment_plan_association.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_shared_commitment_plan_association.py index 64b88eda24e1..c9a67163869d 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_shared_commitment_plan_association.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/delete_shared_commitment_plan_association.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): ).result() -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/DeleteSharedCommitmentPlanAssociation.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/DeleteSharedCommitmentPlanAssociation.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_account.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_account.py index 2556f8438904..1881b8c46079 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_account.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/GetAccount.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetAccount.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_commitment_plan.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_commitment_plan.py index a7a9264a1db1..3598174a6875 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_commitment_plan.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_commitment_plan.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -37,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/GetCommitmentPlan.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetCommitmentPlan.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_defender_for_ai_setting.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_defender_for_ai_setting.py new file mode 100644 index 000000000000..35a84b8457e9 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_defender_for_ai_setting.py @@ -0,0 +1,43 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python get_defender_for_ai_setting.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.defender_for_ai_settings.get( + resource_group_name="resourceGroupName", + account_name="accountName", + defender_for_ai_setting_name="Default", + ) + print(response) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetDefenderForAISetting.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_deleted_account.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_deleted_account.py index ea0b8bdc47da..40dda72c3f7c 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_deleted_account.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_deleted_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -37,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/GetDeletedAccount.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetDeletedAccount.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_deployment.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_deployment.py index fe99b684d8e5..a3a4d524f0e0 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_deployment.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_deployment.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -37,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/GetDeployment.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetDeployment.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_encryption_scope.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_encryption_scope.py new file mode 100644 index 000000000000..ba5cbf44a55f --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_encryption_scope.py @@ -0,0 +1,43 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python get_encryption_scope.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.encryption_scopes.get( + resource_group_name="resourceGroupName", + account_name="accountName", + encryption_scope_name="encryptionScopeName", + ) + print(response) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetEncryptionScope.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_network_security_perimeter_configurations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_network_security_perimeter_configurations.py new file mode 100644 index 000000000000..ae44c6e143d7 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_network_security_perimeter_configurations.py @@ -0,0 +1,43 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python get_network_security_perimeter_configurations.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.network_security_perimeter_configurations.get( + resource_group_name="resourceGroupName", + account_name="accountName", + nsp_configuration_name="NSPConfigurationName", + ) + print(response) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetNetworkSecurityPerimeterConfigurations.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_operations.py index f7e952879586..38776f9f83b7 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_operations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_operations.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -34,6 +35,6 @@ def main(): print(item) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/GetOperations.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetOperations.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_private_endpoint_connection.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_private_endpoint_connection.py index 77228c051511..56da5166c4c4 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_private_endpoint_connection.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_private_endpoint_connection.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -37,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/GetPrivateEndpointConnection.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetPrivateEndpointConnection.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_rai_blocklist.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_rai_blocklist.py new file mode 100644 index 000000000000..2d5a3213df05 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_rai_blocklist.py @@ -0,0 +1,43 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python get_rai_blocklist.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.rai_blocklists.get( + resource_group_name="resourceGroupName", + account_name="accountName", + rai_blocklist_name="raiBlocklistName", + ) + print(response) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetRaiBlocklist.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_rai_blocklist_item.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_rai_blocklist_item.py new file mode 100644 index 000000000000..e951859c73b3 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_rai_blocklist_item.py @@ -0,0 +1,44 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python get_rai_blocklist_item.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.rai_blocklist_items.get( + resource_group_name="resourceGroupName", + account_name="accountName", + rai_blocklist_name="raiBlocklistName", + rai_blocklist_item_name="raiBlocklistItemName", + ) + print(response) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetRaiBlocklistItem.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_rai_content_filter.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_rai_content_filter.py new file mode 100644 index 000000000000..e1d7147b2306 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_rai_content_filter.py @@ -0,0 +1,42 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python get_rai_content_filter.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.rai_content_filters.get( + location="WestUS", + filter_name="IndirectAttack", + ) + print(response) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetRaiContentFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_rai_policy.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_rai_policy.py new file mode 100644 index 000000000000..8e883ce4f930 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_rai_policy.py @@ -0,0 +1,43 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python get_rai_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.rai_policies.get( + resource_group_name="resourceGroupName", + account_name="accountName", + rai_policy_name="raiPolicyName", + ) + print(response) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetRaiPolicy.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_shared_commitment_plan.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_shared_commitment_plan.py index d095d0a18e7a..1a6c21d1cf62 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_shared_commitment_plan.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_shared_commitment_plan.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/GetSharedCommitmentPlan.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetSharedCommitmentPlan.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_shared_commitment_plan_association.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_shared_commitment_plan_association.py index 31dbb4bfc45a..69c381e8f0a7 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_shared_commitment_plan_association.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_shared_commitment_plan_association.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -37,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/GetSharedCommitmentPlanAssociation.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetSharedCommitmentPlanAssociation.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_skus.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_skus.py index e788c8cbb045..786ea31485ab 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_skus.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_skus.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -34,6 +35,6 @@ def main(): print(item) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/GetSkus.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetSkus.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_usages.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_usages.py index 6bca17f6c7b2..88803a4c6b24 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_usages.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/get_usages.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/GetUsages.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/GetUsages.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_account_models.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_account_models.py index cca00e0f0fab..aa9af113805c 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_account_models.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_account_models.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListAccountModels.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListAccountModels.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_accounts_by_resource_group.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_accounts_by_resource_group.py index 2164063843ac..9d5062752922 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_accounts_by_resource_group.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_accounts_by_resource_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListAccountsByResourceGroup.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListAccountsByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_accounts_by_subscription.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_accounts_by_subscription.py index b891f21638ac..7bcf5a77e871 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_accounts_by_subscription.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_accounts_by_subscription.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -34,6 +35,6 @@ def main(): print(item) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListAccountsBySubscription.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListAccountsBySubscription.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_blocklist_items.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_blocklist_items.py new file mode 100644 index 000000000000..016217162532 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_blocklist_items.py @@ -0,0 +1,44 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python list_blocklist_items.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.rai_blocklist_items.list( + resource_group_name="resourceGroupName", + account_name="accountName", + rai_blocklist_name="raiBlocklistName", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListBlocklistItems.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_blocklists.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_blocklists.py new file mode 100644 index 000000000000..a37dbdc54020 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_blocklists.py @@ -0,0 +1,43 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python list_blocklists.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.rai_blocklists.list( + resource_group_name="resourceGroupName", + account_name="accountName", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListBlocklists.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_commitment_plans.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_commitment_plans.py index 05baddbec3a3..30cf8daaf9fb 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_commitment_plans.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_commitment_plans.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListCommitmentPlans.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListCommitmentPlans.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_commitment_tiers.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_commitment_tiers.py index 52026e299a8c..12d2fbde7bb1 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_commitment_tiers.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_commitment_tiers.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListCommitmentTiers.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListCommitmentTiers.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_defender_for_ai_setting.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_defender_for_ai_setting.py new file mode 100644 index 000000000000..a7bea7f61470 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_defender_for_ai_setting.py @@ -0,0 +1,43 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python list_defender_for_ai_setting.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.defender_for_ai_settings.list( + resource_group_name="resourceGroupName", + account_name="accountName", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListDefenderForAISetting.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_deleted_accounts_by_subscription.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_deleted_accounts_by_subscription.py index 6caab01fd7d6..78a21f185710 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_deleted_accounts_by_subscription.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_deleted_accounts_by_subscription.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -34,6 +35,6 @@ def main(): print(item) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListDeletedAccountsBySubscription.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListDeletedAccountsBySubscription.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_deployment_skus.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_deployment_skus.py new file mode 100644 index 000000000000..00f91265d17c --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_deployment_skus.py @@ -0,0 +1,44 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python list_deployment_skus.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.deployments.list_skus( + resource_group_name="resourceGroupName", + account_name="accountName", + deployment_name="deploymentName", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListDeploymentSkus.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_deployments.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_deployments.py index 117cf35fd6f7..e151c56a572c 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_deployments.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_deployments.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListDeployments.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListDeployments.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_encryption_scopes.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_encryption_scopes.py new file mode 100644 index 000000000000..55765b0380b2 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_encryption_scopes.py @@ -0,0 +1,43 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python list_encryption_scopes.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.encryption_scopes.list( + resource_group_name="resourceGroupName", + account_name="accountName", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListEncryptionScopes.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_keys.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_keys.py index aff624848bfd..26c026caa943 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_keys.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_keys.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListKeys.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListKeys.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_location_based_model_capacities.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_location_based_model_capacities.py new file mode 100644 index 000000000000..1ac614c9d699 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_location_based_model_capacities.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) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python list_location_based_model_capacities.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.location_based_model_capacities.list( + location="WestUS", + model_format="OpenAI", + model_name="ada", + model_version="1", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListLocationBasedModelCapacities.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_models.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_location_models.py similarity index 92% rename from sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_models.py rename to sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_location_models.py index f218282f795c..b584ac9a6ca9 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_models.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_location_models.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -14,7 +15,7 @@ pip install azure-identity pip install azure-mgmt-cognitiveservices # USAGE - python list_models.py + python list_location_models.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListModels.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListLocationModels.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_model_capacities.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_model_capacities.py new file mode 100644 index 000000000000..947290881e47 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_model_capacities.py @@ -0,0 +1,44 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python list_model_capacities.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.model_capacities.list( + model_format="OpenAI", + model_name="ada", + model_version="1", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListModelCapacities.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_network_security_perimeter_configurations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_network_security_perimeter_configurations.py new file mode 100644 index 000000000000..f0c188ba01be --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_network_security_perimeter_configurations.py @@ -0,0 +1,43 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python list_network_security_perimeter_configurations.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.network_security_perimeter_configurations.list( + resource_group_name="resourceGroupName", + account_name="accountName", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListNetworkSecurityPerimeterConfigurations.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_private_endpoint_connections.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_private_endpoint_connections.py index 6ea149ae3515..f4eab22e979f 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_private_endpoint_connections.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_private_endpoint_connections.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListPrivateEndpointConnections.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListPrivateEndpointConnections.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_private_link_resources.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_private_link_resources.py index 58f358763729..f7f386bd2ce6 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_private_link_resources.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_private_link_resources.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListPrivateLinkResources.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListPrivateLinkResources.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_rai_content_filters.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_rai_content_filters.py new file mode 100644 index 000000000000..dee5fd639f8d --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_rai_content_filters.py @@ -0,0 +1,42 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python list_rai_content_filters.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.rai_content_filters.list( + location="WestUS", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListRaiContentFilters.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_rai_policies.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_rai_policies.py new file mode 100644 index 000000000000..86dffa7fb150 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_rai_policies.py @@ -0,0 +1,43 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python list_rai_policies.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.rai_policies.list( + resource_group_name="resourceGroupName", + account_name="accountName", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListRaiPolicies.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_shared_commitment_plan_associations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_shared_commitment_plan_associations.py index affc2e5c25cb..e15d1716d255 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_shared_commitment_plan_associations.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_shared_commitment_plan_associations.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListSharedCommitmentPlanAssociations.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListSharedCommitmentPlanAssociations.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_shared_commitment_plans_by_resource_group.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_shared_commitment_plans_by_resource_group.py index e22a4ca092c1..59c13a21ed0f 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_shared_commitment_plans_by_resource_group.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_shared_commitment_plans_by_resource_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListSharedCommitmentPlansByResourceGroup.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListSharedCommitmentPlansByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_shared_commitment_plans_by_subscription.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_shared_commitment_plans_by_subscription.py index cd3627dd22ec..0e15ba4a3c4f 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_shared_commitment_plans_by_subscription.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_shared_commitment_plans_by_subscription.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -34,6 +35,6 @@ def main(): print(item) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListSharedCommitmentPlansBySubscription.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListSharedCommitmentPlansBySubscription.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_skus.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_skus.py index 9ff283f30044..6cafafb8b3e3 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_skus.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_skus.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListSkus.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListSkus.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_usages.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_usages.py index 21b6ff85551c..3a488eb0a34a 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_usages.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/list_usages.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/ListUsages.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ListUsages.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/purge_deleted_account.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/purge_deleted_account.py index 8367a400dd01..3c4c92848dbd 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/purge_deleted_account.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/purge_deleted_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -36,6 +37,6 @@ def main(): ).result() -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/PurgeDeletedAccount.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/PurgeDeletedAccount.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_commitment_plan.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_commitment_plan.py index eb4aeb36c313..05f98b64c533 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_commitment_plan.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_commitment_plan.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -45,6 +46,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/PutCommitmentPlan.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/PutCommitmentPlan.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_deployment.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_deployment.py index 6e42102775f1..a67329990383 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_deployment.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_deployment.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -41,6 +42,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/PutDeployment.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/PutDeployment.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_encryption_scope.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_encryption_scope.py new file mode 100644 index 000000000000..cc44609256b0 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_encryption_scope.py @@ -0,0 +1,55 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python put_encryption_scope.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.encryption_scopes.create_or_update( + resource_group_name="resourceGroupName", + account_name="accountName", + encryption_scope_name="encryptionScopeName", + encryption_scope={ + "properties": { + "keySource": "Microsoft.KeyVault", + "keyVaultProperties": { + "identityClientId": "00000000-0000-0000-0000-000000000000", + "keyName": "DevKeyWestUS2", + "keyVaultUri": "https://devkvwestus2.vault.azure.net/", + "keyVersion": "9f85549d7bf14ff4bf178c10d3bdca95", + }, + "state": "Enabled", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/PutEncryptionScope.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_private_endpoint_connection.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_private_endpoint_connection.py index d1666e3f3fb5..efb30439e8c9 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_private_endpoint_connection.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_private_endpoint_connection.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -40,6 +41,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/PutPrivateEndpointConnection.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/PutPrivateEndpointConnection.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_rai_blocklist.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_rai_blocklist.py new file mode 100644 index 000000000000..108a5e7d6956 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_rai_blocklist.py @@ -0,0 +1,44 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python put_rai_blocklist.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.rai_blocklists.create_or_update( + resource_group_name="resourceGroupName", + account_name="accountName", + rai_blocklist_name="raiBlocklistName", + rai_blocklist={"properties": {"description": "Basic blocklist description"}}, + ) + print(response) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/PutRaiBlocklist.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_rai_blocklist_item.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_rai_blocklist_item.py new file mode 100644 index 000000000000..f2f5d3fb7139 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_rai_blocklist_item.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) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python put_rai_blocklist_item.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.rai_blocklist_items.create_or_update( + resource_group_name="resourceGroupName", + account_name="accountName", + rai_blocklist_name="raiBlocklistName", + rai_blocklist_item_name="raiBlocklistItemName", + rai_blocklist_item={"properties": {"isRegex": False, "pattern": "Pattern To Block"}}, + ) + print(response) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/PutRaiBlocklistItem.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_rai_policy.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_rai_policy.py new file mode 100644 index 000000000000..683d5e7b1b86 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/put_rai_policy.py @@ -0,0 +1,111 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python put_rai_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.rai_policies.create_or_update( + resource_group_name="resourceGroupName", + account_name="accountName", + rai_policy_name="raiPolicyName", + rai_policy={ + "properties": { + "basePolicyName": "Microsoft.Default", + "contentFilters": [ + { + "blocking": False, + "enabled": False, + "name": "Hate", + "severityThreshold": "High", + "source": "Prompt", + }, + { + "blocking": True, + "enabled": True, + "name": "Hate", + "severityThreshold": "Medium", + "source": "Completion", + }, + { + "blocking": True, + "enabled": True, + "name": "Sexual", + "severityThreshold": "High", + "source": "Prompt", + }, + { + "blocking": True, + "enabled": True, + "name": "Sexual", + "severityThreshold": "Medium", + "source": "Completion", + }, + { + "blocking": True, + "enabled": True, + "name": "Selfharm", + "severityThreshold": "High", + "source": "Prompt", + }, + { + "blocking": True, + "enabled": True, + "name": "Selfharm", + "severityThreshold": "Medium", + "source": "Completion", + }, + { + "blocking": True, + "enabled": True, + "name": "Violence", + "severityThreshold": "Medium", + "source": "Prompt", + }, + { + "blocking": True, + "enabled": True, + "name": "Violence", + "severityThreshold": "Medium", + "source": "Completion", + }, + {"blocking": True, "enabled": True, "name": "Jailbreak", "source": "Prompt"}, + {"blocking": True, "enabled": True, "name": "Protected Material Text", "source": "Completion"}, + {"blocking": True, "enabled": True, "name": "Protected Material Code", "source": "Completion"}, + {"blocking": True, "enabled": True, "name": "Profanity", "source": "Prompt"}, + ], + "mode": "Asynchronous_filter", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/PutRaiPolicy.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/reconcile_network_security_perimeter_configurations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/reconcile_network_security_perimeter_configurations.py new file mode 100644 index 000000000000..67b0298f793e --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/reconcile_network_security_perimeter_configurations.py @@ -0,0 +1,43 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python reconcile_network_security_perimeter_configurations.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.network_security_perimeter_configurations.begin_reconcile( + resource_group_name="resourceGroupName", + account_name="accountName", + nsp_configuration_name="NSPConfigurationName", + ).result() + print(response) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/ReconcileNetworkSecurityPerimeterConfigurations.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/update_account.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/update_account.py index 13c709ef36cb..48dfb3319564 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/update_account.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/update_account.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -37,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/UpdateAccount.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/UpdateAccount.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/update_deployment.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/update_deployment.py new file mode 100644 index 000000000000..2dd9f32d9d19 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/update_deployment.py @@ -0,0 +1,44 @@ +# 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.identity import DefaultAzureCredential + +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-cognitiveservices +# USAGE + python update_deployment.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CognitiveServicesManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.deployments.begin_update( + resource_group_name="resourceGroupName", + account_name="accountName", + deployment_name="deploymentName", + deployment={"sku": {"capacity": 1, "name": "Standard"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/UpdateDeployment.json +if __name__ == "__main__": + main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/update_shared_commitment_plan.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/update_shared_commitment_plan.py index 9942bdba52a5..51b582128e7b 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/update_shared_commitment_plan.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_samples/update_shared_commitment_plan.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient """ @@ -37,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2023-05-01/examples/UpdateSharedCommitmentPlan.json +# x-ms-original-file: specification/cognitiveservices/resource-manager/Microsoft.CognitiveServices/stable/2024-10-01/examples/UpdateSharedCommitmentPlan.json if __name__ == "__main__": main() diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/conftest.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/conftest.py new file mode 100644 index 000000000000..de62be014178 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/conftest.py @@ -0,0 +1,47 @@ +# 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. +# -------------------------------------------------------------------------- +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() + + +# aovid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + cognitiveservicesmanagement_subscription_id = os.environ.get( + "AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + cognitiveservicesmanagement_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + cognitiveservicesmanagement_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + cognitiveservicesmanagement_client_secret = os.environ.get( + "AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer( + regex=cognitiveservicesmanagement_subscription_id, value="00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer( + regex=cognitiveservicesmanagement_tenant_id, value="00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer( + regex=cognitiveservicesmanagement_client_id, value="00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer( + regex=cognitiveservicesmanagement_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/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management.py new file mode 100644 index 000000000000..c22944f9a79a --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management.py @@ -0,0 +1,55 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagement(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_check_sku_availability(self, resource_group): + response = self.client.check_sku_availability( + location="str", + skus=["str"], + kind="str", + type="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_check_domain_availability(self, resource_group): + response = self.client.check_domain_availability( + subdomain_name="str", + type="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_calculate_model_capacity(self, resource_group): + response = self.client.calculate_model_capacity( + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_accounts_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_accounts_operations.py new file mode 100644 index 000000000000..167545e80b77 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_accounts_operations.py @@ -0,0 +1,431 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementAccountsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_create(self, resource_group): + response = self.client.accounts.begin_create( + resource_group_name=resource_group.name, + account_name="str", + account={ + "etag": "str", + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "kind": "str", + "location": "str", + "name": "str", + "properties": { + "abusePenalty": {"action": "str", "expiration": "2020-02-20 00:00:00", "rateLimitPercentage": 0.0}, + "allowedFqdnList": ["str"], + "amlWorkspace": {"identityClientId": "str", "resourceId": "str"}, + "apiProperties": { + "aadClientId": "str", + "aadTenantId": "str", + "eventHubConnectionString": "str", + "qnaAzureSearchEndpointId": "str", + "qnaAzureSearchEndpointKey": "str", + "qnaRuntimeEndpoint": "str", + "statisticsEnabled": bool, + "storageAccountConnectionString": "str", + "superUser": "str", + "websiteName": "str", + }, + "callRateLimit": { + "count": 0.0, + "renewalPeriod": 0.0, + "rules": [ + { + "count": 0.0, + "dynamicThrottlingEnabled": bool, + "key": "str", + "matchPatterns": [{"method": "str", "path": "str"}], + "minCount": 0.0, + "renewalPeriod": 0.0, + } + ], + }, + "capabilities": [{"name": "str", "value": "str"}], + "commitmentPlanAssociations": [{"commitmentPlanId": "str", "commitmentPlanLocation": "str"}], + "customSubDomainName": "str", + "dateCreated": "str", + "deletionDate": "str", + "disableLocalAuth": bool, + "dynamicThrottlingEnabled": bool, + "encryption": { + "keySource": "Microsoft.KeyVault", + "keyVaultProperties": { + "identityClientId": "str", + "keyName": "str", + "keyVaultUri": "str", + "keyVersion": "str", + }, + }, + "endpoint": "str", + "endpoints": {"str": "str"}, + "internalId": "str", + "isMigrated": bool, + "locations": { + "regions": [{"customsubdomain": "str", "name": "str", "value": 0.0}], + "routingMethod": "str", + }, + "migrationToken": "str", + "networkAcls": { + "bypass": "str", + "defaultAction": "str", + "ipRules": [{"value": "str"}], + "virtualNetworkRules": [ + {"id": "str", "ignoreMissingVnetServiceEndpoint": bool, "state": "str"} + ], + }, + "privateEndpointConnections": [ + { + "etag": "str", + "id": "str", + "location": "str", + "name": "str", + "properties": { + "privateLinkServiceConnectionState": { + "actionsRequired": "str", + "description": "str", + "status": "str", + }, + "groupIds": ["str"], + "privateEndpoint": {"id": "str"}, + "provisioningState": "str", + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + } + ], + "provisioningState": "str", + "publicNetworkAccess": "str", + "quotaLimit": { + "count": 0.0, + "renewalPeriod": 0.0, + "rules": [ + { + "count": 0.0, + "dynamicThrottlingEnabled": bool, + "key": "str", + "matchPatterns": [{"method": "str", "path": "str"}], + "minCount": 0.0, + "renewalPeriod": 0.0, + } + ], + }, + "raiMonitorConfig": {"adxStorageResourceId": "str", "identityClientId": "str"}, + "restore": bool, + "restrictOutboundNetworkAccess": bool, + "scheduledPurgeDate": "str", + "skuChangeInfo": { + "countOfDowngrades": 0.0, + "countOfUpgradesAfterDowngrades": 0.0, + "lastChangeDate": "str", + }, + "userOwnedStorage": [{"identityClientId": "str", "resourceId": "str"}], + }, + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_update(self, resource_group): + response = self.client.accounts.begin_update( + resource_group_name=resource_group.name, + account_name="str", + account={ + "etag": "str", + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "kind": "str", + "location": "str", + "name": "str", + "properties": { + "abusePenalty": {"action": "str", "expiration": "2020-02-20 00:00:00", "rateLimitPercentage": 0.0}, + "allowedFqdnList": ["str"], + "amlWorkspace": {"identityClientId": "str", "resourceId": "str"}, + "apiProperties": { + "aadClientId": "str", + "aadTenantId": "str", + "eventHubConnectionString": "str", + "qnaAzureSearchEndpointId": "str", + "qnaAzureSearchEndpointKey": "str", + "qnaRuntimeEndpoint": "str", + "statisticsEnabled": bool, + "storageAccountConnectionString": "str", + "superUser": "str", + "websiteName": "str", + }, + "callRateLimit": { + "count": 0.0, + "renewalPeriod": 0.0, + "rules": [ + { + "count": 0.0, + "dynamicThrottlingEnabled": bool, + "key": "str", + "matchPatterns": [{"method": "str", "path": "str"}], + "minCount": 0.0, + "renewalPeriod": 0.0, + } + ], + }, + "capabilities": [{"name": "str", "value": "str"}], + "commitmentPlanAssociations": [{"commitmentPlanId": "str", "commitmentPlanLocation": "str"}], + "customSubDomainName": "str", + "dateCreated": "str", + "deletionDate": "str", + "disableLocalAuth": bool, + "dynamicThrottlingEnabled": bool, + "encryption": { + "keySource": "Microsoft.KeyVault", + "keyVaultProperties": { + "identityClientId": "str", + "keyName": "str", + "keyVaultUri": "str", + "keyVersion": "str", + }, + }, + "endpoint": "str", + "endpoints": {"str": "str"}, + "internalId": "str", + "isMigrated": bool, + "locations": { + "regions": [{"customsubdomain": "str", "name": "str", "value": 0.0}], + "routingMethod": "str", + }, + "migrationToken": "str", + "networkAcls": { + "bypass": "str", + "defaultAction": "str", + "ipRules": [{"value": "str"}], + "virtualNetworkRules": [ + {"id": "str", "ignoreMissingVnetServiceEndpoint": bool, "state": "str"} + ], + }, + "privateEndpointConnections": [ + { + "etag": "str", + "id": "str", + "location": "str", + "name": "str", + "properties": { + "privateLinkServiceConnectionState": { + "actionsRequired": "str", + "description": "str", + "status": "str", + }, + "groupIds": ["str"], + "privateEndpoint": {"id": "str"}, + "provisioningState": "str", + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + } + ], + "provisioningState": "str", + "publicNetworkAccess": "str", + "quotaLimit": { + "count": 0.0, + "renewalPeriod": 0.0, + "rules": [ + { + "count": 0.0, + "dynamicThrottlingEnabled": bool, + "key": "str", + "matchPatterns": [{"method": "str", "path": "str"}], + "minCount": 0.0, + "renewalPeriod": 0.0, + } + ], + }, + "raiMonitorConfig": {"adxStorageResourceId": "str", "identityClientId": "str"}, + "restore": bool, + "restrictOutboundNetworkAccess": bool, + "scheduledPurgeDate": "str", + "skuChangeInfo": { + "countOfDowngrades": 0.0, + "countOfUpgradesAfterDowngrades": 0.0, + "lastChangeDate": "str", + }, + "userOwnedStorage": [{"identityClientId": "str", "resourceId": "str"}], + }, + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_delete(self, resource_group): + response = self.client.accounts.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get(self, resource_group): + response = self.client.accounts.get( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list_by_resource_group(self, resource_group): + response = self.client.accounts.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.accounts.list( + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list_keys(self, resource_group): + response = self.client.accounts.list_keys( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_regenerate_key(self, resource_group): + response = self.client.accounts.regenerate_key( + resource_group_name=resource_group.name, + account_name="str", + key_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list_skus(self, resource_group): + response = self.client.accounts.list_skus( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list_usages(self, resource_group): + response = self.client.accounts.list_usages( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list_models(self, resource_group): + response = self.client.accounts.list_models( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_accounts_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_accounts_operations_async.py new file mode 100644 index 000000000000..48231dfd55a2 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_accounts_operations_async.py @@ -0,0 +1,446 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementAccountsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_create(self, resource_group): + response = await ( + await self.client.accounts.begin_create( + resource_group_name=resource_group.name, + account_name="str", + account={ + "etag": "str", + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "kind": "str", + "location": "str", + "name": "str", + "properties": { + "abusePenalty": { + "action": "str", + "expiration": "2020-02-20 00:00:00", + "rateLimitPercentage": 0.0, + }, + "allowedFqdnList": ["str"], + "amlWorkspace": {"identityClientId": "str", "resourceId": "str"}, + "apiProperties": { + "aadClientId": "str", + "aadTenantId": "str", + "eventHubConnectionString": "str", + "qnaAzureSearchEndpointId": "str", + "qnaAzureSearchEndpointKey": "str", + "qnaRuntimeEndpoint": "str", + "statisticsEnabled": bool, + "storageAccountConnectionString": "str", + "superUser": "str", + "websiteName": "str", + }, + "callRateLimit": { + "count": 0.0, + "renewalPeriod": 0.0, + "rules": [ + { + "count": 0.0, + "dynamicThrottlingEnabled": bool, + "key": "str", + "matchPatterns": [{"method": "str", "path": "str"}], + "minCount": 0.0, + "renewalPeriod": 0.0, + } + ], + }, + "capabilities": [{"name": "str", "value": "str"}], + "commitmentPlanAssociations": [{"commitmentPlanId": "str", "commitmentPlanLocation": "str"}], + "customSubDomainName": "str", + "dateCreated": "str", + "deletionDate": "str", + "disableLocalAuth": bool, + "dynamicThrottlingEnabled": bool, + "encryption": { + "keySource": "Microsoft.KeyVault", + "keyVaultProperties": { + "identityClientId": "str", + "keyName": "str", + "keyVaultUri": "str", + "keyVersion": "str", + }, + }, + "endpoint": "str", + "endpoints": {"str": "str"}, + "internalId": "str", + "isMigrated": bool, + "locations": { + "regions": [{"customsubdomain": "str", "name": "str", "value": 0.0}], + "routingMethod": "str", + }, + "migrationToken": "str", + "networkAcls": { + "bypass": "str", + "defaultAction": "str", + "ipRules": [{"value": "str"}], + "virtualNetworkRules": [ + {"id": "str", "ignoreMissingVnetServiceEndpoint": bool, "state": "str"} + ], + }, + "privateEndpointConnections": [ + { + "etag": "str", + "id": "str", + "location": "str", + "name": "str", + "properties": { + "privateLinkServiceConnectionState": { + "actionsRequired": "str", + "description": "str", + "status": "str", + }, + "groupIds": ["str"], + "privateEndpoint": {"id": "str"}, + "provisioningState": "str", + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + } + ], + "provisioningState": "str", + "publicNetworkAccess": "str", + "quotaLimit": { + "count": 0.0, + "renewalPeriod": 0.0, + "rules": [ + { + "count": 0.0, + "dynamicThrottlingEnabled": bool, + "key": "str", + "matchPatterns": [{"method": "str", "path": "str"}], + "minCount": 0.0, + "renewalPeriod": 0.0, + } + ], + }, + "raiMonitorConfig": {"adxStorageResourceId": "str", "identityClientId": "str"}, + "restore": bool, + "restrictOutboundNetworkAccess": bool, + "scheduledPurgeDate": "str", + "skuChangeInfo": { + "countOfDowngrades": 0.0, + "countOfUpgradesAfterDowngrades": 0.0, + "lastChangeDate": "str", + }, + "userOwnedStorage": [{"identityClientId": "str", "resourceId": "str"}], + }, + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_update(self, resource_group): + response = await ( + await self.client.accounts.begin_update( + resource_group_name=resource_group.name, + account_name="str", + account={ + "etag": "str", + "id": "str", + "identity": { + "principalId": "str", + "tenantId": "str", + "type": "str", + "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, + }, + "kind": "str", + "location": "str", + "name": "str", + "properties": { + "abusePenalty": { + "action": "str", + "expiration": "2020-02-20 00:00:00", + "rateLimitPercentage": 0.0, + }, + "allowedFqdnList": ["str"], + "amlWorkspace": {"identityClientId": "str", "resourceId": "str"}, + "apiProperties": { + "aadClientId": "str", + "aadTenantId": "str", + "eventHubConnectionString": "str", + "qnaAzureSearchEndpointId": "str", + "qnaAzureSearchEndpointKey": "str", + "qnaRuntimeEndpoint": "str", + "statisticsEnabled": bool, + "storageAccountConnectionString": "str", + "superUser": "str", + "websiteName": "str", + }, + "callRateLimit": { + "count": 0.0, + "renewalPeriod": 0.0, + "rules": [ + { + "count": 0.0, + "dynamicThrottlingEnabled": bool, + "key": "str", + "matchPatterns": [{"method": "str", "path": "str"}], + "minCount": 0.0, + "renewalPeriod": 0.0, + } + ], + }, + "capabilities": [{"name": "str", "value": "str"}], + "commitmentPlanAssociations": [{"commitmentPlanId": "str", "commitmentPlanLocation": "str"}], + "customSubDomainName": "str", + "dateCreated": "str", + "deletionDate": "str", + "disableLocalAuth": bool, + "dynamicThrottlingEnabled": bool, + "encryption": { + "keySource": "Microsoft.KeyVault", + "keyVaultProperties": { + "identityClientId": "str", + "keyName": "str", + "keyVaultUri": "str", + "keyVersion": "str", + }, + }, + "endpoint": "str", + "endpoints": {"str": "str"}, + "internalId": "str", + "isMigrated": bool, + "locations": { + "regions": [{"customsubdomain": "str", "name": "str", "value": 0.0}], + "routingMethod": "str", + }, + "migrationToken": "str", + "networkAcls": { + "bypass": "str", + "defaultAction": "str", + "ipRules": [{"value": "str"}], + "virtualNetworkRules": [ + {"id": "str", "ignoreMissingVnetServiceEndpoint": bool, "state": "str"} + ], + }, + "privateEndpointConnections": [ + { + "etag": "str", + "id": "str", + "location": "str", + "name": "str", + "properties": { + "privateLinkServiceConnectionState": { + "actionsRequired": "str", + "description": "str", + "status": "str", + }, + "groupIds": ["str"], + "privateEndpoint": {"id": "str"}, + "provisioningState": "str", + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + } + ], + "provisioningState": "str", + "publicNetworkAccess": "str", + "quotaLimit": { + "count": 0.0, + "renewalPeriod": 0.0, + "rules": [ + { + "count": 0.0, + "dynamicThrottlingEnabled": bool, + "key": "str", + "matchPatterns": [{"method": "str", "path": "str"}], + "minCount": 0.0, + "renewalPeriod": 0.0, + } + ], + }, + "raiMonitorConfig": {"adxStorageResourceId": "str", "identityClientId": "str"}, + "restore": bool, + "restrictOutboundNetworkAccess": bool, + "scheduledPurgeDate": "str", + "skuChangeInfo": { + "countOfDowngrades": 0.0, + "countOfUpgradesAfterDowngrades": 0.0, + "lastChangeDate": "str", + }, + "userOwnedStorage": [{"identityClientId": "str", "resourceId": "str"}], + }, + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_delete(self, resource_group): + response = await ( + await self.client.accounts.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get(self, resource_group): + response = await self.client.accounts.get( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list_by_resource_group(self, resource_group): + response = self.client.accounts.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.accounts.list( + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list_keys(self, resource_group): + response = await self.client.accounts.list_keys( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_regenerate_key(self, resource_group): + response = await self.client.accounts.regenerate_key( + resource_group_name=resource_group.name, + account_name="str", + key_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list_skus(self, resource_group): + response = await self.client.accounts.list_skus( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list_usages(self, resource_group): + response = await self.client.accounts.list_usages( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list_models(self, resource_group): + response = self.client.accounts.list_models( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_async.py new file mode 100644 index 000000000000..b1a297fc3938 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_async.py @@ -0,0 +1,56 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_check_sku_availability(self, resource_group): + response = await self.client.check_sku_availability( + location="str", + skus=["str"], + kind="str", + type="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_check_domain_availability(self, resource_group): + response = await self.client.check_domain_availability( + subdomain_name="str", + type="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_calculate_model_capacity(self, resource_group): + response = await self.client.calculate_model_capacity( + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_commitment_plans_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_commitment_plans_operations.py new file mode 100644 index 000000000000..3ea44faf297b --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_commitment_plans_operations.py @@ -0,0 +1,304 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementCommitmentPlansOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.commitment_plans.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get(self, resource_group): + response = self.client.commitment_plans.get( + resource_group_name=resource_group.name, + account_name="str", + commitment_plan_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_create_or_update(self, resource_group): + response = self.client.commitment_plans.create_or_update( + resource_group_name=resource_group.name, + account_name="str", + commitment_plan_name="str", + commitment_plan={ + "etag": "str", + "id": "str", + "kind": "str", + "location": "str", + "name": "str", + "properties": { + "autoRenew": bool, + "commitmentPlanGuid": "str", + "current": { + "count": 0, + "endDate": "str", + "quota": {"quantity": 0, "unit": "str"}, + "startDate": "str", + "tier": "str", + }, + "hostingModel": "str", + "last": { + "count": 0, + "endDate": "str", + "quota": {"quantity": 0, "unit": "str"}, + "startDate": "str", + "tier": "str", + }, + "next": { + "count": 0, + "endDate": "str", + "quota": {"quantity": 0, "unit": "str"}, + "startDate": "str", + "tier": "str", + }, + "planType": "str", + "provisioningIssues": ["str"], + "provisioningState": "str", + }, + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_delete(self, resource_group): + response = self.client.commitment_plans.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + commitment_plan_name="str", + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_create_or_update_plan(self, resource_group): + response = self.client.commitment_plans.begin_create_or_update_plan( + resource_group_name=resource_group.name, + commitment_plan_name="str", + commitment_plan={ + "etag": "str", + "id": "str", + "kind": "str", + "location": "str", + "name": "str", + "properties": { + "autoRenew": bool, + "commitmentPlanGuid": "str", + "current": { + "count": 0, + "endDate": "str", + "quota": {"quantity": 0, "unit": "str"}, + "startDate": "str", + "tier": "str", + }, + "hostingModel": "str", + "last": { + "count": 0, + "endDate": "str", + "quota": {"quantity": 0, "unit": "str"}, + "startDate": "str", + "tier": "str", + }, + "next": { + "count": 0, + "endDate": "str", + "quota": {"quantity": 0, "unit": "str"}, + "startDate": "str", + "tier": "str", + }, + "planType": "str", + "provisioningIssues": ["str"], + "provisioningState": "str", + }, + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_update_plan(self, resource_group): + response = self.client.commitment_plans.begin_update_plan( + resource_group_name=resource_group.name, + commitment_plan_name="str", + commitment_plan={ + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "tags": {"str": "str"}, + }, + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_delete_plan(self, resource_group): + response = self.client.commitment_plans.begin_delete_plan( + resource_group_name=resource_group.name, + commitment_plan_name="str", + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get_plan(self, resource_group): + response = self.client.commitment_plans.get_plan( + resource_group_name=resource_group.name, + commitment_plan_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list_plans_by_resource_group(self, resource_group): + response = self.client.commitment_plans.list_plans_by_resource_group( + resource_group_name=resource_group.name, + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list_plans_by_subscription(self, resource_group): + response = self.client.commitment_plans.list_plans_by_subscription( + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list_associations(self, resource_group): + response = self.client.commitment_plans.list_associations( + resource_group_name=resource_group.name, + commitment_plan_name="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get_association(self, resource_group): + response = self.client.commitment_plans.get_association( + resource_group_name=resource_group.name, + commitment_plan_name="str", + commitment_plan_association_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_create_or_update_association(self, resource_group): + response = self.client.commitment_plans.begin_create_or_update_association( + resource_group_name=resource_group.name, + commitment_plan_name="str", + commitment_plan_association_name="str", + association={ + "accountId": "str", + "etag": "str", + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_delete_association(self, resource_group): + response = self.client.commitment_plans.begin_delete_association( + resource_group_name=resource_group.name, + commitment_plan_name="str", + commitment_plan_association_name="str", + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_commitment_plans_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_commitment_plans_operations_async.py new file mode 100644 index 000000000000..64b0e522673a --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_commitment_plans_operations_async.py @@ -0,0 +1,317 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementCommitmentPlansOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.commitment_plans.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get(self, resource_group): + response = await self.client.commitment_plans.get( + resource_group_name=resource_group.name, + account_name="str", + commitment_plan_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_create_or_update(self, resource_group): + response = await self.client.commitment_plans.create_or_update( + resource_group_name=resource_group.name, + account_name="str", + commitment_plan_name="str", + commitment_plan={ + "etag": "str", + "id": "str", + "kind": "str", + "location": "str", + "name": "str", + "properties": { + "autoRenew": bool, + "commitmentPlanGuid": "str", + "current": { + "count": 0, + "endDate": "str", + "quota": {"quantity": 0, "unit": "str"}, + "startDate": "str", + "tier": "str", + }, + "hostingModel": "str", + "last": { + "count": 0, + "endDate": "str", + "quota": {"quantity": 0, "unit": "str"}, + "startDate": "str", + "tier": "str", + }, + "next": { + "count": 0, + "endDate": "str", + "quota": {"quantity": 0, "unit": "str"}, + "startDate": "str", + "tier": "str", + }, + "planType": "str", + "provisioningIssues": ["str"], + "provisioningState": "str", + }, + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_delete(self, resource_group): + response = await ( + await self.client.commitment_plans.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + commitment_plan_name="str", + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_create_or_update_plan(self, resource_group): + response = await ( + await self.client.commitment_plans.begin_create_or_update_plan( + resource_group_name=resource_group.name, + commitment_plan_name="str", + commitment_plan={ + "etag": "str", + "id": "str", + "kind": "str", + "location": "str", + "name": "str", + "properties": { + "autoRenew": bool, + "commitmentPlanGuid": "str", + "current": { + "count": 0, + "endDate": "str", + "quota": {"quantity": 0, "unit": "str"}, + "startDate": "str", + "tier": "str", + }, + "hostingModel": "str", + "last": { + "count": 0, + "endDate": "str", + "quota": {"quantity": 0, "unit": "str"}, + "startDate": "str", + "tier": "str", + }, + "next": { + "count": 0, + "endDate": "str", + "quota": {"quantity": 0, "unit": "str"}, + "startDate": "str", + "tier": "str", + }, + "planType": "str", + "provisioningIssues": ["str"], + "provisioningState": "str", + }, + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_update_plan(self, resource_group): + response = await ( + await self.client.commitment_plans.begin_update_plan( + resource_group_name=resource_group.name, + commitment_plan_name="str", + commitment_plan={ + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "tags": {"str": "str"}, + }, + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_delete_plan(self, resource_group): + response = await ( + await self.client.commitment_plans.begin_delete_plan( + resource_group_name=resource_group.name, + commitment_plan_name="str", + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get_plan(self, resource_group): + response = await self.client.commitment_plans.get_plan( + resource_group_name=resource_group.name, + commitment_plan_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list_plans_by_resource_group(self, resource_group): + response = self.client.commitment_plans.list_plans_by_resource_group( + resource_group_name=resource_group.name, + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list_plans_by_subscription(self, resource_group): + response = self.client.commitment_plans.list_plans_by_subscription( + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list_associations(self, resource_group): + response = self.client.commitment_plans.list_associations( + resource_group_name=resource_group.name, + commitment_plan_name="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get_association(self, resource_group): + response = await self.client.commitment_plans.get_association( + resource_group_name=resource_group.name, + commitment_plan_name="str", + commitment_plan_association_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_create_or_update_association(self, resource_group): + response = await ( + await self.client.commitment_plans.begin_create_or_update_association( + resource_group_name=resource_group.name, + commitment_plan_name="str", + commitment_plan_association_name="str", + association={ + "accountId": "str", + "etag": "str", + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_delete_association(self, resource_group): + response = await ( + await self.client.commitment_plans.begin_delete_association( + resource_group_name=resource_group.name, + commitment_plan_name="str", + commitment_plan_association_name="str", + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_commitment_tiers_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_commitment_tiers_operations.py new file mode 100644 index 000000000000..98c9d9791e30 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_commitment_tiers_operations.py @@ -0,0 +1,30 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementCommitmentTiersOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.commitment_tiers.list( + location="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_commitment_tiers_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_commitment_tiers_operations_async.py new file mode 100644 index 000000000000..70dca8f7cc01 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_commitment_tiers_operations_async.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) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementCommitmentTiersOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.commitment_tiers.list( + location="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_defender_for_ai_settings_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_defender_for_ai_settings_operations.py new file mode 100644 index 000000000000..f25c9d9b8460 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_defender_for_ai_settings_operations.py @@ -0,0 +1,102 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementDefenderForAISettingsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.defender_for_ai_settings.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get(self, resource_group): + response = self.client.defender_for_ai_settings.get( + resource_group_name=resource_group.name, + account_name="str", + defender_for_ai_setting_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_create_or_update(self, resource_group): + response = self.client.defender_for_ai_settings.create_or_update( + resource_group_name=resource_group.name, + account_name="str", + defender_for_ai_setting_name="str", + defender_for_ai_settings={ + "etag": "str", + "id": "str", + "name": "str", + "state": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_update(self, resource_group): + response = self.client.defender_for_ai_settings.update( + resource_group_name=resource_group.name, + account_name="str", + defender_for_ai_setting_name="str", + defender_for_ai_settings={ + "etag": "str", + "id": "str", + "name": "str", + "state": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_defender_for_ai_settings_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_defender_for_ai_settings_operations_async.py new file mode 100644 index 000000000000..68f2b58ee6cd --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_defender_for_ai_settings_operations_async.py @@ -0,0 +1,103 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementDefenderForAISettingsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.defender_for_ai_settings.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get(self, resource_group): + response = await self.client.defender_for_ai_settings.get( + resource_group_name=resource_group.name, + account_name="str", + defender_for_ai_setting_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_create_or_update(self, resource_group): + response = await self.client.defender_for_ai_settings.create_or_update( + resource_group_name=resource_group.name, + account_name="str", + defender_for_ai_setting_name="str", + defender_for_ai_settings={ + "etag": "str", + "id": "str", + "name": "str", + "state": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_update(self, resource_group): + response = await self.client.defender_for_ai_settings.update( + resource_group_name=resource_group.name, + account_name="str", + defender_for_ai_setting_name="str", + defender_for_ai_settings={ + "etag": "str", + "id": "str", + "name": "str", + "state": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_deleted_accounts_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_deleted_accounts_operations.py new file mode 100644 index 000000000000..a74476dc88d1 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_deleted_accounts_operations.py @@ -0,0 +1,55 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementDeletedAccountsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get(self, resource_group): + response = self.client.deleted_accounts.get( + location="str", + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_purge(self, resource_group): + response = self.client.deleted_accounts.begin_purge( + location="str", + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.deleted_accounts.list( + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_deleted_accounts_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_deleted_accounts_operations_async.py new file mode 100644 index 000000000000..a1d8b2241e32 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_deleted_accounts_operations_async.py @@ -0,0 +1,58 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementDeletedAccountsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get(self, resource_group): + response = await self.client.deleted_accounts.get( + location="str", + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_purge(self, resource_group): + response = await ( + await self.client.deleted_accounts.begin_purge( + location="str", + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.deleted_accounts.list( + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_deployments_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_deployments_operations.py new file mode 100644 index 000000000000..15e401263208 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_deployments_operations.py @@ -0,0 +1,173 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementDeploymentsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.deployments.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get(self, resource_group): + response = self.client.deployments.get( + resource_group_name=resource_group.name, + account_name="str", + deployment_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_create_or_update(self, resource_group): + response = self.client.deployments.begin_create_or_update( + resource_group_name=resource_group.name, + account_name="str", + deployment_name="str", + deployment={ + "etag": "str", + "id": "str", + "name": "str", + "properties": { + "callRateLimit": { + "count": 0.0, + "renewalPeriod": 0.0, + "rules": [ + { + "count": 0.0, + "dynamicThrottlingEnabled": bool, + "key": "str", + "matchPatterns": [{"method": "str", "path": "str"}], + "minCount": 0.0, + "renewalPeriod": 0.0, + } + ], + }, + "capabilities": {"str": "str"}, + "capacitySettings": {"designatedCapacity": 0, "priority": 0}, + "currentCapacity": 0, + "dynamicThrottlingEnabled": bool, + "model": { + "callRateLimit": { + "count": 0.0, + "renewalPeriod": 0.0, + "rules": [ + { + "count": 0.0, + "dynamicThrottlingEnabled": bool, + "key": "str", + "matchPatterns": [{"method": "str", "path": "str"}], + "minCount": 0.0, + "renewalPeriod": 0.0, + } + ], + }, + "format": "str", + "name": "str", + "publisher": "str", + "source": "str", + "sourceAccount": "str", + "version": "str", + }, + "parentDeploymentName": "str", + "provisioningState": "str", + "raiPolicyName": "str", + "rateLimits": [ + { + "count": 0.0, + "dynamicThrottlingEnabled": bool, + "key": "str", + "matchPatterns": [{"method": "str", "path": "str"}], + "minCount": 0.0, + "renewalPeriod": 0.0, + } + ], + "scaleSettings": {"activeCapacity": 0, "capacity": 0, "scaleType": "str"}, + "versionUpgradeOption": "str", + }, + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_update(self, resource_group): + response = self.client.deployments.begin_update( + resource_group_name=resource_group.name, + account_name="str", + deployment_name="str", + deployment={ + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "tags": {"str": "str"}, + }, + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_delete(self, resource_group): + response = self.client.deployments.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + deployment_name="str", + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list_skus(self, resource_group): + response = self.client.deployments.list_skus( + resource_group_name=resource_group.name, + account_name="str", + deployment_name="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_deployments_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_deployments_operations_async.py new file mode 100644 index 000000000000..cacdffc9fe81 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_deployments_operations_async.py @@ -0,0 +1,180 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementDeploymentsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.deployments.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get(self, resource_group): + response = await self.client.deployments.get( + resource_group_name=resource_group.name, + account_name="str", + deployment_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_create_or_update(self, resource_group): + response = await ( + await self.client.deployments.begin_create_or_update( + resource_group_name=resource_group.name, + account_name="str", + deployment_name="str", + deployment={ + "etag": "str", + "id": "str", + "name": "str", + "properties": { + "callRateLimit": { + "count": 0.0, + "renewalPeriod": 0.0, + "rules": [ + { + "count": 0.0, + "dynamicThrottlingEnabled": bool, + "key": "str", + "matchPatterns": [{"method": "str", "path": "str"}], + "minCount": 0.0, + "renewalPeriod": 0.0, + } + ], + }, + "capabilities": {"str": "str"}, + "capacitySettings": {"designatedCapacity": 0, "priority": 0}, + "currentCapacity": 0, + "dynamicThrottlingEnabled": bool, + "model": { + "callRateLimit": { + "count": 0.0, + "renewalPeriod": 0.0, + "rules": [ + { + "count": 0.0, + "dynamicThrottlingEnabled": bool, + "key": "str", + "matchPatterns": [{"method": "str", "path": "str"}], + "minCount": 0.0, + "renewalPeriod": 0.0, + } + ], + }, + "format": "str", + "name": "str", + "publisher": "str", + "source": "str", + "sourceAccount": "str", + "version": "str", + }, + "parentDeploymentName": "str", + "provisioningState": "str", + "raiPolicyName": "str", + "rateLimits": [ + { + "count": 0.0, + "dynamicThrottlingEnabled": bool, + "key": "str", + "matchPatterns": [{"method": "str", "path": "str"}], + "minCount": 0.0, + "renewalPeriod": 0.0, + } + ], + "scaleSettings": {"activeCapacity": 0, "capacity": 0, "scaleType": "str"}, + "versionUpgradeOption": "str", + }, + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_update(self, resource_group): + response = await ( + await self.client.deployments.begin_update( + resource_group_name=resource_group.name, + account_name="str", + deployment_name="str", + deployment={ + "sku": {"name": "str", "capacity": 0, "family": "str", "size": "str", "tier": "str"}, + "tags": {"str": "str"}, + }, + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_delete(self, resource_group): + response = await ( + await self.client.deployments.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + deployment_name="str", + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list_skus(self, resource_group): + response = self.client.deployments.list_skus( + resource_group_name=resource_group.name, + account_name="str", + deployment_name="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_encryption_scopes_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_encryption_scopes_operations.py new file mode 100644 index 000000000000..d967c0ff45c4 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_encryption_scopes_operations.py @@ -0,0 +1,96 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementEncryptionScopesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.encryption_scopes.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get(self, resource_group): + response = self.client.encryption_scopes.get( + resource_group_name=resource_group.name, + account_name="str", + encryption_scope_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_create_or_update(self, resource_group): + response = self.client.encryption_scopes.create_or_update( + resource_group_name=resource_group.name, + account_name="str", + encryption_scope_name="str", + encryption_scope={ + "etag": "str", + "id": "str", + "name": "str", + "properties": { + "keySource": "Microsoft.KeyVault", + "keyVaultProperties": { + "identityClientId": "str", + "keyName": "str", + "keyVaultUri": "str", + "keyVersion": "str", + }, + "provisioningState": "str", + "state": "str", + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_delete(self, resource_group): + response = self.client.encryption_scopes.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + encryption_scope_name="str", + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_encryption_scopes_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_encryption_scopes_operations_async.py new file mode 100644 index 000000000000..850573c72894 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_encryption_scopes_operations_async.py @@ -0,0 +1,99 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementEncryptionScopesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.encryption_scopes.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get(self, resource_group): + response = await self.client.encryption_scopes.get( + resource_group_name=resource_group.name, + account_name="str", + encryption_scope_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_create_or_update(self, resource_group): + response = await self.client.encryption_scopes.create_or_update( + resource_group_name=resource_group.name, + account_name="str", + encryption_scope_name="str", + encryption_scope={ + "etag": "str", + "id": "str", + "name": "str", + "properties": { + "keySource": "Microsoft.KeyVault", + "keyVaultProperties": { + "identityClientId": "str", + "keyName": "str", + "keyVaultUri": "str", + "keyVersion": "str", + }, + "provisioningState": "str", + "state": "str", + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_delete(self, resource_group): + response = await ( + await self.client.encryption_scopes.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + encryption_scope_name="str", + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_location_based_model_capacities_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_location_based_model_capacities_operations.py new file mode 100644 index 000000000000..4d0a27d8ec07 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_location_based_model_capacities_operations.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) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementLocationBasedModelCapacitiesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.location_based_model_capacities.list( + location="str", + model_format="str", + model_name="str", + model_version="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_location_based_model_capacities_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_location_based_model_capacities_operations_async.py new file mode 100644 index 000000000000..c6cacad33717 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_location_based_model_capacities_operations_async.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) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementLocationBasedModelCapacitiesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.location_based_model_capacities.list( + location="str", + model_format="str", + model_name="str", + model_version="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_model_capacities_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_model_capacities_operations.py new file mode 100644 index 000000000000..c156fa2436d6 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_model_capacities_operations.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) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementModelCapacitiesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.model_capacities.list( + model_format="str", + model_name="str", + model_version="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_model_capacities_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_model_capacities_operations_async.py new file mode 100644 index 000000000000..e95828958954 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_model_capacities_operations_async.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) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementModelCapacitiesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.model_capacities.list( + model_format="str", + model_name="str", + model_version="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_models_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_models_operations.py new file mode 100644 index 000000000000..faea0ec9f7f8 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_models_operations.py @@ -0,0 +1,30 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementModelsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.models.list( + location="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_models_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_models_operations_async.py new file mode 100644 index 000000000000..ad64b9c72310 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_models_operations_async.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) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementModelsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.models.list( + location="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_network_security_perimeter_configurations_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_network_security_perimeter_configurations_operations.py new file mode 100644 index 000000000000..7f07dcf36d59 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_network_security_perimeter_configurations_operations.py @@ -0,0 +1,57 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementNetworkSecurityPerimeterConfigurationsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.network_security_perimeter_configurations.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get(self, resource_group): + response = self.client.network_security_perimeter_configurations.get( + resource_group_name=resource_group.name, + account_name="str", + nsp_configuration_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_reconcile(self, resource_group): + response = self.client.network_security_perimeter_configurations.begin_reconcile( + resource_group_name=resource_group.name, + account_name="str", + nsp_configuration_name="str", + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_network_security_perimeter_configurations_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_network_security_perimeter_configurations_operations_async.py new file mode 100644 index 000000000000..828da45f5710 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_network_security_perimeter_configurations_operations_async.py @@ -0,0 +1,60 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementNetworkSecurityPerimeterConfigurationsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.network_security_perimeter_configurations.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get(self, resource_group): + response = await self.client.network_security_perimeter_configurations.get( + resource_group_name=resource_group.name, + account_name="str", + nsp_configuration_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_reconcile(self, resource_group): + response = await ( + await self.client.network_security_perimeter_configurations.begin_reconcile( + resource_group_name=resource_group.name, + account_name="str", + nsp_configuration_name="str", + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_operations.py new file mode 100644 index 000000000000..c66de343c10a --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_operations.py @@ -0,0 +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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.operations.list( + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_operations_async.py new file mode 100644 index 000000000000..48ba34c38069 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_operations_async.py @@ -0,0 +1,30 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.operations.list( + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_private_endpoint_connections_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_private_endpoint_connections_operations.py new file mode 100644 index 000000000000..efd140ede911 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_private_endpoint_connections_operations.py @@ -0,0 +1,95 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementPrivateEndpointConnectionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.private_endpoint_connections.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get(self, resource_group): + response = self.client.private_endpoint_connections.get( + resource_group_name=resource_group.name, + account_name="str", + private_endpoint_connection_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_create_or_update(self, resource_group): + response = self.client.private_endpoint_connections.begin_create_or_update( + resource_group_name=resource_group.name, + account_name="str", + private_endpoint_connection_name="str", + properties={ + "etag": "str", + "id": "str", + "location": "str", + "name": "str", + "properties": { + "privateLinkServiceConnectionState": { + "actionsRequired": "str", + "description": "str", + "status": "str", + }, + "groupIds": ["str"], + "privateEndpoint": {"id": "str"}, + "provisioningState": "str", + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_delete(self, resource_group): + response = self.client.private_endpoint_connections.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + private_endpoint_connection_name="str", + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_private_endpoint_connections_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_private_endpoint_connections_operations_async.py new file mode 100644 index 000000000000..d4c54f0c819d --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_private_endpoint_connections_operations_async.py @@ -0,0 +1,100 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementPrivateEndpointConnectionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = await self.client.private_endpoint_connections.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get(self, resource_group): + response = await self.client.private_endpoint_connections.get( + resource_group_name=resource_group.name, + account_name="str", + private_endpoint_connection_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_create_or_update(self, resource_group): + response = await ( + await self.client.private_endpoint_connections.begin_create_or_update( + resource_group_name=resource_group.name, + account_name="str", + private_endpoint_connection_name="str", + properties={ + "etag": "str", + "id": "str", + "location": "str", + "name": "str", + "properties": { + "privateLinkServiceConnectionState": { + "actionsRequired": "str", + "description": "str", + "status": "str", + }, + "groupIds": ["str"], + "privateEndpoint": {"id": "str"}, + "provisioningState": "str", + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_delete(self, resource_group): + response = await ( + await self.client.private_endpoint_connections.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + private_endpoint_connection_name="str", + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_private_link_resources_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_private_link_resources_operations.py new file mode 100644 index 000000000000..269f8ab124e2 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_private_link_resources_operations.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) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementPrivateLinkResourcesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.private_link_resources.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_private_link_resources_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_private_link_resources_operations_async.py new file mode 100644 index 000000000000..c0e569ca22da --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_private_link_resources_operations_async.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) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementPrivateLinkResourcesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = await self.client.private_link_resources.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_blocklist_items_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_blocklist_items_operations.py new file mode 100644 index 000000000000..024fcc253dab --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_blocklist_items_operations.py @@ -0,0 +1,118 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementRaiBlocklistItemsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.rai_blocklist_items.list( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get(self, resource_group): + response = self.client.rai_blocklist_items.get( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + rai_blocklist_item_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_create_or_update(self, resource_group): + response = self.client.rai_blocklist_items.create_or_update( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + rai_blocklist_item_name="str", + rai_blocklist_item={ + "etag": "str", + "id": "str", + "name": "str", + "properties": {"isRegex": bool, "pattern": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_delete(self, resource_group): + response = self.client.rai_blocklist_items.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + rai_blocklist_item_name="str", + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_batch_add(self, resource_group): + response = self.client.rai_blocklist_items.batch_add( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + rai_blocklist_items=[{"name": "str", "properties": {"isRegex": bool, "pattern": "str"}}], + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_batch_delete(self, resource_group): + response = self.client.rai_blocklist_items.batch_delete( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + rai_blocklist_items_names={}, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_blocklist_items_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_blocklist_items_operations_async.py new file mode 100644 index 000000000000..d1fbf3a58f36 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_blocklist_items_operations_async.py @@ -0,0 +1,121 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementRaiBlocklistItemsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.rai_blocklist_items.list( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get(self, resource_group): + response = await self.client.rai_blocklist_items.get( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + rai_blocklist_item_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_create_or_update(self, resource_group): + response = await self.client.rai_blocklist_items.create_or_update( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + rai_blocklist_item_name="str", + rai_blocklist_item={ + "etag": "str", + "id": "str", + "name": "str", + "properties": {"isRegex": bool, "pattern": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_delete(self, resource_group): + response = await ( + await self.client.rai_blocklist_items.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + rai_blocklist_item_name="str", + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_batch_add(self, resource_group): + response = await self.client.rai_blocklist_items.batch_add( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + rai_blocklist_items=[{"name": "str", "properties": {"isRegex": bool, "pattern": "str"}}], + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_batch_delete(self, resource_group): + response = await self.client.rai_blocklist_items.batch_delete( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + rai_blocklist_items_names={}, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_blocklists_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_blocklists_operations.py new file mode 100644 index 000000000000..8e8560968797 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_blocklists_operations.py @@ -0,0 +1,86 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementRaiBlocklistsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.rai_blocklists.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get(self, resource_group): + response = self.client.rai_blocklists.get( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_create_or_update(self, resource_group): + response = self.client.rai_blocklists.create_or_update( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + rai_blocklist={ + "etag": "str", + "id": "str", + "name": "str", + "properties": {"description": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_delete(self, resource_group): + response = self.client.rai_blocklists.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_blocklists_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_blocklists_operations_async.py new file mode 100644 index 000000000000..fb192a693373 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_blocklists_operations_async.py @@ -0,0 +1,89 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementRaiBlocklistsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.rai_blocklists.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get(self, resource_group): + response = await self.client.rai_blocklists.get( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_create_or_update(self, resource_group): + response = await self.client.rai_blocklists.create_or_update( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + rai_blocklist={ + "etag": "str", + "id": "str", + "name": "str", + "properties": {"description": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_delete(self, resource_group): + response = await ( + await self.client.rai_blocklists.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + rai_blocklist_name="str", + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_content_filters_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_content_filters_operations.py new file mode 100644 index 000000000000..fa1c0083fc96 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_content_filters_operations.py @@ -0,0 +1,42 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementRaiContentFiltersOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.rai_content_filters.list( + location="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get(self, resource_group): + response = self.client.rai_content_filters.get( + location="str", + filter_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_content_filters_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_content_filters_operations_async.py new file mode 100644 index 000000000000..bfc8ec002236 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_content_filters_operations_async.py @@ -0,0 +1,43 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementRaiContentFiltersOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.rai_content_filters.list( + location="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get(self, resource_group): + response = await self.client.rai_content_filters.get( + location="str", + filter_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_policies_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_policies_operations.py new file mode 100644 index 000000000000..80308b75060b --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_policies_operations.py @@ -0,0 +1,94 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementRaiPoliciesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.rai_policies.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get(self, resource_group): + response = self.client.rai_policies.get( + resource_group_name=resource_group.name, + account_name="str", + rai_policy_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_create_or_update(self, resource_group): + response = self.client.rai_policies.create_or_update( + resource_group_name=resource_group.name, + account_name="str", + rai_policy_name="str", + rai_policy={ + "etag": "str", + "id": "str", + "name": "str", + "properties": { + "basePolicyName": "str", + "contentFilters": [ + {"blocking": bool, "enabled": bool, "name": "str", "severityThreshold": "str", "source": "str"} + ], + "customBlocklists": [{"blocking": bool, "blocklistName": "str", "source": "str"}], + "mode": "str", + "type": "str", + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_begin_delete(self, resource_group): + response = self.client.rai_policies.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + rai_policy_name="str", + api_version="2024-10-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_policies_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_policies_operations_async.py new file mode 100644 index 000000000000..a74b7a510680 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_rai_policies_operations_async.py @@ -0,0 +1,97 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementRaiPoliciesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.rai_policies.list( + resource_group_name=resource_group.name, + account_name="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get(self, resource_group): + response = await self.client.rai_policies.get( + resource_group_name=resource_group.name, + account_name="str", + rai_policy_name="str", + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_create_or_update(self, resource_group): + response = await self.client.rai_policies.create_or_update( + resource_group_name=resource_group.name, + account_name="str", + rai_policy_name="str", + rai_policy={ + "etag": "str", + "id": "str", + "name": "str", + "properties": { + "basePolicyName": "str", + "contentFilters": [ + {"blocking": bool, "enabled": bool, "name": "str", "severityThreshold": "str", "source": "str"} + ], + "customBlocklists": [{"blocking": bool, "blocklistName": "str", "source": "str"}], + "mode": "str", + "type": "str", + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2024-10-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_begin_delete(self, resource_group): + response = await ( + await self.client.rai_policies.begin_delete( + resource_group_name=resource_group.name, + account_name="str", + rai_policy_name="str", + api_version="2024-10-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_resource_skus_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_resource_skus_operations.py new file mode 100644 index 000000000000..387f49b4e85f --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_resource_skus_operations.py @@ -0,0 +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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementResourceSkusOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.resource_skus.list( + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_resource_skus_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_resource_skus_operations_async.py new file mode 100644 index 000000000000..0b68fd9d6db6 --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_resource_skus_operations_async.py @@ -0,0 +1,30 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementResourceSkusOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.resource_skus.list( + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_usages_operations.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_usages_operations.py new file mode 100644 index 000000000000..2dc319f5c8ad --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_usages_operations.py @@ -0,0 +1,30 @@ +# 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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementUsagesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_list(self, resource_group): + response = self.client.usages.list( + location="str", + api_version="2024-10-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_usages_operations_async.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_usages_operations_async.py new file mode 100644 index 000000000000..fed20f87d97d --- /dev/null +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/generated_tests/test_cognitive_services_management_usages_operations_async.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) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.cognitiveservices.aio import CognitiveServicesManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestCognitiveServicesManagementUsagesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(CognitiveServicesManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_list(self, resource_group): + response = self.client.usages.list( + location="str", + api_version="2024-10-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/setup.py b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/setup.py index 5193a173990b..4e8885cd3582 100644 --- a/sdk/cognitiveservices/azure-mgmt-cognitiveservices/setup.py +++ b/sdk/cognitiveservices/azure-mgmt-cognitiveservices/setup.py @@ -22,11 +22,9 @@ # Version extraction inspired from 'requests' with open( - ( - os.path.join(package_folder_path, "version.py") - if os.path.exists(os.path.join(package_folder_path, "version.py")) - else os.path.join(package_folder_path, "_version.py") - ), + os.path.join(package_folder_path, "version.py") + if os.path.exists(os.path.join(package_folder_path, "version.py")) + else os.path.join(package_folder_path, "_version.py"), "r", ) as fd: version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) @@ -55,11 +53,11 @@ "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", "License :: OSI Approved :: MIT License", ], zip_safe=False, @@ -76,10 +74,10 @@ "pytyped": ["py.typed"], }, install_requires=[ - "isodate<1.0.0,>=0.6.1", - "azure-common~=1.1", - "azure-mgmt-core>=1.3.2,<2.0.0", - "typing-extensions>=4.3.0; python_version<'3.8.0'", + "isodate>=0.6.1", + "typing-extensions>=4.6.0", + "azure-common>=1.1", + "azure-mgmt-core>=1.3.2", ], - python_requires=">=3.7", + python_requires=">=3.8", )