From 32eb7767e040e32d6047304ce2aa7e62d633737c Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Thu, 11 Aug 2022 14:47:15 +0000 Subject: [PATCH] CodeGen from PR 20121 in Azure/azure-rest-api-specs Merge d4a2ceae8dee937042a4bcd897279570e38174a0 into 4b5383a3c9fb089d361d2e11f65d0d04c76e94ac --- .../azure-mgmt-labservices/_meta.json | 10 +- .../azure/mgmt/labservices/__init__.py | 18 +- .../azure/mgmt/labservices/_configuration.py | 53 +- .../mgmt/labservices/_lab_services_client.py | 23 +- .../mgmt/labservices/_managed_labs_client.py | 134 + .../azure/mgmt/labservices/_patch.py | 2 +- .../azure/mgmt/labservices/_serialization.py | 1970 +++++++++++++++ .../azure/mgmt/labservices/_vendor.py | 6 +- .../azure/mgmt/labservices/_version.py | 2 +- .../azure/mgmt/labservices/aio/__init__.py | 18 +- .../mgmt/labservices/aio/_configuration.py | 55 +- .../labservices/aio/_lab_services_client.py | 29 +- .../labservices/aio/_managed_labs_client.py | 131 + .../azure/mgmt/labservices/aio/_patch.py | 2 +- .../labservices/aio/operations/__init__.py | 30 +- .../aio/operations/_images_operations.py | 428 +++- .../aio/operations/_lab_plans_operations.py | 913 ++++--- .../aio/operations/_labs_operations.py | 940 ++++--- .../_operation_results_operations.py | 92 +- .../labservices/aio/operations/_operations.py | 103 +- .../mgmt/labservices/aio/operations/_patch.py | 20 + .../aio/operations/_schedules_operations.py | 549 ++-- .../aio/operations/_skus_operations.py | 113 +- .../aio/operations/_usages_operations.py | 114 +- .../aio/operations/_users_operations.py | 899 +++++-- .../_virtual_machines_operations.py | 801 +++--- .../azure/mgmt/labservices/models/__init__.py | 236 +- .../models/_lab_services_client_enums.py | 89 +- .../models/_managed_labs_client_enums.py | 263 ++ .../mgmt/labservices/models/_models_py3.py | 2234 ++++++++--------- .../azure/mgmt/labservices/models/_patch.py | 20 + .../mgmt/labservices/operations/__init__.py | 30 +- .../operations/_images_operations.py | 638 +++-- .../operations/_lab_plans_operations.py | 1268 ++++++---- .../operations/_labs_operations.py | 1340 +++++----- .../_operation_results_operations.py | 149 +- .../labservices/operations/_operations.py | 142 +- .../mgmt/labservices/operations/_patch.py | 20 + .../operations/_schedules_operations.py | 813 +++--- .../operations/_skus_operations.py | 161 +- .../operations/_usages_operations.py | 165 +- .../operations/_users_operations.py | 1242 +++++---- .../_virtual_machines_operations.py | 1210 +++++---- 43 files changed, 11367 insertions(+), 6108 deletions(-) create mode 100644 sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_managed_labs_client.py create mode 100644 sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_serialization.py create mode 100644 sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_managed_labs_client.py create mode 100644 sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_patch.py create mode 100644 sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_managed_labs_client_enums.py create mode 100644 sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_patch.py create mode 100644 sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_patch.py diff --git a/sdk/labservices/azure-mgmt-labservices/_meta.json b/sdk/labservices/azure-mgmt-labservices/_meta.json index 3f9d4b4ac6b5..dc5225a16ff6 100644 --- a/sdk/labservices/azure-mgmt-labservices/_meta.json +++ b/sdk/labservices/azure-mgmt-labservices/_meta.json @@ -1,11 +1,11 @@ { - "autorest": "3.7.2", + "autorest": "3.8.4", "use": [ - "@autorest/python@5.12.0", - "@autorest/modelerfour@4.19.3" + "@autorest/python@6.0.1", + "@autorest/modelerfour@4.23.5" ], - "commit": "0f149eb7239f7a262601bb5476e7772f06d1b28d", + "commit": "f963a5a562e738723636af6bfa4f8cf097663719", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/labservices/resource-manager/readme.md --multiapi --python --python-mode=update --python-sdks-folder=/home/vsts/work/1/azure-sdk-for-python/sdk --python3-only --track2 --use=@autorest/python@5.12.0 --use=@autorest/modelerfour@4.19.3 --version=3.7.2", + "autorest_command": "autorest specification/labservices/resource-manager/readme.md --models-mode=msrest --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.0.1 --use=@autorest/modelerfour@4.23.5 --version=3.8.4 --version-tolerant=False", "readme": "specification/labservices/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/__init__.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/__init__.py index 6c21b29185d9..c86a0ea819f8 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/__init__.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/__init__.py @@ -6,13 +6,19 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._lab_services_client import LabServicesClient +from ._managed_labs_client import ManagedLabsClient from ._version import VERSION __version__ = VERSION -__all__ = ['LabServicesClient'] -# `._patch.py` is used for handwritten extensions to the generated code -# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md -from ._patch import patch_sdk -patch_sdk() +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["ManagedLabsClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_configuration.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_configuration.py index 5142abd3893f..306ba9d5c687 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_configuration.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_configuration.py @@ -19,25 +19,25 @@ from azure.core.credentials import TokenCredential -class LabServicesClientConfiguration(Configuration): - """Configuration for LabServicesClient. +class ManagedLabsClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for ManagedLabsClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :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. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2022-08-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(LabServicesClientConfiguration, self).__init__(**kwargs) + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(ManagedLabsClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2022-08-01") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: @@ -45,24 +45,25 @@ def __init__( self.credential = credential self.subscription_id = subscription_id - self.api_version = "2021-11-15-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-labservices/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-labservices/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - 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.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + 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.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_lab_services_client.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_lab_services_client.py index 4316ab78f6fb..b6b929f94c25 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_lab_services_client.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_lab_services_client.py @@ -15,12 +15,24 @@ from . import models from ._configuration import LabServicesClientConfiguration -from .operations import ImagesOperations, LabPlansOperations, LabsOperations, OperationResultsOperations, Operations, SchedulesOperations, SkusOperations, UsagesOperations, UsersOperations, VirtualMachinesOperations +from .operations import ( + ImagesOperations, + LabPlansOperations, + LabsOperations, + OperationResultsOperations, + Operations, + SchedulesOperations, + SkusOperations, + UsagesOperations, + UsersOperations, + VirtualMachinesOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential + class LabServicesClient: """REST API for managing Azure Lab Services images. @@ -72,14 +84,17 @@ def __init__( self.lab_plans = LabPlansOperations(self._client, self._config, self._serialize, self._deserialize) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.labs = LabsOperations(self._client, self._config, self._serialize, self._deserialize) - self.operation_results = OperationResultsOperations(self._client, self._config, self._serialize, self._deserialize) + self.operation_results = OperationResultsOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.schedules = SchedulesOperations(self._client, self._config, self._serialize, self._deserialize) self.users = UsersOperations(self._client, self._config, self._serialize, self._deserialize) - self.virtual_machines = VirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize) + self.virtual_machines = VirtualMachinesOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.usages = UsagesOperations(self._client, self._config, self._serialize, self._deserialize) self.skus = SkusOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request( self, request, # type: HttpRequest diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_managed_labs_client.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_managed_labs_client.py new file mode 100644 index 000000000000..a5ce1e794e06 --- /dev/null +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_managed_labs_client.py @@ -0,0 +1,134 @@ +# 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 copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient + +from . import models +from ._configuration import ManagedLabsClientConfiguration +from ._serialization import Deserializer, Serializer +from .operations import ( + ImagesOperations, + LabPlansOperations, + LabsOperations, + OperationResultsOperations, + Operations, + SchedulesOperations, + SkusOperations, + UsagesOperations, + UsersOperations, + VirtualMachinesOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class ManagedLabsClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """REST API for managing Azure Lab Services images. + + :ivar images: ImagesOperations operations + :vartype images: azure.mgmt.labservices.operations.ImagesOperations + :ivar lab_plans: LabPlansOperations operations + :vartype lab_plans: azure.mgmt.labservices.operations.LabPlansOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.labservices.operations.Operations + :ivar labs: LabsOperations operations + :vartype labs: azure.mgmt.labservices.operations.LabsOperations + :ivar operation_results: OperationResultsOperations operations + :vartype operation_results: azure.mgmt.labservices.operations.OperationResultsOperations + :ivar schedules: SchedulesOperations operations + :vartype schedules: azure.mgmt.labservices.operations.SchedulesOperations + :ivar skus: SkusOperations operations + :vartype skus: azure.mgmt.labservices.operations.SkusOperations + :ivar usages: UsagesOperations operations + :vartype usages: azure.mgmt.labservices.operations.UsagesOperations + :ivar users: UsersOperations operations + :vartype users: azure.mgmt.labservices.operations.UsersOperations + :ivar virtual_machines: VirtualMachinesOperations operations + :vartype virtual_machines: azure.mgmt.labservices.operations.VirtualMachinesOperations + :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 "2022-08-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = ManagedLabsClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.images = ImagesOperations(self._client, self._config, self._serialize, self._deserialize) + self.lab_plans = LabPlansOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.labs = LabsOperations(self._client, self._config, self._serialize, self._deserialize) + self.operation_results = OperationResultsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.schedules = SchedulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.skus = SkusOperations(self._client, self._config, self._serialize, self._deserialize) + self.usages = UsagesOperations(self._client, self._config, self._serialize, self._deserialize) + self.users = UsersOperations(self._client, self._config, self._serialize, self._deserialize) + self.virtual_machines = VirtualMachinesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> ManagedLabsClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_patch.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_patch.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_serialization.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_serialization.py new file mode 100644 index 000000000000..648f84cc4e65 --- /dev/null +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_serialization.py @@ -0,0 +1,1970 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# pylint: skip-file + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote # type: ignore +import xml.etree.ElementTree as ET + +import isodate + +from typing import Dict, Any, cast, TYPE_CHECKING + +from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +if TYPE_CHECKING: + from typing import Optional, Union, AnyStr, IO, Mapping + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data, content_type=None): + # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError: + # 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 + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # 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("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes, headers): + # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +try: + basestring # type: ignore + unicode_str = unicode # type: ignore +except NameError: + basestring = str # type: ignore + unicode_str = str # type: ignore + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + + +class UTC(datetime.tzinfo): + """Time Zone info for handling UTC""" + + def utcoffset(self, dt): + """UTF offset for UTC is 0.""" + return datetime.timedelta(0) + + def tzname(self, dt): + """Timestamp representation.""" + return "Z" + + def dst(self, dt): + """No daylight saving for UTC.""" + return datetime.timedelta(hours=1) + + +try: + from datetime import timezone as _FixedOffset +except ImportError: # Python 2.7 + + class _FixedOffset(datetime.tzinfo): # type: ignore + """Fixed offset in minutes east from UTC. + Copy/pasted from Python doc + :param datetime.timedelta offset: offset in timedelta format + """ + + def __init__(self, offset): + self.__offset = offset + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds() / 3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + def __getinitargs__(self): + return (self.__offset,) + + +try: + from datetime import timezone + + TZ_UTC = timezone.utc # type: ignore +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes=None): + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize(self, target_obj, data_type=None, **kwargs): + """Serialize data into a string according to type. + + :param target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises: SerializationError if serialization fails. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() + try: + attributes = target_obj._attribute_map + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized.update(target_obj.additional_properties) + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) + continue + if xml_desc.get("text", False): + serialized.text = new_attr + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) + 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) + serialized.append(local_node) + else: # JSON + for k in reversed(keys): + unflattened = {k: new_attr} + new_attr = unflattened + + _new_attr = new_attr + _serialized = serialized + for k in keys: + if k not in _serialized: + _serialized.update(_new_attr) + _new_attr = _new_attr[k] + _serialized = _serialized[k] + except ValueError: + continue + + 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) + else: + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises: SerializationError if serialization fails. + :raises: ValueError if data is None + """ + + # Just in case this is a dict + internal_data_type = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) + except DeserializationError as err: + raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + # 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)) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :param bool required: Whether it's essential that the data not be + empty or None + :raises: AttributeError if required data is None. + :raises: ValueError if data is None + :raises: SerializationError if serialization fails. + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + elif data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, data.__class__) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **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) + else: + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param data: Object to be serialized. + :param str data_type: Type of object in the iterable. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + return eval(data_type)(data) # nosec + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param data: Object to be serialized. + :rtype: str + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + else: + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list attr: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param bool required: Whether the objects in the iterable must + not be None or empty. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + :rtype: list, str + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError: + serialized.append(None) + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :param bool required: Whether the objects in the dictionary must + not be None or empty. + :rtype: dict + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + 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: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + elif obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) + return result + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) + + @staticmethod + def serialize_bytearray(attr, **kwargs): + """Serialize bytearray into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): + """Serialize str into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): + """Serialize Decimal object to float. + + :param attr: Object to be serialized. + :rtype: float + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): + """Serialize long (Py2) or int (Py3). + + :param attr: Object to be serialized. + :rtype: int/long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: TypeError if format invalid. + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError: + raise TypeError("RFC1123 object must be valid Datetime object.") + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: SerializationError if format invalid. + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise_with_traceback(SerializationError, msg, err) + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise_with_traceback(TypeError, msg, err) + + @staticmethod + def serialize_unix(attr, **kwargs): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises: SerializationError if format invalid + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError: + raise TypeError("Unix time object must be valid Datetime object.") + + +def rest_key_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, 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:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_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:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key.""" + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + else: + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + else: # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer(object): + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes=None): + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies = 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 + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, basestring): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None: + return data + try: + attributes = response._attribute_map + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name + raise_with_traceback(DeserializationError, msg, err) + else: + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + """ + if target is None: + return None, None + + if isinstance(target, basestring): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + :param str content_type: Swagger "produces" if available. + """ + try: + return self(target_obj, data, content_type=content_type) + except: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param raw_data: Data to be processed. + :param content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + 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"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param response: The response model class. + :param d_attrs: The deserialized response attributes. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [k for k, v in response._validation.items() if v.get("readonly")] + const = [k for k, v in response._validation.items() if v.get("constant")] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) + + def deserialize_data(self, data, data_type): + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_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) + else: + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :rtype: dict + :raises: TypeError if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, basestring): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + else: + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :rtype: str, int, float or bool + :raises: TypeError if string format is not valid. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + else: + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + elif isinstance(attr, basestring): + if attr.lower() in ["true", "1"]: + return True + elif attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + return eval(data_type)(attr) # nosec + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): + return data + except NameError: + return str(data) + else: + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + 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: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) + attr = attr + padding + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :rtype: Decimal + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(attr) + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise_with_traceback(DeserializationError, msg, err) + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :rtype: long or int + :raises: ValueError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :rtype: TimeDelta + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise_with_traceback(DeserializationError, msg, err) + else: + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :rtype: Date + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + 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) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + 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) + else: + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :rtype: Datetime + :raises: DeserializationError if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) + try: + 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) + else: + return date_obj diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_vendor.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_vendor.py index 138f663c53a4..9aad73fc743e 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_vendor.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_vendor.py @@ -7,6 +7,7 @@ from azure.core.pipeline.transport import HttpRequest + 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) @@ -14,6 +15,7 @@ def _convert_request(request, files=None): request.set_formdata_body(files) return request + def _format_url_section(template, **kwargs): components = template.split("/") while components: @@ -21,7 +23,5 @@ def _format_url_section(template, **kwargs): return template.format(**kwargs) except KeyError as key: formatted_components = template.split("/") - components = [ - c for c in formatted_components if "{}".format(key.args[0]) not in c - ] + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] template = "/".join(components) diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_version.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_version.py index e32dc6ec4218..c47f66669f1b 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_version.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0b1" +VERSION = "1.0.0" diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/__init__.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/__init__.py index fa404ff18f8b..a13ee1764e5b 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/__init__.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/__init__.py @@ -6,10 +6,16 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._lab_services_client import LabServicesClient -__all__ = ['LabServicesClient'] +from ._managed_labs_client import ManagedLabsClient -# `._patch.py` is used for handwritten extensions to the generated code -# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md -from ._patch import patch_sdk -patch_sdk() +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["ManagedLabsClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_configuration.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_configuration.py index 44f7e1f97102..98555bc42626 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_configuration.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_configuration.py @@ -19,25 +19,25 @@ from azure.core.credentials_async import AsyncTokenCredential -class LabServicesClientConfiguration(Configuration): - """Configuration for LabServicesClient. +class ManagedLabsClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for ManagedLabsClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :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. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2022-08-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(LabServicesClientConfiguration, self).__init__(**kwargs) + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(ManagedLabsClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2022-08-01") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: @@ -45,23 +45,22 @@ def __init__( self.credential = credential self.subscription_id = subscription_id - self.api_version = "2021-11-15-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-labservices/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-labservices/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - 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.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + 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.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_lab_services_client.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_lab_services_client.py index 07f03fe0fd4b..a3c1e9ef2b9b 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_lab_services_client.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_lab_services_client.py @@ -15,12 +15,24 @@ from .. import models from ._configuration import LabServicesClientConfiguration -from .operations import ImagesOperations, LabPlansOperations, LabsOperations, OperationResultsOperations, Operations, SchedulesOperations, SkusOperations, UsagesOperations, UsersOperations, VirtualMachinesOperations +from .operations import ( + ImagesOperations, + LabPlansOperations, + LabsOperations, + OperationResultsOperations, + Operations, + SchedulesOperations, + SkusOperations, + UsagesOperations, + UsersOperations, + VirtualMachinesOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential + class LabServicesClient: """REST API for managing Azure Lab Services images. @@ -72,19 +84,18 @@ def __init__( self.lab_plans = LabPlansOperations(self._client, self._config, self._serialize, self._deserialize) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.labs = LabsOperations(self._client, self._config, self._serialize, self._deserialize) - self.operation_results = OperationResultsOperations(self._client, self._config, self._serialize, self._deserialize) + self.operation_results = OperationResultsOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.schedules = SchedulesOperations(self._client, self._config, self._serialize, self._deserialize) self.users = UsersOperations(self._client, self._config, self._serialize, self._deserialize) - self.virtual_machines = VirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize) + self.virtual_machines = VirtualMachinesOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.usages = UsagesOperations(self._client, self._config, self._serialize, self._deserialize) self.skus = SkusOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_managed_labs_client.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_managed_labs_client.py new file mode 100644 index 000000000000..8c84b8003f27 --- /dev/null +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_managed_labs_client.py @@ -0,0 +1,131 @@ +# 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 copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models +from .._serialization import Deserializer, Serializer +from ._configuration import ManagedLabsClientConfiguration +from .operations import ( + ImagesOperations, + LabPlansOperations, + LabsOperations, + OperationResultsOperations, + Operations, + SchedulesOperations, + SkusOperations, + UsagesOperations, + UsersOperations, + VirtualMachinesOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class ManagedLabsClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """REST API for managing Azure Lab Services images. + + :ivar images: ImagesOperations operations + :vartype images: azure.mgmt.labservices.aio.operations.ImagesOperations + :ivar lab_plans: LabPlansOperations operations + :vartype lab_plans: azure.mgmt.labservices.aio.operations.LabPlansOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.labservices.aio.operations.Operations + :ivar labs: LabsOperations operations + :vartype labs: azure.mgmt.labservices.aio.operations.LabsOperations + :ivar operation_results: OperationResultsOperations operations + :vartype operation_results: azure.mgmt.labservices.aio.operations.OperationResultsOperations + :ivar schedules: SchedulesOperations operations + :vartype schedules: azure.mgmt.labservices.aio.operations.SchedulesOperations + :ivar skus: SkusOperations operations + :vartype skus: azure.mgmt.labservices.aio.operations.SkusOperations + :ivar usages: UsagesOperations operations + :vartype usages: azure.mgmt.labservices.aio.operations.UsagesOperations + :ivar users: UsersOperations operations + :vartype users: azure.mgmt.labservices.aio.operations.UsersOperations + :ivar virtual_machines: VirtualMachinesOperations operations + :vartype virtual_machines: azure.mgmt.labservices.aio.operations.VirtualMachinesOperations + :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 "2022-08-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = ManagedLabsClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.images = ImagesOperations(self._client, self._config, self._serialize, self._deserialize) + self.lab_plans = LabPlansOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.labs = LabsOperations(self._client, self._config, self._serialize, self._deserialize) + self.operation_results = OperationResultsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.schedules = SchedulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.skus = SkusOperations(self._client, self._config, self._serialize, self._deserialize) + self.usages = UsagesOperations(self._client, self._config, self._serialize, self._deserialize) + self.users = UsersOperations(self._client, self._config, self._serialize, self._deserialize) + self.virtual_machines = VirtualMachinesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "ManagedLabsClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_patch.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_patch.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/__init__.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/__init__.py index f4c911b36ab4..dfde78e0230c 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/__init__.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/__init__.py @@ -12,20 +12,26 @@ from ._labs_operations import LabsOperations from ._operation_results_operations import OperationResultsOperations from ._schedules_operations import SchedulesOperations +from ._skus_operations import SkusOperations +from ._usages_operations import UsagesOperations from ._users_operations import UsersOperations from ._virtual_machines_operations import VirtualMachinesOperations -from ._usages_operations import UsagesOperations -from ._skus_operations import SkusOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'ImagesOperations', - 'LabPlansOperations', - 'Operations', - 'LabsOperations', - 'OperationResultsOperations', - 'SchedulesOperations', - 'UsersOperations', - 'VirtualMachinesOperations', - 'UsagesOperations', - 'SkusOperations', + "ImagesOperations", + "LabPlansOperations", + "Operations", + "LabsOperations", + "OperationResultsOperations", + "SchedulesOperations", + "SkusOperations", + "UsagesOperations", + "UsersOperations", + "VirtualMachinesOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_images_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_images_operations.py index 5d523bd83ff4..fb4ecedabbb2 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_images_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_images_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,100 +6,111 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import 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 ..._vendor import _convert_request -from ...operations._images_operations import build_create_or_update_request, build_get_request, build_list_by_lab_plan_request, build_update_request -T = TypeVar('T') +from ...operations._images_operations import ( + build_create_or_update_request, + build_get_request, + build_list_by_lab_plan_request, + build_update_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ImagesOperations: - """ImagesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class ImagesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.aio.ManagedLabsClient`'s + :attr:`images` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_by_lab_plan( - self, - resource_group_name: str, - lab_plan_name: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.PagedImages"]: + self, resource_group_name: str, lab_plan_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.Image"]: """Gets all images. Gets all images from galleries attached to a lab plan. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 PagedImages or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.PagedImages] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Image or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.Image] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedImages"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedImages] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_lab_plan_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, + subscription_id=self._config.subscription_id, filter=filter, - template_url=self.list_by_lab_plan.metadata['url'], + api_version=api_version, + template_url=self.list_by_lab_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) # type: ignore else: - - request = build_list_by_lab_plan_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - lab_plan_name=lab_plan_name, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -112,7 +124,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -122,54 +136,55 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_lab_plan.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images'} # type: ignore + list_by_lab_plan.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images"} # type: ignore @distributed_trace_async - async def get( - self, - resource_group_name: str, - lab_plan_name: str, - image_name: str, - **kwargs: Any - ) -> "_models.Image": + async def get(self, resource_group_name: str, lab_plan_name: str, image_name: str, **kwargs: Any) -> _models.Image: """Gets an image. Gets an image resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str - :param image_name: The image name. + :param image_name: The image name. Required. :type image_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Image, or the result of cls(response) + :return: Image or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.Image - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Image"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Image] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, image_name=image_name, - template_url=self.get.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -177,15 +192,82 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Image', pipeline_response) + deserialized = self._deserialize("Image", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}"} # type: ignore + + @overload + async def create_or_update( + self, + resource_group_name: str, + lab_plan_name: str, + image_name: str, + body: _models.Image, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Image: + """Updates an image via PUT. + + Updates an image resource via PUT. Creating new resources via PUT will not function. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param image_name: The image name. Required. + :type image_name: str + :param body: The request body. Required. + :type body: ~azure.mgmt.labservices.models.Image + :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: Image or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Image + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + lab_plan_name: str, + image_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Image: + """Updates an image via PUT. + + Updates an image resource via PUT. Creating new resources via PUT will not function. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param image_name: The image name. Required. + :type image_name: str + :param body: The request body. Required. + :type body: IO + :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: Image or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Image + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def create_or_update( @@ -193,50 +275,69 @@ async def create_or_update( resource_group_name: str, lab_plan_name: str, image_name: str, - body: "_models.Image", + body: Union[_models.Image, IO], **kwargs: Any - ) -> "_models.Image": + ) -> _models.Image: """Updates an image via PUT. Updates an image resource via PUT. Creating new resources via PUT will not function. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str - :param image_name: The image name. + :param image_name: The image name. Required. :type image_name: str - :param body: The request body. - :type body: ~azure.mgmt.labservices.models.Image + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.Image 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 - :return: Image, or the result of cls(response) + :return: Image or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.Image - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Image"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(body, 'Image') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Image] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "Image") request = build_create_or_update_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, image_name=image_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.create_or_update.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -244,15 +345,82 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Image', pipeline_response) + deserialized = self._deserialize("Image", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}'} # type: ignore + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}"} # type: ignore + + @overload + async def update( + self, + resource_group_name: str, + lab_plan_name: str, + image_name: str, + body: _models.ImageUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Image: + """Updates an image. + + Updates an image resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param image_name: The image name. Required. + :type image_name: str + :param body: The request body. Required. + :type body: ~azure.mgmt.labservices.models.ImageUpdate + :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: Image or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Image + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + lab_plan_name: str, + image_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Image: + """Updates an image. + + Updates an image resource. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param image_name: The image name. Required. + :type image_name: str + :param body: The request body. Required. + :type body: IO + :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: Image or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Image + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def update( @@ -260,50 +428,69 @@ async def update( resource_group_name: str, lab_plan_name: str, image_name: str, - body: "_models.ImageUpdate", + body: Union[_models.ImageUpdate, IO], **kwargs: Any - ) -> "_models.Image": + ) -> _models.Image: """Updates an image. Updates an image resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str - :param image_name: The image name. + :param image_name: The image name. Required. :type image_name: str - :param body: The request body. - :type body: ~azure.mgmt.labservices.models.ImageUpdate + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.ImageUpdate 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 - :return: Image, or the result of cls(response) + :return: Image or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.Image - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Image"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Image] - _json = self._serialize.body(body, 'ImageUpdate') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ImageUpdate") request = build_update_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, image_name=image_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -311,12 +498,11 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Image', pipeline_response) + deserialized = self._deserialize("Image", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}'} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_lab_plans_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_lab_plans_operations.py index 9cf8934b813b..efa2f8f5619a 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_lab_plans_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_lab_plans_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,91 +6,106 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + 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.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 ..._vendor import _convert_request -from ...operations._lab_plans_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_resource_group_request, build_list_by_subscription_request, build_save_image_request_initial, build_update_request_initial -T = TypeVar('T') +from ...operations._lab_plans_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_request, + build_list_by_subscription_request, + build_save_image_request, + build_update_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class LabPlansOperations: - """LabPlansOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class LabPlansOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.aio.ManagedLabsClient`'s + :attr:`lab_plans` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_by_subscription( - self, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.PagedLabPlans"]: + def list_by_subscription(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.LabPlan"]: """Get all lab plans for a subscription. Returns a list of all lab plans within a subscription. - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 PagedLabPlans or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.PagedLabPlans] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either LabPlan or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.LabPlan] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedLabPlans"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedLabPlans] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, filter=filter, - template_url=self.list_by_subscription.metadata['url'], + api_version=api_version, + template_url=self.list_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) # type: ignore else: - - request = build_list_by_subscription_request( - subscription_id=self._config.subscription_id, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -103,7 +119,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -113,54 +131,55 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/labPlans'} # type: ignore + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/labPlans"} # type: ignore @distributed_trace - def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.PagedLabPlans"]: + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.LabPlan"]: """Get all lab plans for a subscription and resource group. Returns a list of all lab plans for a subscription and 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 PagedLabPlans or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.PagedLabPlans] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either LabPlan or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.LabPlan] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedLabPlans"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedLabPlans] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, - template_url=self.list_by_resource_group.metadata['url'], + 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) # type: ignore else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -174,7 +193,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -184,50 +205,52 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans'} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans"} # type: ignore @distributed_trace_async - async def get( - self, - resource_group_name: str, - lab_plan_name: str, - **kwargs: Any - ) -> "_models.LabPlan": + async def get(self, resource_group_name: str, lab_plan_name: str, **kwargs: Any) -> _models.LabPlan: """Retrieves a Lab Plan resource. Retrieves the properties of a Lab Plan. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: LabPlan, or the result of cls(response) + :return: LabPlan or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.LabPlan - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.LabPlan"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.LabPlan] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, - template_url=self.get.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -235,87 +258,103 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}"} # type: ignore async def _create_or_update_initial( - self, - resource_group_name: str, - lab_plan_name: str, - body: "_models.LabPlan", - **kwargs: Any - ) -> "_models.LabPlan": - cls = kwargs.pop('cls', None) # type: ClsType["_models.LabPlan"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(body, 'LabPlan') + self, resource_group_name: str, lab_plan_name: str, body: Union[_models.LabPlan, IO], **kwargs: Any + ) -> _models.LabPlan: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.LabPlan] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "LabPlan") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}'} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}"} # type: ignore - - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, lab_plan_name: str, - body: "_models.LabPlan", + body: _models.LabPlan, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.LabPlan"]: + ) -> AsyncLROPoller[_models.LabPlan]: """Updates or creates a Lab Plan resource. Operation to create or update a Lab Plan resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str - :param body: The request body. + :param body: The request body. Required. :type body: ~azure.mgmt.labservices.models.LabPlan + :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 @@ -327,118 +366,214 @@ async def begin_create_or_update( :return: An instance of AsyncLROPoller that returns either LabPlan or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.LabPlan] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.LabPlan"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + lab_plan_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.LabPlan]: + """Updates or creates a Lab Plan resource. + + Operation to create or update a Lab Plan resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param body: The request body. Required. + :type body: IO + :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 LabPlan or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.LabPlan] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, resource_group_name: str, lab_plan_name: str, body: Union[_models.LabPlan, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.LabPlan]: + """Updates or creates a Lab Plan resource. + + Operation to create or update a Lab Plan resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.LabPlan 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. + :return: An instance of AsyncLROPoller that returns either LabPlan or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.LabPlan] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.LabPlan] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._create_or_update_initial( + raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'original-uri'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncARMPolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs), + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}"} # type: ignore async def _update_initial( - self, - resource_group_name: str, - lab_plan_name: str, - body: "_models.LabPlanUpdate", - **kwargs: Any - ) -> "_models.LabPlan": - cls = kwargs.pop('cls', None) # type: ClsType["_models.LabPlan"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(body, 'LabPlanUpdate') + self, resource_group_name: str, lab_plan_name: str, body: Union[_models.LabPlanUpdate, IO], **kwargs: Any + ) -> _models.LabPlan: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.LabPlan] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "LabPlanUpdate") - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_update_request( resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}'} # type: ignore - + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}"} # type: ignore - @distributed_trace_async + @overload async def begin_update( self, resource_group_name: str, lab_plan_name: str, - body: "_models.LabPlanUpdate", + body: _models.LabPlanUpdate, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.LabPlan"]: + ) -> AsyncLROPoller[_models.LabPlan]: """Updates a Lab Plan resource. Operation to update a Lab Plan resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str - :param body: The request body. + :param body: The request body. Required. :type body: ~azure.mgmt.labservices.models.LabPlanUpdate + :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 @@ -450,92 +585,170 @@ async def begin_update( :return: An instance of AsyncLROPoller that returns either LabPlan or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.LabPlan] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.LabPlan"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_update( + self, + resource_group_name: str, + lab_plan_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.LabPlan]: + """Updates a Lab Plan resource. + + Operation to update a Lab Plan resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param body: The request body. Required. + :type body: IO + :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 LabPlan or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.LabPlan] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, resource_group_name: str, lab_plan_name: str, body: Union[_models.LabPlanUpdate, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.LabPlan]: + """Updates a Lab Plan resource. + + Operation to update a Lab Plan resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.LabPlanUpdate 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. + :return: An instance of AsyncLROPoller that returns either LabPlan or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.LabPlan] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.LabPlan] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._update_initial( + raw_result = await self._update_initial( # type: ignore resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}'} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}"} # type: ignore - async def _delete_initial( - self, - resource_group_name: str, - lab_plan_name: str, - **kwargs: Any + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_plan_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, - template_url=self._delete_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}"} # type: ignore @distributed_trace_async - async def begin_delete( - self, - resource_group_name: str, - lab_plan_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_delete(self, resource_group_name: str, lab_plan_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Deletes a Lab Plan resource. Operation to delete a Lab Plan resource. Deleting a lab plan does not delete labs associated @@ -543,9 +756,10 @@ async def begin_delete( permission container. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_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. @@ -557,91 +771,111 @@ async def begin_delete( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._delete_initial( + raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}"} # type: ignore - async def _save_image_initial( - self, - resource_group_name: str, - lab_plan_name: str, - body: "_models.SaveImageBody", - **kwargs: Any + async def _save_image_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_plan_name: str, body: Union[_models.SaveImageBody, IO], **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(body, 'SaveImageBody') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] - request = build_save_image_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "SaveImageBody") + + request = build_save_image_request( resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._save_image_initial.metadata['url'], + content=_content, + template_url=self._save_image_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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _save_image_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/saveImage'} # type: ignore + _save_image_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/saveImage"} # type: ignore - - @distributed_trace_async + @overload async def begin_save_image( self, resource_group_name: str, lab_plan_name: str, - body: "_models.SaveImageBody", + body: _models.SaveImageBody, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[None]: """Save an image from a lab VM to the attached shared image gallery. @@ -649,12 +883,16 @@ async def begin_save_image( Saves an image from a lab VM to the attached shared image gallery. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str - :param body: The request body. + :param body: The request body. Required. :type body: ~azure.mgmt.labservices.models.SaveImageBody + :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 @@ -665,43 +903,120 @@ async def begin_save_image( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_save_image( + self, + resource_group_name: str, + lab_plan_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Save an image from a lab VM to the attached shared image gallery. + + Saves an image from a lab VM to the attached shared image gallery. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param body: The request body. Required. + :type body: IO + :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 None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_save_image( + self, resource_group_name: str, lab_plan_name: str, body: Union[_models.SaveImageBody, IO], **kwargs: Any + ) -> AsyncLROPoller[None]: + """Save an image from a lab VM to the attached shared image gallery. + + Saves an image from a lab VM to the attached shared image gallery. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.SaveImageBody 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. + :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 = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._save_image_initial( + raw_result = await self._save_image_initial( # type: ignore resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_save_image.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/saveImage'} # type: ignore + begin_save_image.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/saveImage"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_labs_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_labs_operations.py index bec533939416..f20a3af8d442 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_labs_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_labs_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,91 +6,107 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + 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.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 ..._vendor import _convert_request -from ...operations._labs_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_resource_group_request, build_list_by_subscription_request, build_publish_request_initial, build_sync_group_request_initial, build_update_request_initial -T = TypeVar('T') +from ...operations._labs_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_request, + build_list_by_subscription_request, + build_publish_request, + build_sync_group_request, + build_update_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class LabsOperations: - """LabsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class LabsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.aio.ManagedLabsClient`'s + :attr:`labs` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_by_subscription( - self, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.PagedLabs"]: + def list_by_subscription(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.Lab"]: """Get all labs for a subscription. Returns a list of all labs for a subscription. - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 PagedLabs or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.PagedLabs] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Lab or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.Lab] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedLabs"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedLabs] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, filter=filter, - template_url=self.list_by_subscription.metadata['url'], + api_version=api_version, + template_url=self.list_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) # type: ignore else: - - request = build_list_by_subscription_request( - subscription_id=self._config.subscription_id, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -103,7 +120,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -113,54 +132,55 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/labs'} # type: ignore + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/labs"} # type: ignore @distributed_trace - def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.PagedLabs"]: + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.Lab"]: """Get all labs for a subscription and resource group. Returns a list of all labs in a 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 PagedLabs or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.PagedLabs] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Lab or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.Lab] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedLabs"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedLabs] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, - template_url=self.list_by_resource_group.metadata['url'], + 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) # type: ignore else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -174,7 +194,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -184,50 +206,52 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs'} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs"} # type: ignore @distributed_trace_async - async def get( - self, - resource_group_name: str, - lab_name: str, - **kwargs: Any - ) -> "_models.Lab": + async def get(self, resource_group_name: str, lab_name: str, **kwargs: Any) -> _models.Lab: """Get a lab resource. Returns the properties of a lab resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Lab, or the result of cls(response) + :return: Lab or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.Lab - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Lab"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Lab] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, - template_url=self.get.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -235,87 +259,103 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}"} # type: ignore async def _create_or_update_initial( - self, - resource_group_name: str, - lab_name: str, - body: "_models.Lab", - **kwargs: Any - ) -> "_models.Lab": - cls = kwargs.pop('cls', None) # type: ClsType["_models.Lab"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(body, 'Lab') + self, resource_group_name: str, lab_name: str, body: Union[_models.Lab, IO], **kwargs: Any + ) -> _models.Lab: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Lab] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "Lab") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, lab_name=lab_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}'} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}"} # type: ignore - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, lab_name: str, - body: "_models.Lab", + body: _models.Lab, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.Lab"]: + ) -> AsyncLROPoller[_models.Lab]: """Create or update a lab resource. Operation to create or update a lab resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str - :param body: The request body. + :param body: The request body. Required. :type body: ~azure.mgmt.labservices.models.Lab + :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 @@ -326,118 +366,212 @@ async def begin_create_or_update( Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Lab or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.Lab] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.Lab"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + lab_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Lab]: + """Create or update a lab resource. + + Operation to create or update a lab resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param body: The request body. Required. + :type body: IO + :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 Lab or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.Lab] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, resource_group_name: str, lab_name: str, body: Union[_models.Lab, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.Lab]: + """Create or update a lab resource. + + Operation to create or update a lab resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.Lab 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. + :return: An instance of AsyncLROPoller that returns either Lab or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.Lab] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Lab] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._create_or_update_initial( + raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'original-uri'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncARMPolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs), + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}"} # type: ignore async def _update_initial( - self, - resource_group_name: str, - lab_name: str, - body: "_models.LabUpdate", - **kwargs: Any - ) -> "_models.Lab": - cls = kwargs.pop('cls', None) # type: ClsType["_models.Lab"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(body, 'LabUpdate') + self, resource_group_name: str, lab_name: str, body: Union[_models.LabUpdate, IO], **kwargs: Any + ) -> _models.Lab: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Lab] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "LabUpdate") - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_update_request( resource_group_name=resource_group_name, lab_name=lab_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}'} # type: ignore - + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}"} # type: ignore - @distributed_trace_async + @overload async def begin_update( self, resource_group_name: str, lab_name: str, - body: "_models.LabUpdate", + body: _models.LabUpdate, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.Lab"]: + ) -> AsyncLROPoller[_models.Lab]: """Update a lab resource. Operation to update a lab resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str - :param body: The request body. + :param body: The request body. Required. :type body: ~azure.mgmt.labservices.models.LabUpdate + :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 @@ -448,100 +582,177 @@ async def begin_update( Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Lab or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.Lab] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.Lab"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_update( + self, + resource_group_name: str, + lab_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Lab]: + """Update a lab resource. + + Operation to update a lab resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param body: The request body. Required. + :type body: IO + :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 Lab or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.Lab] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, resource_group_name: str, lab_name: str, body: Union[_models.LabUpdate, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.Lab]: + """Update a lab resource. + + Operation to update a lab resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.LabUpdate 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. + :return: An instance of AsyncLROPoller that returns either Lab or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.Lab] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Lab] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._update_initial( + raw_result = await self._update_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}'} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}"} # type: ignore - async def _delete_initial( - self, - resource_group_name: str, - lab_name: str, - **kwargs: Any + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( resource_group_name=resource_group_name, lab_name=lab_name, - template_url=self._delete_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}"} # type: ignore @distributed_trace_async - async def begin_delete( - self, - resource_group_name: str, - lab_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_delete(self, resource_group_name: str, lab_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Deletes a lab resource. Operation to delete a lab resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_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. @@ -553,95 +764,103 @@ async def begin_delete( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._delete_initial( + raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}"} # type: ignore - async def _publish_initial( - self, - resource_group_name: str, - lab_name: str, - **kwargs: Any + async def _publish_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_publish_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_publish_request( resource_group_name=resource_group_name, lab_name=lab_name, - template_url=self._publish_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._publish_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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _publish_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/publish'} # type: ignore - + _publish_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/publish"} # type: ignore @distributed_trace_async - async def begin_publish( - self, - resource_group_name: str, - lab_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_publish(self, resource_group_name: str, lab_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Publish or re-publish a lab. Publish or re-publish a lab. This will create or update all lab resources, such as virtual machines. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_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. @@ -653,94 +872,102 @@ async def begin_publish( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._publish_initial( + raw_result = await self._publish_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_publish.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/publish'} # type: ignore + begin_publish.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/publish"} # type: ignore - async def _sync_group_initial( - self, - resource_group_name: str, - lab_name: str, - **kwargs: Any + async def _sync_group_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_sync_group_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_sync_group_request( resource_group_name=resource_group_name, lab_name=lab_name, - template_url=self._sync_group_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._sync_group_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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _sync_group_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/syncGroup'} # type: ignore - + _sync_group_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/syncGroup"} # type: ignore @distributed_trace_async - async def begin_sync_group( - self, - resource_group_name: str, - lab_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_sync_group(self, resource_group_name: str, lab_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Manually sync the lab group. Action used to manually kick off an AAD group sync job. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_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. @@ -752,40 +979,47 @@ async def begin_sync_group( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._sync_group_initial( + raw_result = await self._sync_group_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_sync_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/syncGroup'} # type: ignore + begin_sync_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/syncGroup"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_operation_results_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_operation_results_operations.py index e9268ee54665..161c26e690cf 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_operation_results_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_operation_results_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,78 +6,86 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._operation_results_operations import build_get_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class OperationResultsOperations: - """OperationResultsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class OperationResultsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.aio.ManagedLabsClient`'s + :attr:`operation_results` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_async - async def get( - self, - operation_result_id: str, - **kwargs: Any - ) -> Optional["_models.OperationResult"]: + async def get(self, operation_result_id: str, **kwargs: Any) -> Optional[_models.OperationResult]: """Get an azure operation result. Returns an azure operation result. - :param operation_result_id: The operation result ID / name. + :param operation_result_id: The operation result ID / name. Required. :type operation_result_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: OperationResult, or the result of cls(response) + :return: OperationResult or None or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.OperationResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationResult"]] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.OperationResult]] - request = build_get_request( - subscription_id=self._config.subscription_id, operation_result_id=operation_result_id, - template_url=self.get.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -86,12 +95,11 @@ async def get( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('OperationResult', pipeline_response) + deserialized = self._deserialize("OperationResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/operationResults/{operationResultId}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/operationResults/{operationResultId}"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_operations.py index f67c32045850..988b65a5e2b6 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,83 +6,91 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import 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 ..._vendor import _convert_request from ...operations._operations import build_list_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.aio.ManagedLabsClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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, - **kwargs: Any - ) -> AsyncIterable["_models.OperationListResult"]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Get all operations. Returns a list of all operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - template_url=self.list.metadata['url'], + 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) # type: ignore else: - - request = build_list_request( - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -95,7 +104,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -105,8 +116,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.LabServices/operations'} # type: ignore + list.metadata = {"url": "/providers/Microsoft.LabServices/operations"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_patch.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_schedules_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_schedules_operations.py index e62bed319846..5e72d6dc0254 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_schedules_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_schedules_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,102 +6,114 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + 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.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 ..._vendor import _convert_request -from ...operations._schedules_operations import build_create_or_update_request, build_delete_request_initial, build_get_request, build_list_by_lab_request, build_update_request -T = TypeVar('T') +from ...operations._schedules_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_lab_request, + build_update_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class SchedulesOperations: - """SchedulesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class SchedulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.aio.ManagedLabsClient`'s + :attr:`schedules` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_by_lab( - self, - resource_group_name: str, - lab_name: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.PagedSchedules"]: + self, resource_group_name: str, lab_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.Schedule"]: """Get all schedules for a lab. Returns a list of all schedules for a lab. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 PagedSchedules or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.PagedSchedules] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Schedule or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.Schedule] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedSchedules"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedSchedules] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_lab_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, + subscription_id=self._config.subscription_id, filter=filter, - template_url=self.list_by_lab.metadata['url'], + api_version=api_version, + template_url=self.list_by_lab.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) # type: ignore else: - - request = build_list_by_lab_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - lab_name=lab_name, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -114,7 +127,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -124,55 +139,56 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_lab.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules'} # type: ignore + list_by_lab.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules"} # type: ignore @distributed_trace_async - async def get( - self, - resource_group_name: str, - lab_name: str, - schedule_name: str, - **kwargs: Any - ) -> "_models.Schedule": + async def get(self, resource_group_name: str, lab_name: str, schedule_name: str, **kwargs: Any) -> _models.Schedule: """Get a lab Schedule. Returns the properties of a lab Schedule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param schedule_name: The name of the schedule that uniquely identifies it within containing - lab. Used in resource URIs. + lab. Used in resource URIs. Required. :type schedule_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Schedule, or the result of cls(response) + :return: Schedule or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.Schedule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Schedule"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Schedule] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, schedule_name=schedule_name, - template_url=self.get.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -180,15 +196,84 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Schedule', pipeline_response) + deserialized = self._deserialize("Schedule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}"} # type: ignore + + @overload + async def create_or_update( + self, + resource_group_name: str, + lab_name: str, + schedule_name: str, + body: _models.Schedule, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Schedule: + """Create or update a lab schedule. + + Operation to create or update a lab schedule. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param schedule_name: The name of the schedule that uniquely identifies it within containing + lab. Used in resource URIs. Required. + :type schedule_name: str + :param body: The request body. Required. + :type body: ~azure.mgmt.labservices.models.Schedule + :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: Schedule or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Schedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + lab_name: str, + schedule_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Schedule: + """Create or update a lab schedule. + + Operation to create or update a lab schedule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param schedule_name: The name of the schedule that uniquely identifies it within containing + lab. Used in resource URIs. Required. + :type schedule_name: str + :param body: The request body. Required. + :type body: IO + :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: Schedule or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Schedule + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def create_or_update( @@ -196,51 +281,70 @@ async def create_or_update( resource_group_name: str, lab_name: str, schedule_name: str, - body: "_models.Schedule", + body: Union[_models.Schedule, IO], **kwargs: Any - ) -> "_models.Schedule": + ) -> _models.Schedule: """Create or update a lab schedule. Operation to create or update a lab schedule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param schedule_name: The name of the schedule that uniquely identifies it within containing - lab. Used in resource URIs. + lab. Used in resource URIs. Required. :type schedule_name: str - :param body: The request body. - :type body: ~azure.mgmt.labservices.models.Schedule + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.Schedule 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 - :return: Schedule, or the result of cls(response) + :return: Schedule or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.Schedule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Schedule"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Schedule] - _json = self._serialize.body(body, 'Schedule') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "Schedule") request = build_create_or_update_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, schedule_name=schedule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.create_or_update.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -249,18 +353,87 @@ async def create_or_update( raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Schedule', pipeline_response) + deserialized = self._deserialize("Schedule", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Schedule', pipeline_response) + deserialized = self._deserialize("Schedule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}'} # type: ignore + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}"} # type: ignore + @overload + async def update( + self, + resource_group_name: str, + lab_name: str, + schedule_name: str, + body: _models.ScheduleUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Schedule: + """Update a lab schedule. + + Operation to update a lab schedule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param schedule_name: The name of the schedule that uniquely identifies it within containing + lab. Used in resource URIs. Required. + :type schedule_name: str + :param body: The request body. Required. + :type body: ~azure.mgmt.labservices.models.ScheduleUpdate + :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: Schedule or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Schedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + lab_name: str, + schedule_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Schedule: + """Update a lab schedule. + + Operation to update a lab schedule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param schedule_name: The name of the schedule that uniquely identifies it within containing + lab. Used in resource URIs. Required. + :type schedule_name: str + :param body: The request body. Required. + :type body: IO + :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: Schedule or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Schedule + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def update( @@ -268,51 +441,70 @@ async def update( resource_group_name: str, lab_name: str, schedule_name: str, - body: "_models.ScheduleUpdate", + body: Union[_models.ScheduleUpdate, IO], **kwargs: Any - ) -> "_models.Schedule": + ) -> _models.Schedule: """Update a lab schedule. Operation to update a lab schedule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param schedule_name: The name of the schedule that uniquely identifies it within containing - lab. Used in resource URIs. + lab. Used in resource URIs. Required. :type schedule_name: str - :param body: The request body. - :type body: ~azure.mgmt.labservices.models.ScheduleUpdate + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.ScheduleUpdate 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 - :return: Schedule, or the result of cls(response) + :return: Schedule or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.Schedule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Schedule"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(body, 'ScheduleUpdate') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Schedule] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ScheduleUpdate") request = build_update_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, schedule_name=schedule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -320,72 +512,72 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Schedule', pipeline_response) + deserialized = self._deserialize("Schedule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}'} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}"} # type: ignore - async def _delete_initial( - self, - resource_group_name: str, - lab_name: str, - schedule_name: str, - **kwargs: Any + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, schedule_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( resource_group_name=resource_group_name, lab_name=lab_name, schedule_name=schedule_name, - template_url=self._delete_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}"} # type: ignore @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - lab_name: str, - schedule_name: str, - **kwargs: Any + self, resource_group_name: str, lab_name: str, schedule_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a schedule resource. Operation to delete a schedule resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param schedule_name: The name of the schedule that uniquely identifies it within containing - lab. Used in resource URIs. + lab. Used in resource URIs. Required. :type schedule_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. @@ -397,41 +589,48 @@ async def begin_delete( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._delete_initial( + raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, schedule_name=schedule_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_skus_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_skus_operations.py index 6519c6755964..c1044f91dff8 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_skus_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_skus_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,91 +6,95 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import 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 ..._vendor import _convert_request from ...operations._skus_operations import build_list_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class SkusOperations: - """SkusOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class SkusOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.aio.ManagedLabsClient`'s + :attr:`skus` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.PagedLabServicesSkus"]: - """Gets all the Azure Lab Services resource SKUs. + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.LabServicesSku"]: + """Gets the Azure Lab Services resource SKUs. - Returns a list of all the Azure Lab Services resource SKUs. + Returns a list of Azure Lab Services resource SKUs. - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 PagedLabServicesSkus or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.PagedLabServicesSkus] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either LabServicesSku or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.LabServicesSku] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedLabServicesSkus"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedLabServicesSkus] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + 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, filter=filter, - template_url=self.list.metadata['url'], + 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) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -103,7 +108,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -113,8 +120,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/skus'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/skus"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_usages_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_usages_operations.py index 66213024da88..91435141d756 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_usages_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_usages_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,95 +6,100 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import 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 ..._vendor import _convert_request from ...operations._usages_operations import build_list_by_location_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class UsagesOperations: - """UsagesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class UsagesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.aio.ManagedLabsClient`'s + :attr:`usages` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_by_location( - self, - location: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.ListUsagesResult"]: + self, location: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.Usage"]: """Gets the list of usages. Returns list of usage per SKU family for the specified subscription in the specified region. - :param location: The location name. + :param location: The location name. Required. :type location: str - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 ListUsagesResult or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.ListUsagesResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Usage or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.Usage] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ListUsagesResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ListUsagesResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_location_request( - subscription_id=self._config.subscription_id, location=location, + subscription_id=self._config.subscription_id, filter=filter, - template_url=self.list_by_location.metadata['url'], + api_version=api_version, + template_url=self.list_by_location.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) # type: ignore else: - - request = build_list_by_location_request( - subscription_id=self._config.subscription_id, - location=location, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -107,7 +113,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -117,8 +125,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_location.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/locations/{location}/usages'} # type: ignore + list_by_location.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/locations/{location}/usages"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_users_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_users_operations.py index 9972040966d4..7655ea96d409 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_users_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_users_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,102 +6,115 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + 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.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 ..._vendor import _convert_request -from ...operations._users_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_invite_request_initial, build_list_by_lab_request, build_update_request_initial -T = TypeVar('T') +from ...operations._users_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_invite_request, + build_list_by_lab_request, + build_update_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class UsersOperations: - """UsersOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class UsersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.aio.ManagedLabsClient`'s + :attr:`users` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_by_lab( - self, - resource_group_name: str, - lab_name: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.PagedUsers"]: + self, resource_group_name: str, lab_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.User"]: """Get all users for a lab. Returns a list of all users for a lab. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 PagedUsers or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.PagedUsers] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either User or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.User] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedUsers"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedUsers] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_lab_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, + subscription_id=self._config.subscription_id, filter=filter, - template_url=self.list_by_lab.metadata['url'], + api_version=api_version, + template_url=self.list_by_lab.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) # type: ignore else: - - request = build_list_by_lab_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - lab_name=lab_name, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -114,7 +128,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -124,55 +140,56 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_lab.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users'} # type: ignore + list_by_lab.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users"} # type: ignore @distributed_trace_async - async def get( - self, - resource_group_name: str, - lab_name: str, - user_name: str, - **kwargs: Any - ) -> "_models.User": + async def get(self, resource_group_name: str, lab_name: str, user_name: str, **kwargs: Any) -> _models.User: """Get a lab user. Returns the properties of a lab user. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param user_name: The name of the user that uniquely identifies it within containing lab. Used - in resource URIs. + in resource URIs. Required. :type user_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: User, or the result of cls(response) + :return: User or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.User - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.User"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.User] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, - template_url=self.get.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -180,93 +197,108 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}"} # type: ignore async def _create_or_update_initial( - self, - resource_group_name: str, - lab_name: str, - user_name: str, - body: "_models.User", - **kwargs: Any - ) -> "_models.User": - cls = kwargs.pop('cls', None) # type: ClsType["_models.User"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(body, 'User') + self, resource_group_name: str, lab_name: str, user_name: str, body: Union[_models.User, IO], **kwargs: Any + ) -> _models.User: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.User] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "User") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}'} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}"} # type: ignore - - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, lab_name: str, user_name: str, - body: "_models.User", + body: _models.User, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.User"]: + ) -> AsyncLROPoller[_models.User]: """Create or update a lab user. Operation to create or update a lab user. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param user_name: The name of the user that uniquely identifies it within containing lab. Used - in resource URIs. + in resource URIs. Required. :type user_name: str - :param body: The request body. + :param body: The request body. Required. :type body: ~azure.mgmt.labservices.models.User + :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 @@ -277,101 +309,284 @@ async def begin_create_or_update( Retry-After header is present. :return: An instance of AsyncLROPoller that returns either User or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.User] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.User"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + lab_name: str, + user_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.User]: + """Create or update a lab user. + + Operation to create or update a lab user. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param user_name: The name of the user that uniquely identifies it within containing lab. Used + in resource URIs. Required. + :type user_name: str + :param body: The request body. Required. + :type body: IO + :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 User or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.User] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, resource_group_name: str, lab_name: str, user_name: str, body: Union[_models.User, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.User]: + """Create or update a lab user. + + Operation to create or update a lab user. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param user_name: The name of the user that uniquely identifies it within containing lab. Used + in resource URIs. Required. + :type user_name: str + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.User 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. + :return: An instance of AsyncLROPoller that returns either User or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.User] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.User] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._create_or_update_initial( + raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'original-uri'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncARMPolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs), + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}"} # type: ignore async def _update_initial( self, resource_group_name: str, lab_name: str, user_name: str, - body: "_models.UserUpdate", + body: Union[_models.UserUpdate, IO], **kwargs: Any - ) -> "_models.User": - cls = kwargs.pop('cls', None) # type: ClsType["_models.User"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(body, 'UserUpdate') + ) -> _models.User: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.User] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "UserUpdate") - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_update_request( resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}'} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}"} # type: ignore + + @overload + async def begin_update( + self, + resource_group_name: str, + lab_name: str, + user_name: str, + body: _models.UserUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.User]: + """Update a lab user. + + Operation to update a lab user. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param user_name: The name of the user that uniquely identifies it within containing lab. Used + in resource URIs. Required. + :type user_name: str + :param body: The request body. Required. + :type body: ~azure.mgmt.labservices.models.UserUpdate + :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 User or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.User] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + lab_name: str, + user_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.User]: + """Update a lab user. + + Operation to update a lab user. + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param user_name: The name of the user that uniquely identifies it within containing lab. Used + in resource URIs. Required. + :type user_name: str + :param body: The request body. Required. + :type body: IO + :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 User or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.User] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_update( @@ -379,23 +594,27 @@ async def begin_update( resource_group_name: str, lab_name: str, user_name: str, - body: "_models.UserUpdate", + body: Union[_models.UserUpdate, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.User"]: + ) -> AsyncLROPoller[_models.User]: """Update a lab user. Operation to update a lab user. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param user_name: The name of the user that uniquely identifies it within containing lab. Used - in resource URIs. + in resource URIs. Required. :type user_name: str - :param body: The request body. - :type body: ~azure.mgmt.labservices.models.UserUpdate + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.UserUpdate 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 @@ -406,107 +625,114 @@ async def begin_update( Retry-After header is present. :return: An instance of AsyncLROPoller that returns either User or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.labservices.models.User] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.User"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.User] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._update_initial( + raw_result = await self._update_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}'} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}"} # type: ignore - async def _delete_initial( - self, - resource_group_name: str, - lab_name: str, - user_name: str, - **kwargs: Any + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, user_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, - template_url=self._delete_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}"} # type: ignore @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - lab_name: str, - user_name: str, - **kwargs: Any + self, resource_group_name: str, lab_name: str, user_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a user resource. Operation to delete a user resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param user_name: The name of the user that uniquely identifies it within containing lab. Used - in resource URIs. + in resource URIs. Required. :type user_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. @@ -518,87 +744,193 @@ async def begin_delete( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._delete_initial( + raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}"} # type: ignore - async def _invite_initial( + async def _invite_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, lab_name: str, user_name: str, - body: "_models.InviteBody", + body: Union[_models.InviteBody, IO], **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(body, 'InviteBody') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] - request = build_invite_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "InviteBody") + + request = build_invite_request( resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._invite_initial.metadata['url'], + content=_content, + template_url=self._invite_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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _invite_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}/invite'} # type: ignore + _invite_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}/invite"} # type: ignore + @overload + async def begin_invite( + self, + resource_group_name: str, + lab_name: str, + user_name: str, + body: _models.InviteBody, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Invite a user to a lab. + + Operation to invite a user to a lab. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param user_name: The name of the user that uniquely identifies it within containing lab. Used + in resource URIs. Required. + :type user_name: str + :param body: The request body. Required. + :type body: ~azure.mgmt.labservices.models.InviteBody + :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 None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_invite( + self, + resource_group_name: str, + lab_name: str, + user_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Invite a user to a lab. + + Operation to invite a user to a lab. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param user_name: The name of the user that uniquely identifies it within containing lab. Used + in resource URIs. Required. + :type user_name: str + :param body: The request body. Required. + :type body: IO + :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 None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_invite( @@ -606,7 +938,7 @@ async def begin_invite( resource_group_name: str, lab_name: str, user_name: str, - body: "_models.InviteBody", + body: Union[_models.InviteBody, IO], **kwargs: Any ) -> AsyncLROPoller[None]: """Invite a user to a lab. @@ -614,15 +946,19 @@ async def begin_invite( Operation to invite a user to a lab. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param user_name: The name of the user that uniquely identifies it within containing lab. Used - in resource URIs. + in resource URIs. Required. :type user_name: str - :param body: The request body. - :type body: ~azure.mgmt.labservices.models.InviteBody + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.InviteBody 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 @@ -633,44 +969,51 @@ async def begin_invite( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._invite_initial( + raw_result = await self._invite_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_invite.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}/invite'} # type: ignore + begin_invite.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}/invite"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_virtual_machines_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_virtual_machines_operations.py index afdad027d2fd..e662a6472ba5 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_virtual_machines_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/aio/operations/_virtual_machines_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,104 +6,116 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from urllib.parse import parse_qs, urljoin, urlparse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + 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.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 ..._vendor import _convert_request -from ...operations._virtual_machines_operations import build_get_request, build_list_by_lab_request, build_redeploy_request_initial, build_reimage_request_initial, build_reset_password_request_initial, build_start_request_initial, build_stop_request_initial -T = TypeVar('T') +from ...operations._virtual_machines_operations import ( + build_get_request, + build_list_by_lab_request, + build_redeploy_request, + build_reimage_request, + build_reset_password_request, + build_start_request, + build_stop_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class VirtualMachinesOperations: - """VirtualMachinesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class VirtualMachinesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.aio.ManagedLabsClient`'s + :attr:`virtual_machines` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_by_lab( - self, - resource_group_name: str, - lab_name: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.PagedVirtualMachines"]: + self, resource_group_name: str, lab_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.VirtualMachine"]: """Get all virtual machines for a lab. Returns a list of all virtual machines for a lab. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 PagedVirtualMachines or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.PagedVirtualMachines] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either VirtualMachine or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.labservices.models.VirtualMachine] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedVirtualMachines"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedVirtualMachines] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_lab_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, + subscription_id=self._config.subscription_id, filter=filter, - template_url=self.list_by_lab.metadata['url'], + api_version=api_version, + template_url=self.list_by_lab.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) # type: ignore else: - - request = build_list_by_lab_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - lab_name=lab_name, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -116,7 +129,9 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -126,55 +141,58 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_lab.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines'} # type: ignore + list_by_lab.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines"} # type: ignore @distributed_trace_async async def get( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any - ) -> "_models.VirtualMachine": + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any + ) -> _models.VirtualMachine: """Get a lab virtual machine. Returns the properties for a lab virtual machine. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within - the containing lab. Used in resource URIs. + the containing lab. Used in resource URIs. Required. :type virtual_machine_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: VirtualMachine, or the result of cls(response) + :return: VirtualMachine or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.VirtualMachine - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualMachine"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.VirtualMachine] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - template_url=self.get.metadata['url'], + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -182,72 +200,72 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('VirtualMachine', pipeline_response) + deserialized = self._deserialize("VirtualMachine", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}"} # type: ignore - - async def _start_initial( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + async def _start_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_start_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_start_request( resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - template_url=self._start_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._start_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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _start_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/start'} # type: ignore - + _start_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/start"} # type: ignore @distributed_trace_async async def begin_start( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Start a lab virtual machine. Action to start a lab virtual machine. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within - the containing lab. Used in resource URIs. + the containing lab. Used in resource URIs. Required. :type virtual_machine_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. @@ -259,101 +277,109 @@ async def begin_start( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._start_initial( + raw_result = await self._start_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_start.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/start'} # type: ignore + begin_start.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/start"} # type: ignore - async def _stop_initial( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + async def _stop_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_stop_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - template_url=self._stop_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._stop_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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _stop_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/stop'} # type: ignore - + _stop_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/stop"} # type: ignore @distributed_trace_async async def begin_stop( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Stop a lab virtual machine. Action to stop a lab virtual machine. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within - the containing lab. Used in resource URIs. + the containing lab. Used in resource URIs. Required. :type virtual_machine_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. @@ -365,89 +391,96 @@ async def begin_stop( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._stop_initial( + raw_result = await self._stop_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_stop.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/stop'} # type: ignore + begin_stop.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/stop"} # type: ignore - async def _reimage_initial( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + async def _reimage_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_reimage_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_reimage_request( resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - template_url=self._reimage_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._reimage_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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _reimage_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/reimage'} # type: ignore - + _reimage_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/reimage"} # type: ignore @distributed_trace_async async def begin_reimage( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Re-image a lab virtual machine. @@ -455,12 +488,13 @@ async def begin_reimage( latest published snapshot of the reference environment of the lab. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within - the containing lab. Used in resource URIs. + the containing lab. Used in resource URIs. Required. :type virtual_machine_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. @@ -472,89 +506,96 @@ async def begin_reimage( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._reimage_initial( + raw_result = await self._reimage_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_reimage.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/reimage'} # type: ignore + begin_reimage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/reimage"} # type: ignore - async def _redeploy_initial( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + async def _redeploy_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_redeploy_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_redeploy_request( resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - template_url=self._redeploy_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._redeploy_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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _redeploy_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/redeploy'} # type: ignore - + _redeploy_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/redeploy"} # type: ignore @distributed_trace_async async def begin_redeploy( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Redeploy a lab virtual machine to a different compute node. For troubleshooting connectivity. @@ -562,12 +603,13 @@ async def begin_redeploy( connectivity. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within - the containing lab. Used in resource URIs. + the containing lab. Used in resource URIs. Required. :type virtual_machine_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. @@ -579,87 +621,193 @@ async def begin_redeploy( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._redeploy_initial( + raw_result = await self._redeploy_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_redeploy.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/redeploy'} # type: ignore + begin_redeploy.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/redeploy"} # type: ignore - async def _reset_password_initial( + async def _reset_password_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, lab_name: str, virtual_machine_name: str, - body: "_models.ResetPasswordBody", + body: Union[_models.ResetPasswordBody, IO], **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(body, 'ResetPasswordBody') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] - request = build_reset_password_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ResetPasswordBody") + + request = build_reset_password_request( resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._reset_password_initial.metadata['url'], + content=_content, + template_url=self._reset_password_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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _reset_password_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/resetPassword'} # type: ignore + _reset_password_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/resetPassword"} # type: ignore + @overload + async def begin_reset_password( + self, + resource_group_name: str, + lab_name: str, + virtual_machine_name: str, + body: _models.ResetPasswordBody, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Reset a lab virtual machine password. + + Resets a lab virtual machine password. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within + the containing lab. Used in resource URIs. Required. + :type virtual_machine_name: str + :param body: The request body. Required. + :type body: ~azure.mgmt.labservices.models.ResetPasswordBody + :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 None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_reset_password( + self, + resource_group_name: str, + lab_name: str, + virtual_machine_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Reset a lab virtual machine password. + + Resets a lab virtual machine password. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within + the containing lab. Used in resource URIs. Required. + :type virtual_machine_name: str + :param body: The request body. Required. + :type body: IO + :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 None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_reset_password( @@ -667,7 +815,7 @@ async def begin_reset_password( resource_group_name: str, lab_name: str, virtual_machine_name: str, - body: "_models.ResetPasswordBody", + body: Union[_models.ResetPasswordBody, IO], **kwargs: Any ) -> AsyncLROPoller[None]: """Reset a lab virtual machine password. @@ -675,15 +823,19 @@ async def begin_reset_password( Resets a lab virtual machine password. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within - the containing lab. Used in resource URIs. + the containing lab. Used in resource URIs. Required. :type virtual_machine_name: str - :param body: The request body. - :type body: ~azure.mgmt.labservices.models.ResetPasswordBody + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.ResetPasswordBody 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 @@ -694,44 +846,51 @@ async def begin_reset_password( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._reset_password_initial( + raw_result = await self._reset_password_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_reset_password.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/resetPassword'} # type: ignore + begin_reset_password.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/resetPassword"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/__init__.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/__init__.py index 701e6f0b7671..7771407aacb5 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/__init__.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/__init__.py @@ -12,6 +12,7 @@ from ._models_py3 import ErrorAdditionalInfo from ._models_py3 import ErrorDetail from ._models_py3 import ErrorResponse +from ._models_py3 import Identity from ._models_py3 import Image from ._models_py3 import ImageProperties from ._models_py3 import ImageReference @@ -72,122 +73,125 @@ from ._models_py3 import VirtualMachineConnectionProfile from ._models_py3 import VirtualMachineProfile - -from ._lab_services_client_enums import ( - ActionType, - ConnectionType, - CreateOption, - CreatedByType, - EnableState, - InvitationState, - LabServicesSkuTier, - LabState, - OperationStatus, - Origin, - OsState, - OsType, - ProvisioningState, - RecurrenceFrequency, - RegistrationState, - RestrictionReasonCode, - RestrictionType, - ScaleType, - ShutdownOnIdleMode, - SkuTier, - UsageUnit, - VirtualMachineState, - VirtualMachineType, - WeekDay, -) +from ._managed_labs_client_enums import ActionType +from ._managed_labs_client_enums import ConnectionType +from ._managed_labs_client_enums import CreateOption +from ._managed_labs_client_enums import CreatedByType +from ._managed_labs_client_enums import EnableState +from ._managed_labs_client_enums import InvitationState +from ._managed_labs_client_enums import LabServicesSkuTier +from ._managed_labs_client_enums import LabState +from ._managed_labs_client_enums import OperationStatus +from ._managed_labs_client_enums import Origin +from ._managed_labs_client_enums import OsState +from ._managed_labs_client_enums import OsType +from ._managed_labs_client_enums import ProvisioningState +from ._managed_labs_client_enums import RecurrenceFrequency +from ._managed_labs_client_enums import RegistrationState +from ._managed_labs_client_enums import RestrictionReasonCode +from ._managed_labs_client_enums import RestrictionType +from ._managed_labs_client_enums import ScaleType +from ._managed_labs_client_enums import ShutdownOnIdleMode +from ._managed_labs_client_enums import SkuTier +from ._managed_labs_client_enums import UsageUnit +from ._managed_labs_client_enums import VirtualMachineState +from ._managed_labs_client_enums import VirtualMachineType +from ._managed_labs_client_enums import WeekDay +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'AutoShutdownProfile', - 'ConnectionProfile', - 'Credentials', - 'ErrorAdditionalInfo', - 'ErrorDetail', - 'ErrorResponse', - 'Image', - 'ImageProperties', - 'ImageReference', - 'ImageUpdate', - 'ImageUpdateProperties', - 'InviteBody', - 'Lab', - 'LabNetworkProfile', - 'LabPlan', - 'LabPlanNetworkProfile', - 'LabPlanProperties', - 'LabPlanUpdate', - 'LabPlanUpdateProperties', - 'LabProperties', - 'LabServicesSku', - 'LabServicesSkuCapabilities', - 'LabServicesSkuCapacity', - 'LabServicesSkuCost', - 'LabServicesSkuRestrictions', - 'LabUpdate', - 'LabUpdateProperties', - 'ListUsagesResult', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'OperationResult', - 'PagedImages', - 'PagedLabPlans', - 'PagedLabServicesSkus', - 'PagedLabs', - 'PagedSchedules', - 'PagedUsers', - 'PagedVirtualMachines', - 'ProxyResource', - 'RecurrencePattern', - 'ResetPasswordBody', - 'Resource', - 'RosterProfile', - 'SaveImageBody', - 'Schedule', - 'ScheduleProperties', - 'ScheduleUpdate', - 'ScheduleUpdateProperties', - 'SecurityProfile', - 'Sku', - 'SupportInfo', - 'SystemData', - 'TrackedResource', - 'TrackedResourceUpdate', - 'Usage', - 'UsageName', - 'User', - 'UserProperties', - 'UserUpdate', - 'UserUpdateProperties', - 'VirtualMachine', - 'VirtualMachineAdditionalCapabilities', - 'VirtualMachineConnectionProfile', - 'VirtualMachineProfile', - 'ActionType', - 'ConnectionType', - 'CreateOption', - 'CreatedByType', - 'EnableState', - 'InvitationState', - 'LabServicesSkuTier', - 'LabState', - 'OperationStatus', - 'Origin', - 'OsState', - 'OsType', - 'ProvisioningState', - 'RecurrenceFrequency', - 'RegistrationState', - 'RestrictionReasonCode', - 'RestrictionType', - 'ScaleType', - 'ShutdownOnIdleMode', - 'SkuTier', - 'UsageUnit', - 'VirtualMachineState', - 'VirtualMachineType', - 'WeekDay', + "AutoShutdownProfile", + "ConnectionProfile", + "Credentials", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "Identity", + "Image", + "ImageProperties", + "ImageReference", + "ImageUpdate", + "ImageUpdateProperties", + "InviteBody", + "Lab", + "LabNetworkProfile", + "LabPlan", + "LabPlanNetworkProfile", + "LabPlanProperties", + "LabPlanUpdate", + "LabPlanUpdateProperties", + "LabProperties", + "LabServicesSku", + "LabServicesSkuCapabilities", + "LabServicesSkuCapacity", + "LabServicesSkuCost", + "LabServicesSkuRestrictions", + "LabUpdate", + "LabUpdateProperties", + "ListUsagesResult", + "Operation", + "OperationDisplay", + "OperationListResult", + "OperationResult", + "PagedImages", + "PagedLabPlans", + "PagedLabServicesSkus", + "PagedLabs", + "PagedSchedules", + "PagedUsers", + "PagedVirtualMachines", + "ProxyResource", + "RecurrencePattern", + "ResetPasswordBody", + "Resource", + "RosterProfile", + "SaveImageBody", + "Schedule", + "ScheduleProperties", + "ScheduleUpdate", + "ScheduleUpdateProperties", + "SecurityProfile", + "Sku", + "SupportInfo", + "SystemData", + "TrackedResource", + "TrackedResourceUpdate", + "Usage", + "UsageName", + "User", + "UserProperties", + "UserUpdate", + "UserUpdateProperties", + "VirtualMachine", + "VirtualMachineAdditionalCapabilities", + "VirtualMachineConnectionProfile", + "VirtualMachineProfile", + "ActionType", + "ConnectionType", + "CreateOption", + "CreatedByType", + "EnableState", + "InvitationState", + "LabServicesSkuTier", + "LabState", + "OperationStatus", + "Origin", + "OsState", + "OsType", + "ProvisioningState", + "RecurrenceFrequency", + "RegistrationState", + "RestrictionReasonCode", + "RestrictionType", + "ScaleType", + "ShutdownOnIdleMode", + "SkuTier", + "UsageUnit", + "VirtualMachineState", + "VirtualMachineType", + "WeekDay", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_lab_services_client_enums.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_lab_services_client_enums.py index 7353dc17965d..6ba7ef2143d1 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_lab_services_client_enums.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_lab_services_client_enums.py @@ -12,31 +12,30 @@ class ActionType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. - """ + """Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs.""" INTERNAL = "Internal" + class ConnectionType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """A connection type for access labs and VMs (Public, Private or None). - """ + """A connection type for access labs and VMs (Public, Private or None).""" PUBLIC = "Public" PRIVATE = "Private" NONE = "None" + class CreatedByType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of identity that created the resource. - """ + """The type of identity that created the resource.""" USER = "User" APPLICATION = "Application" MANAGED_IDENTITY = "ManagedIdentity" KEY = "Key" + class CreateOption(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Indicates what lab virtual machines are created from. - """ + """Indicates what lab virtual machines are created from.""" #: An image is used to create all lab user virtual machines. When this option is set, no template #: VM will be created. @@ -44,16 +43,16 @@ class CreateOption(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: A template VM will be used to create all lab user virtual machines. TEMPLATE_VM = "TemplateVM" + class EnableState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Property enabled state. - """ + """Property enabled state.""" ENABLED = "Enabled" DISABLED = "Disabled" + class InvitationState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The lab user invitation state. - """ + """The lab user invitation state.""" #: The invitation has not been sent. NOT_SENT = "NotSent" @@ -64,16 +63,16 @@ class InvitationState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: There was an error while sending the invitation. FAILED = "Failed" + class LabServicesSkuTier(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The tier of the SKU. - """ + """The tier of the SKU.""" STANDARD = "Standard" PREMIUM = "Premium" + class LabState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The state of a virtual machine. - """ + """The state of a virtual machine.""" #: The lab is currently in draft (has not been published). DRAFT = "Draft" @@ -86,9 +85,9 @@ class LabState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: The lab has been published. PUBLISHED = "Published" + class OperationStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The operation status - """ + """The operation status""" #: The operation has been accepted but hasn't started. NOT_STARTED = "NotStarted" @@ -101,6 +100,7 @@ class OperationStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: Not supported yet. CANCELED = "Canceled" + class Origin(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): """The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is "user,system" @@ -110,25 +110,25 @@ class Origin(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): SYSTEM = "system" USER_SYSTEM = "user,system" + class OsState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The operating system state. - """ + """The operating system state.""" #: Image does not contain any machine and user specific information. GENERALIZED = "Generalized" #: Image contains machine and user specific information. SPECIALIZED = "Specialized" + class OsType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The operating system type. - """ + """The operating system type.""" WINDOWS = "Windows" LINUX = "Linux" + class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Resource provisioning state. - """ + """Resource provisioning state.""" #: Resource is in the process of being created. CREATING = "Creating" @@ -145,40 +145,40 @@ class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: finished. LOCKED = "Locked" + class RecurrenceFrequency(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Schedule recurrence frequencies. - """ + """Schedule recurrence frequencies.""" #: Schedule will run every days. DAILY = "Daily" #: Schedule will run every week on days specified in weekDays. WEEKLY = "Weekly" + class RegistrationState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The user lab registration state. - """ + """The user lab registration state.""" #: User has not yet registered with the lab. REGISTERED = "Registered" #: User has registered with the lab. NOT_REGISTERED = "NotRegistered" + class RestrictionReasonCode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The reason for the restriction. - """ + """The reason for the restriction.""" QUOTA_ID = "QuotaId" NOT_AVAILABLE_FOR_SUBSCRIPTION = "NotAvailableForSubscription" + class RestrictionType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of restriction. - """ + """The type of restriction.""" LOCATION = "Location" + class ScaleType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The localized name of the resource. - """ + """The localized name of the resource.""" #: The capacity is not adjustable in any way. NONE = "None" @@ -187,9 +187,9 @@ class ScaleType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: The user is permitted to scale this SKU in and out. AUTOMATIC = "Automatic" + class ShutdownOnIdleMode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Defines whether to shut down VM on idle and the criteria for idle detection. - """ + """Defines whether to shut down VM on idle and the criteria for idle detection.""" #: The VM won't be shut down when it is idle. NONE = "None" @@ -199,6 +199,7 @@ class ShutdownOnIdleMode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: consumption is low. LOW_USAGE = "LowUsage" + class SkuTier(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): """This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. @@ -209,15 +210,15 @@ class SkuTier(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): STANDARD = "Standard" PREMIUM = "Premium" + class UsageUnit(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The unit details. - """ + """The unit details.""" COUNT = "Count" + class VirtualMachineState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The state of a virtual machine. - """ + """The state of a virtual machine.""" #: The VM is currently stopped. STOPPED = "Stopped" @@ -234,18 +235,18 @@ class VirtualMachineState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): #: The VM is being redeployed. REDEPLOYING = "Redeploying" + class VirtualMachineType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of the lab virtual machine. - """ + """The type of the lab virtual machine.""" #: A user VM. USER = "User" #: A template VM. TEMPLATE = "Template" + class WeekDay(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Days of the week. - """ + """Days of the week.""" #: Schedule will run on Sunday. SUNDAY = "Sunday" diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_managed_labs_client_enums.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_managed_labs_client_enums.py new file mode 100644 index 000000000000..f99cec9f961d --- /dev/null +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_managed_labs_client_enums.py @@ -0,0 +1,263 @@ +# 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 enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs.""" + + INTERNAL = "Internal" + + +class ConnectionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """A connection type for access labs and VMs (Public, Private or None).""" + + PUBLIC = "Public" + PRIVATE = "Private" + NONE = "None" + + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + + +class CreateOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates what lab virtual machines are created from.""" + + #: An image is used to create all lab user virtual machines. When this option is set, no template + #: VM will be created. + IMAGE = "Image" + #: A template VM will be used to create all lab user virtual machines. + TEMPLATE_VM = "TemplateVM" + + +class EnableState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Property enabled state.""" + + ENABLED = "Enabled" + DISABLED = "Disabled" + + +class InvitationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The lab user invitation state.""" + + #: The invitation has not been sent. + NOT_SENT = "NotSent" + #: Currently sending the invitation. + SENDING = "Sending" + #: The invitation has been successfully sent. + SENT = "Sent" + #: There was an error while sending the invitation. + FAILED = "Failed" + + +class LabServicesSkuTier(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The tier of the SKU.""" + + STANDARD = "Standard" + PREMIUM = "Premium" + + +class LabState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The state of a virtual machine.""" + + #: The lab is currently in draft (has not been published). + DRAFT = "Draft" + #: The lab is publishing. + PUBLISHING = "Publishing" + #: The lab is scaling. + SCALING = "Scaling" + #: The lab is syncing users. + SYNCING = "Syncing" + #: The lab has been published. + PUBLISHED = "Published" + + +class OperationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The operation status.""" + + #: The operation has been accepted but hasn't started. + NOT_STARTED = "NotStarted" + #: The operation is running + IN_PROGRESS = "InProgress" + #: The operation Succeeded + SUCCEEDED = "Succeeded" + #: The operation failed + FAILED = "Failed" + #: Not supported yet + CANCELED = "Canceled" + + +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". + """ + + USER = "user" + SYSTEM = "system" + USER_SYSTEM = "user,system" + + +class OsState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The operating system state.""" + + #: Image does not contain any machine and user specific information. + GENERALIZED = "Generalized" + #: Image contains machine and user specific information. + SPECIALIZED = "Specialized" + + +class OsType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The operating system type.""" + + WINDOWS = "Windows" + LINUX = "Linux" + + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Resource provisioning state.""" + + #: Resource is in the process of being created. + CREATING = "Creating" + #: New property values are being applied to the resource. + UPDATING = "Updating" + #: Resource is in the process of being deleted. + DELETING = "Deleting" + #: Resource is in healthy state after creation or update operation. + SUCCEEDED = "Succeeded" + #: Previous operation on the resource has failed leaving resource in unhealthy state. + FAILED = "Failed" + #: The resource is locked and changes are currently blocked. This could be due to maintenance or a + #: scheduled operation. The state will go back to succeeded once the locking operation has + #: finished. + LOCKED = "Locked" + + +class RecurrenceFrequency(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Schedule recurrence frequencies.""" + + #: Schedule will run every days. + DAILY = "Daily" + #: Schedule will run every week on days specified in weekDays. + WEEKLY = "Weekly" + + +class RegistrationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The user lab registration state.""" + + #: User has not yet registered with the lab. + REGISTERED = "Registered" + #: User has registered with the lab. + NOT_REGISTERED = "NotRegistered" + + +class RestrictionReasonCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The reason for the restriction.""" + + QUOTA_ID = "QuotaId" + NOT_AVAILABLE_FOR_SUBSCRIPTION = "NotAvailableForSubscription" + + +class RestrictionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of restriction.""" + + LOCATION = "Location" + + +class ScaleType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The localized name of the resource.""" + + #: The capacity is not adjustable in any way. + NONE = "None" + #: The user must manually scale this SKU in and out. + MANUAL = "Manual" + #: The user is permitted to scale this SKU in and out. + AUTOMATIC = "Automatic" + + +class ShutdownOnIdleMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Defines whether to shut down VM on idle and the criteria for idle detection.""" + + #: The VM won't be shut down when it is idle. + NONE = "None" + #: The VM will be considered as idle when there is no keyboard or mouse input. + USER_ABSENCE = "UserAbsence" + #: The VM will be considered as idle when user is absent and the resource (CPU and disk) + #: consumption is low. + LOW_USAGE = "LowUsage" + + +class SkuTier(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This field is required to be implemented by the Resource Provider if the service has more than + one tier, but is not required on a PUT. + """ + + FREE = "Free" + BASIC = "Basic" + STANDARD = "Standard" + PREMIUM = "Premium" + + +class UsageUnit(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The unit details.""" + + COUNT = "Count" + + +class VirtualMachineState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The state of a virtual machine.""" + + #: The VM is currently stopped. + STOPPED = "Stopped" + #: The VM is starting. + STARTING = "Starting" + #: The VM is running. + RUNNING = "Running" + #: The VM is stopping. + STOPPING = "Stopping" + #: The VM password is being reset. + RESETTING_PASSWORD = "ResettingPassword" + #: The VM is being reimaged. + REIMAGING = "Reimaging" + #: The VM is being redeployed. + REDEPLOYING = "Redeploying" + + +class VirtualMachineType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the lab virtual machine.""" + + #: A user VM + USER = "User" + #: A template VM + TEMPLATE = "Template" + + +class WeekDay(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Days of the week.""" + + #: Schedule will run on Sunday + SUNDAY = "Sunday" + #: Schedule will run on Monday + MONDAY = "Monday" + #: Schedule will run on Tuesday + TUESDAY = "Tuesday" + #: Schedule will run on Wednesday + WEDNESDAY = "Wednesday" + #: Schedule will run on Thursday + THURSDAY = "Thursday" + #: Schedule will run on Friday + FRIDAY = "Friday" + #: Schedule will run on Saturday + SATURDAY = "Saturday" diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_models_py3.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_models_py3.py index 8a324fcc3708..083b7e13ff1f 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_models_py3.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -7,25 +8,26 @@ # -------------------------------------------------------------------------- import datetime -from typing import Dict, List, Optional, Union +from typing import Dict, List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from .. import _serialization -from ._lab_services_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class AutoShutdownProfile(msrest.serialization.Model): +class AutoShutdownProfile(_serialization.Model): """Profile for how to handle shutting down virtual machines. - :ivar shutdown_on_disconnect: Whether shutdown on disconnect is enabled. Possible values - include: "Enabled", "Disabled". + :ivar shutdown_on_disconnect: Whether shutdown on disconnect is enabled. Known values are: + "Enabled" and "Disabled". :vartype shutdown_on_disconnect: str or ~azure.mgmt.labservices.models.EnableState :ivar shutdown_when_not_connected: Whether a VM will get shutdown when it hasn't been connected - to after a period of time. Possible values include: "Enabled", "Disabled". + to after a period of time. Known values are: "Enabled" and "Disabled". :vartype shutdown_when_not_connected: str or ~azure.mgmt.labservices.models.EnableState :ivar shutdown_on_idle: Whether a VM will get shutdown when it has idled for a period of time. - Possible values include: "None", "UserAbsence", "LowUsage". + Known values are: "None", "UserAbsence", and "LowUsage". :vartype shutdown_on_idle: str or ~azure.mgmt.labservices.models.ShutdownOnIdleMode :ivar disconnect_delay: The amount of time a VM will stay running after a user disconnects if this behavior is enabled. @@ -39,34 +41,34 @@ class AutoShutdownProfile(msrest.serialization.Model): """ _attribute_map = { - 'shutdown_on_disconnect': {'key': 'shutdownOnDisconnect', 'type': 'str'}, - 'shutdown_when_not_connected': {'key': 'shutdownWhenNotConnected', 'type': 'str'}, - 'shutdown_on_idle': {'key': 'shutdownOnIdle', 'type': 'str'}, - 'disconnect_delay': {'key': 'disconnectDelay', 'type': 'duration'}, - 'no_connect_delay': {'key': 'noConnectDelay', 'type': 'duration'}, - 'idle_delay': {'key': 'idleDelay', 'type': 'duration'}, + "shutdown_on_disconnect": {"key": "shutdownOnDisconnect", "type": "str"}, + "shutdown_when_not_connected": {"key": "shutdownWhenNotConnected", "type": "str"}, + "shutdown_on_idle": {"key": "shutdownOnIdle", "type": "str"}, + "disconnect_delay": {"key": "disconnectDelay", "type": "duration"}, + "no_connect_delay": {"key": "noConnectDelay", "type": "duration"}, + "idle_delay": {"key": "idleDelay", "type": "duration"}, } def __init__( self, *, - shutdown_on_disconnect: Optional[Union[str, "EnableState"]] = None, - shutdown_when_not_connected: Optional[Union[str, "EnableState"]] = None, - shutdown_on_idle: Optional[Union[str, "ShutdownOnIdleMode"]] = None, + shutdown_on_disconnect: Optional[Union[str, "_models.EnableState"]] = None, + shutdown_when_not_connected: Optional[Union[str, "_models.EnableState"]] = None, + shutdown_on_idle: Optional[Union[str, "_models.ShutdownOnIdleMode"]] = None, disconnect_delay: Optional[datetime.timedelta] = None, no_connect_delay: Optional[datetime.timedelta] = None, idle_delay: Optional[datetime.timedelta] = None, **kwargs ): """ - :keyword shutdown_on_disconnect: Whether shutdown on disconnect is enabled. Possible values - include: "Enabled", "Disabled". + :keyword shutdown_on_disconnect: Whether shutdown on disconnect is enabled. Known values are: + "Enabled" and "Disabled". :paramtype shutdown_on_disconnect: str or ~azure.mgmt.labservices.models.EnableState :keyword shutdown_when_not_connected: Whether a VM will get shutdown when it hasn't been - connected to after a period of time. Possible values include: "Enabled", "Disabled". + connected to after a period of time. Known values are: "Enabled" and "Disabled". :paramtype shutdown_when_not_connected: str or ~azure.mgmt.labservices.models.EnableState :keyword shutdown_on_idle: Whether a VM will get shutdown when it has idled for a period of - time. Possible values include: "None", "UserAbsence", "LowUsage". + time. Known values are: "None", "UserAbsence", and "LowUsage". :paramtype shutdown_on_idle: str or ~azure.mgmt.labservices.models.ShutdownOnIdleMode :keyword disconnect_delay: The amount of time a VM will stay running after a user disconnects if this behavior is enabled. @@ -78,7 +80,7 @@ def __init__( is enabled. :paramtype idle_delay: ~datetime.timedelta """ - super(AutoShutdownProfile, self).__init__(**kwargs) + super().__init__(**kwargs) self.shutdown_on_disconnect = shutdown_on_disconnect self.shutdown_when_not_connected = shutdown_when_not_connected self.shutdown_on_idle = shutdown_on_idle @@ -87,99 +89,93 @@ def __init__( self.idle_delay = idle_delay -class ConnectionProfile(msrest.serialization.Model): +class ConnectionProfile(_serialization.Model): """Connection profile for how users connect to lab virtual machines. - :ivar web_ssh_access: The enabled access level for Web Access over SSH. Possible values - include: "Public", "Private", "None". + :ivar web_ssh_access: The enabled access level for Web Access over SSH. Known values are: + "Public", "Private", and "None". :vartype web_ssh_access: str or ~azure.mgmt.labservices.models.ConnectionType - :ivar web_rdp_access: The enabled access level for Web Access over RDP. Possible values - include: "Public", "Private", "None". + :ivar web_rdp_access: The enabled access level for Web Access over RDP. Known values are: + "Public", "Private", and "None". :vartype web_rdp_access: str or ~azure.mgmt.labservices.models.ConnectionType - :ivar client_ssh_access: The enabled access level for Client Access over SSH. Possible values - include: "Public", "Private", "None". + :ivar client_ssh_access: The enabled access level for Client Access over SSH. Known values are: + "Public", "Private", and "None". :vartype client_ssh_access: str or ~azure.mgmt.labservices.models.ConnectionType - :ivar client_rdp_access: The enabled access level for Client Access over RDP. Possible values - include: "Public", "Private", "None". + :ivar client_rdp_access: The enabled access level for Client Access over RDP. Known values are: + "Public", "Private", and "None". :vartype client_rdp_access: str or ~azure.mgmt.labservices.models.ConnectionType """ _attribute_map = { - 'web_ssh_access': {'key': 'webSshAccess', 'type': 'str'}, - 'web_rdp_access': {'key': 'webRdpAccess', 'type': 'str'}, - 'client_ssh_access': {'key': 'clientSshAccess', 'type': 'str'}, - 'client_rdp_access': {'key': 'clientRdpAccess', 'type': 'str'}, + "web_ssh_access": {"key": "webSshAccess", "type": "str"}, + "web_rdp_access": {"key": "webRdpAccess", "type": "str"}, + "client_ssh_access": {"key": "clientSshAccess", "type": "str"}, + "client_rdp_access": {"key": "clientRdpAccess", "type": "str"}, } def __init__( self, *, - web_ssh_access: Optional[Union[str, "ConnectionType"]] = None, - web_rdp_access: Optional[Union[str, "ConnectionType"]] = None, - client_ssh_access: Optional[Union[str, "ConnectionType"]] = None, - client_rdp_access: Optional[Union[str, "ConnectionType"]] = None, + web_ssh_access: Optional[Union[str, "_models.ConnectionType"]] = None, + web_rdp_access: Optional[Union[str, "_models.ConnectionType"]] = None, + client_ssh_access: Optional[Union[str, "_models.ConnectionType"]] = None, + client_rdp_access: Optional[Union[str, "_models.ConnectionType"]] = None, **kwargs ): """ - :keyword web_ssh_access: The enabled access level for Web Access over SSH. Possible values - include: "Public", "Private", "None". + :keyword web_ssh_access: The enabled access level for Web Access over SSH. Known values are: + "Public", "Private", and "None". :paramtype web_ssh_access: str or ~azure.mgmt.labservices.models.ConnectionType - :keyword web_rdp_access: The enabled access level for Web Access over RDP. Possible values - include: "Public", "Private", "None". + :keyword web_rdp_access: The enabled access level for Web Access over RDP. Known values are: + "Public", "Private", and "None". :paramtype web_rdp_access: str or ~azure.mgmt.labservices.models.ConnectionType - :keyword client_ssh_access: The enabled access level for Client Access over SSH. Possible - values include: "Public", "Private", "None". + :keyword client_ssh_access: The enabled access level for Client Access over SSH. Known values + are: "Public", "Private", and "None". :paramtype client_ssh_access: str or ~azure.mgmt.labservices.models.ConnectionType - :keyword client_rdp_access: The enabled access level for Client Access over RDP. Possible - values include: "Public", "Private", "None". + :keyword client_rdp_access: The enabled access level for Client Access over RDP. Known values + are: "Public", "Private", and "None". :paramtype client_rdp_access: str or ~azure.mgmt.labservices.models.ConnectionType """ - super(ConnectionProfile, self).__init__(**kwargs) + super().__init__(**kwargs) self.web_ssh_access = web_ssh_access self.web_rdp_access = web_rdp_access self.client_ssh_access = client_ssh_access self.client_rdp_access = client_rdp_access -class Credentials(msrest.serialization.Model): +class Credentials(_serialization.Model): """Credentials for a user on a lab VM. All required parameters must be populated in order to send to Azure. - :ivar username: Required. The username to use when signing in to lab VMs. + :ivar username: The username to use when signing in to lab VMs. Required. :vartype username: str :ivar password: The password for the user. This is required for the TemplateVM createOption. :vartype password: str """ _validation = { - 'username': {'required': True}, + "username": {"required": True}, } _attribute_map = { - 'username': {'key': 'username', 'type': 'str'}, - 'password': {'key': 'password', 'type': 'str'}, + "username": {"key": "username", "type": "str"}, + "password": {"key": "password", "type": "str"}, } - def __init__( - self, - *, - username: str, - password: Optional[str] = None, - **kwargs - ): + def __init__(self, *, username: str, password: Optional[str] = None, **kwargs): """ - :keyword username: Required. The username to use when signing in to lab VMs. + :keyword username: The username to use when signing in to lab VMs. Required. :paramtype username: str :keyword password: The password for the user. This is required for the TemplateVM createOption. :paramtype password: str """ - super(Credentials, self).__init__(**kwargs) + super().__init__(**kwargs) self.username = username self.password = password -class ErrorAdditionalInfo(msrest.serialization.Model): +class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. Variables are only populated by the server, and will be ignored when sending a request. @@ -187,31 +183,27 @@ class ErrorAdditionalInfo(msrest.serialization.Model): :ivar type: The additional info type. :vartype type: str :ivar info: The additional info. - :vartype info: any + :vartype info: JSON """ _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, + "type": {"readonly": True}, + "info": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ErrorAdditionalInfo, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None self.info = None -class ErrorDetail(msrest.serialization.Model): +class ErrorDetail(_serialization.Model): """The error detail. Variables are only populated by the server, and will be ignored when sending a request. @@ -229,28 +221,24 @@ class ErrorDetail(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDetail]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ErrorDetail, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None @@ -258,7 +246,7 @@ def __init__( self.additional_info = None -class ErrorResponse(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). :ivar error: The error object. @@ -266,24 +254,54 @@ class ErrorResponse(msrest.serialization.Model): """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, + "error": {"key": "error", "type": "ErrorDetail"}, } - def __init__( - self, - *, - error: Optional["ErrorDetail"] = None, - **kwargs - ): + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): """ :keyword error: The error object. :paramtype error: ~azure.mgmt.labservices.models.ErrorDetail """ - super(ErrorResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.error = error -class Resource(msrest.serialization.Model): +class Identity(_serialization.Model): + """Identity for the resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal ID of resource identity. + :vartype principal_id: str + :ivar tenant_id: The tenant ID of resource. + :vartype tenant_id: str + :ivar type: The identity type. Default value is "SystemAssigned". + :vartype type: str + """ + + _validation = { + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, type: Optional[str] = None, **kwargs): + """ + :keyword type: The identity type. Default value is "SystemAssigned". + :paramtype type: str + """ + super().__init__(**kwargs) + self.principal_id = None + self.tenant_id = None + self.type = type + + +class Resource(_serialization.Model): """Common fields that are returned in the response for all Azure Resource Manager resources. Variables are only populated by the server, and will be ignored when sending a request. @@ -299,24 +317,20 @@ class Resource(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "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'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(Resource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -338,27 +352,23 @@ class ProxyResource(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "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'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ProxyResource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) -class Image(ProxyResource): +class Image(ProxyResource): # pylint: disable=too-many-instance-attributes """Lab services virtual machine image. Variables are only populated by the server, and will be ignored when sending a request. @@ -373,10 +383,10 @@ class Image(ProxyResource): :vartype type: str :ivar system_data: Metadata pertaining to creation and last modification of the image. :vartype system_data: ~azure.mgmt.labservices.models.SystemData - :ivar enabled_state: Is the image enabled. Possible values include: "Enabled", "Disabled". + :ivar enabled_state: Is the image enabled. Known values are: "Enabled" and "Disabled". :vartype enabled_state: str or ~azure.mgmt.labservices.models.EnableState - :ivar provisioning_state: Current provisioning state of the image. Possible values include: - "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Locked". + :ivar provisioning_state: Current provisioning state of the image. Known values are: + "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Locked". :vartype provisioning_state: str or ~azure.mgmt.labservices.models.ProvisioningState :ivar display_name: The image display name. :vartype display_name: str @@ -386,12 +396,12 @@ class Image(ProxyResource): :vartype icon_url: str :ivar author: The image author. :vartype author: str - :ivar os_type: The OS Type of the image. Possible values include: "Windows", "Linux". + :ivar os_type: The OS Type of the image. Known values are: "Windows" and "Linux". :vartype os_type: str or ~azure.mgmt.labservices.models.OsType :ivar plan: The ID of marketplace plan associated with the image (optional). :vartype plan: str :ivar terms_status: The status of image terms of use (enabled = accepted, disabled = not - accepted). Possible values include: "Enabled", "Disabled". + accepted). Known values are: "Enabled" and "Disabled". :vartype terms_status: str or ~azure.mgmt.labservices.models.EnableState :ivar offer: The ID of an offer associated with the image. :vartype offer: str @@ -405,69 +415,68 @@ class Image(ProxyResource): :vartype shared_gallery_id: str :ivar available_regions: The available regions of the image in the shared gallery. :vartype available_regions: list[str] - :ivar os_state: The OS State of the image. Possible values include: "Generalized", - "Specialized". + :ivar os_state: The OS State of the image. Known values are: "Generalized" and "Specialized". :vartype os_state: str or ~azure.mgmt.labservices.models.OsState """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'display_name': {'readonly': True}, - 'description': {'readonly': True}, - 'icon_url': {'readonly': True}, - 'author': {'readonly': True}, - 'os_type': {'readonly': True}, - 'plan': {'readonly': True}, - 'terms_status': {'readonly': True}, - 'offer': {'readonly': True}, - 'publisher': {'readonly': True}, - 'sku': {'readonly': True}, - 'version': {'readonly': True}, - 'shared_gallery_id': {'readonly': True, 'max_length': 2000, 'min_length': 3}, - 'os_state': {'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'}, - 'enabled_state': {'key': 'properties.enabledState', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'icon_url': {'key': 'properties.iconUrl', 'type': 'str'}, - 'author': {'key': 'properties.author', 'type': 'str'}, - 'os_type': {'key': 'properties.osType', 'type': 'str'}, - 'plan': {'key': 'properties.plan', 'type': 'str'}, - 'terms_status': {'key': 'properties.termsStatus', 'type': 'str'}, - 'offer': {'key': 'properties.offer', 'type': 'str'}, - 'publisher': {'key': 'properties.publisher', 'type': 'str'}, - 'sku': {'key': 'properties.sku', 'type': 'str'}, - 'version': {'key': 'properties.version', 'type': 'str'}, - 'shared_gallery_id': {'key': 'properties.sharedGalleryId', 'type': 'str'}, - 'available_regions': {'key': 'properties.availableRegions', 'type': '[str]'}, - 'os_state': {'key': 'properties.osState', 'type': 'str'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "display_name": {"readonly": True}, + "description": {"readonly": True}, + "icon_url": {"readonly": True}, + "author": {"readonly": True}, + "os_type": {"readonly": True}, + "plan": {"readonly": True}, + "terms_status": {"readonly": True}, + "offer": {"readonly": True}, + "publisher": {"readonly": True}, + "sku": {"readonly": True}, + "version": {"readonly": True}, + "shared_gallery_id": {"readonly": True, "max_length": 2000, "min_length": 3}, + "os_state": {"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"}, + "enabled_state": {"key": "properties.enabledState", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "icon_url": {"key": "properties.iconUrl", "type": "str"}, + "author": {"key": "properties.author", "type": "str"}, + "os_type": {"key": "properties.osType", "type": "str"}, + "plan": {"key": "properties.plan", "type": "str"}, + "terms_status": {"key": "properties.termsStatus", "type": "str"}, + "offer": {"key": "properties.offer", "type": "str"}, + "publisher": {"key": "properties.publisher", "type": "str"}, + "sku": {"key": "properties.sku", "type": "str"}, + "version": {"key": "properties.version", "type": "str"}, + "shared_gallery_id": {"key": "properties.sharedGalleryId", "type": "str"}, + "available_regions": {"key": "properties.availableRegions", "type": "[str]"}, + "os_state": {"key": "properties.osState", "type": "str"}, } def __init__( self, *, - enabled_state: Optional[Union[str, "EnableState"]] = None, + enabled_state: Optional[Union[str, "_models.EnableState"]] = None, available_regions: Optional[List[str]] = None, **kwargs ): """ - :keyword enabled_state: Is the image enabled. Possible values include: "Enabled", "Disabled". + :keyword enabled_state: Is the image enabled. Known values are: "Enabled" and "Disabled". :paramtype enabled_state: str or ~azure.mgmt.labservices.models.EnableState :keyword available_regions: The available regions of the image in the shared gallery. :paramtype available_regions: list[str] """ - super(Image, self).__init__(**kwargs) + super().__init__(**kwargs) self.system_data = None self.enabled_state = enabled_state self.provisioning_state = None @@ -487,40 +496,35 @@ def __init__( self.os_state = None -class ImageUpdateProperties(msrest.serialization.Model): +class ImageUpdateProperties(_serialization.Model): """Properties of an image resource update. - :ivar enabled_state: Is the image enabled. Possible values include: "Enabled", "Disabled". + :ivar enabled_state: Is the image enabled. Known values are: "Enabled" and "Disabled". :vartype enabled_state: str or ~azure.mgmt.labservices.models.EnableState """ _attribute_map = { - 'enabled_state': {'key': 'enabledState', 'type': 'str'}, + "enabled_state": {"key": "enabledState", "type": "str"}, } - def __init__( - self, - *, - enabled_state: Optional[Union[str, "EnableState"]] = None, - **kwargs - ): + def __init__(self, *, enabled_state: Optional[Union[str, "_models.EnableState"]] = None, **kwargs): """ - :keyword enabled_state: Is the image enabled. Possible values include: "Enabled", "Disabled". + :keyword enabled_state: Is the image enabled. Known values are: "Enabled" and "Disabled". :paramtype enabled_state: str or ~azure.mgmt.labservices.models.EnableState """ - super(ImageUpdateProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.enabled_state = enabled_state -class ImageProperties(ImageUpdateProperties): +class ImageProperties(ImageUpdateProperties): # pylint: disable=too-many-instance-attributes """Properties of an image resource. Variables are only populated by the server, and will be ignored when sending a request. - :ivar enabled_state: Is the image enabled. Possible values include: "Enabled", "Disabled". + :ivar enabled_state: Is the image enabled. Known values are: "Enabled" and "Disabled". :vartype enabled_state: str or ~azure.mgmt.labservices.models.EnableState - :ivar provisioning_state: Current provisioning state of the image. Possible values include: - "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Locked". + :ivar provisioning_state: Current provisioning state of the image. Known values are: + "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Locked". :vartype provisioning_state: str or ~azure.mgmt.labservices.models.ProvisioningState :ivar display_name: The image display name. :vartype display_name: str @@ -530,12 +534,12 @@ class ImageProperties(ImageUpdateProperties): :vartype icon_url: str :ivar author: The image author. :vartype author: str - :ivar os_type: The OS Type of the image. Possible values include: "Windows", "Linux". + :ivar os_type: The OS Type of the image. Known values are: "Windows" and "Linux". :vartype os_type: str or ~azure.mgmt.labservices.models.OsType :ivar plan: The ID of marketplace plan associated with the image (optional). :vartype plan: str :ivar terms_status: The status of image terms of use (enabled = accepted, disabled = not - accepted). Possible values include: "Enabled", "Disabled". + accepted). Known values are: "Enabled" and "Disabled". :vartype terms_status: str or ~azure.mgmt.labservices.models.EnableState :ivar offer: The ID of an offer associated with the image. :vartype offer: str @@ -549,61 +553,60 @@ class ImageProperties(ImageUpdateProperties): :vartype shared_gallery_id: str :ivar available_regions: The available regions of the image in the shared gallery. :vartype available_regions: list[str] - :ivar os_state: The OS State of the image. Possible values include: "Generalized", - "Specialized". + :ivar os_state: The OS State of the image. Known values are: "Generalized" and "Specialized". :vartype os_state: str or ~azure.mgmt.labservices.models.OsState """ _validation = { - 'provisioning_state': {'readonly': True}, - 'display_name': {'readonly': True}, - 'description': {'readonly': True}, - 'icon_url': {'readonly': True}, - 'author': {'readonly': True}, - 'os_type': {'readonly': True}, - 'plan': {'readonly': True}, - 'terms_status': {'readonly': True}, - 'offer': {'readonly': True}, - 'publisher': {'readonly': True}, - 'sku': {'readonly': True}, - 'version': {'readonly': True}, - 'shared_gallery_id': {'readonly': True, 'max_length': 2000, 'min_length': 3}, - 'os_state': {'readonly': True}, - } - - _attribute_map = { - 'enabled_state': {'key': 'enabledState', 'type': 'str'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - 'icon_url': {'key': 'iconUrl', 'type': 'str'}, - 'author': {'key': 'author', 'type': 'str'}, - 'os_type': {'key': 'osType', 'type': 'str'}, - 'plan': {'key': 'plan', 'type': 'str'}, - 'terms_status': {'key': 'termsStatus', 'type': 'str'}, - 'offer': {'key': 'offer', 'type': 'str'}, - 'publisher': {'key': 'publisher', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'str'}, - 'version': {'key': 'version', 'type': 'str'}, - 'shared_gallery_id': {'key': 'sharedGalleryId', 'type': 'str'}, - 'available_regions': {'key': 'availableRegions', 'type': '[str]'}, - 'os_state': {'key': 'osState', 'type': 'str'}, + "provisioning_state": {"readonly": True}, + "display_name": {"readonly": True}, + "description": {"readonly": True}, + "icon_url": {"readonly": True}, + "author": {"readonly": True}, + "os_type": {"readonly": True}, + "plan": {"readonly": True}, + "terms_status": {"readonly": True}, + "offer": {"readonly": True}, + "publisher": {"readonly": True}, + "sku": {"readonly": True}, + "version": {"readonly": True}, + "shared_gallery_id": {"readonly": True, "max_length": 2000, "min_length": 3}, + "os_state": {"readonly": True}, + } + + _attribute_map = { + "enabled_state": {"key": "enabledState", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "icon_url": {"key": "iconUrl", "type": "str"}, + "author": {"key": "author", "type": "str"}, + "os_type": {"key": "osType", "type": "str"}, + "plan": {"key": "plan", "type": "str"}, + "terms_status": {"key": "termsStatus", "type": "str"}, + "offer": {"key": "offer", "type": "str"}, + "publisher": {"key": "publisher", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "version": {"key": "version", "type": "str"}, + "shared_gallery_id": {"key": "sharedGalleryId", "type": "str"}, + "available_regions": {"key": "availableRegions", "type": "[str]"}, + "os_state": {"key": "osState", "type": "str"}, } def __init__( self, *, - enabled_state: Optional[Union[str, "EnableState"]] = None, + enabled_state: Optional[Union[str, "_models.EnableState"]] = None, available_regions: Optional[List[str]] = None, **kwargs ): """ - :keyword enabled_state: Is the image enabled. Possible values include: "Enabled", "Disabled". + :keyword enabled_state: Is the image enabled. Known values are: "Enabled" and "Disabled". :paramtype enabled_state: str or ~azure.mgmt.labservices.models.EnableState :keyword available_regions: The available regions of the image in the shared gallery. :paramtype available_regions: list[str] """ - super(ImageProperties, self).__init__(enabled_state=enabled_state, **kwargs) + super().__init__(enabled_state=enabled_state, **kwargs) self.provisioning_state = None self.display_name = None self.description = None @@ -621,7 +624,7 @@ def __init__( self.os_state = None -class ImageReference(msrest.serialization.Model): +class ImageReference(_serialization.Model): """Image reference information. Used in the virtual machine profile. Variables are only populated by the server, and will be ignored when sending a request. @@ -641,23 +644,23 @@ class ImageReference(msrest.serialization.Model): """ _validation = { - 'id': {'max_length': 2000, 'min_length': 3}, - 'exact_version': {'readonly': True}, + "id": {"max_length": 2000, "min_length": 3}, + "exact_version": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'offer': {'key': 'offer', 'type': 'str'}, - 'publisher': {'key': 'publisher', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'str'}, - 'version': {'key': 'version', 'type': 'str'}, - 'exact_version': {'key': 'exactVersion', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "offer": {"key": "offer", "type": "str"}, + "publisher": {"key": "publisher", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "version": {"key": "version", "type": "str"}, + "exact_version": {"key": "exactVersion", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin offer: Optional[str] = None, publisher: Optional[str] = None, sku: Optional[str] = None, @@ -676,7 +679,7 @@ def __init__( :keyword version: The image version specified on creation. :paramtype version: str """ - super(ImageReference, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = id self.offer = offer self.publisher = publisher @@ -685,32 +688,27 @@ def __init__( self.exact_version = None -class ImageUpdate(msrest.serialization.Model): +class ImageUpdate(_serialization.Model): """Lab services virtual machine image for updates. - :ivar enabled_state: Is the image enabled. Possible values include: "Enabled", "Disabled". + :ivar enabled_state: Is the image enabled. Known values are: "Enabled" and "Disabled". :vartype enabled_state: str or ~azure.mgmt.labservices.models.EnableState """ _attribute_map = { - 'enabled_state': {'key': 'properties.enabledState', 'type': 'str'}, + "enabled_state": {"key": "properties.enabledState", "type": "str"}, } - def __init__( - self, - *, - enabled_state: Optional[Union[str, "EnableState"]] = None, - **kwargs - ): + def __init__(self, *, enabled_state: Optional[Union[str, "_models.EnableState"]] = None, **kwargs): """ - :keyword enabled_state: Is the image enabled. Possible values include: "Enabled", "Disabled". + :keyword enabled_state: Is the image enabled. Known values are: "Enabled" and "Disabled". :paramtype enabled_state: str or ~azure.mgmt.labservices.models.EnableState """ - super(ImageUpdate, self).__init__(**kwargs) + super().__init__(**kwargs) self.enabled_state = enabled_state -class InviteBody(msrest.serialization.Model): +class InviteBody(_serialization.Model): """Body for a user invite request. :ivar text: Custom text for the invite email. @@ -718,20 +716,15 @@ class InviteBody(msrest.serialization.Model): """ _attribute_map = { - 'text': {'key': 'text', 'type': 'str'}, + "text": {"key": "text", "type": "str"}, } - def __init__( - self, - *, - text: Optional[str] = None, - **kwargs - ): + def __init__(self, *, text: Optional[str] = None, **kwargs): """ :keyword text: Custom text for the invite email. :paramtype text: str """ - super(InviteBody, self).__init__(**kwargs) + super().__init__(**kwargs) self.text = text @@ -750,46 +743,40 @@ class TrackedResource(Resource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] - :ivar location: Required. The geo-location where the resource lives. + :ivar location: The geo-location where the resource lives. Required. :vartype location: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, } - def __init__( - self, - *, - location: str, - tags: Optional[Dict[str, str]] = None, - **kwargs - ): + def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs): """ - :keyword tags: A set of tags. Resource tags. + :keyword tags: Resource tags. :paramtype tags: dict[str, str] - :keyword location: Required. The geo-location where the resource lives. + :keyword location: The geo-location where the resource lives. Required. :paramtype location: str """ - super(TrackedResource, self).__init__(**kwargs) + super().__init__(**kwargs) self.tags = tags self.location = location -class Lab(TrackedResource): +class Lab(TrackedResource): # pylint: disable=too-many-instance-attributes """The lab resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -804,9 +791,9 @@ class Lab(TrackedResource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] - :ivar location: Required. The geo-location where the resource lives. + :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar system_data: Metadata pertaining to creation and last modification of the lab. :vartype system_data: ~azure.mgmt.labservices.models.SystemData @@ -830,47 +817,47 @@ class Lab(TrackedResource): :vartype title: str :ivar description: The description of the lab. :vartype description: str - :ivar provisioning_state: Current provisioning state of the lab. Possible values include: - "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Locked". + :ivar provisioning_state: Current provisioning state of the lab. Known values are: "Creating", + "Updating", "Deleting", "Succeeded", "Failed", and "Locked". :vartype provisioning_state: str or ~azure.mgmt.labservices.models.ProvisioningState :ivar network_profile: The network profile for the lab, typically applied via a lab plan. This profile cannot be modified once a lab has been created. :vartype network_profile: ~azure.mgmt.labservices.models.LabNetworkProfile - :ivar state: The lab state. Possible values include: "Draft", "Publishing", "Scaling", - "Syncing", "Published". + :ivar state: The lab state. Known values are: "Draft", "Publishing", "Scaling", "Syncing", and + "Published". :vartype state: str or ~azure.mgmt.labservices.models.LabState """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - 'system_data': {'readonly': True}, - 'lab_plan_id': {'max_length': 2000, 'min_length': 3}, - 'title': {'max_length': 120, 'min_length': 1}, - 'provisioning_state': {'readonly': True}, - 'state': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - 'auto_shutdown_profile': {'key': 'properties.autoShutdownProfile', 'type': 'AutoShutdownProfile'}, - 'connection_profile': {'key': 'properties.connectionProfile', 'type': 'ConnectionProfile'}, - 'virtual_machine_profile': {'key': 'properties.virtualMachineProfile', 'type': 'VirtualMachineProfile'}, - 'security_profile': {'key': 'properties.securityProfile', 'type': 'SecurityProfile'}, - 'roster_profile': {'key': 'properties.rosterProfile', 'type': 'RosterProfile'}, - 'lab_plan_id': {'key': 'properties.labPlanId', 'type': 'str'}, - 'title': {'key': 'properties.title', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'network_profile': {'key': 'properties.networkProfile', 'type': 'LabNetworkProfile'}, - 'state': {'key': 'properties.state', 'type': 'str'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + "system_data": {"readonly": True}, + "lab_plan_id": {"max_length": 2000, "min_length": 3}, + "title": {"max_length": 120, "min_length": 1}, + "provisioning_state": {"readonly": True}, + "state": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "auto_shutdown_profile": {"key": "properties.autoShutdownProfile", "type": "AutoShutdownProfile"}, + "connection_profile": {"key": "properties.connectionProfile", "type": "ConnectionProfile"}, + "virtual_machine_profile": {"key": "properties.virtualMachineProfile", "type": "VirtualMachineProfile"}, + "security_profile": {"key": "properties.securityProfile", "type": "SecurityProfile"}, + "roster_profile": {"key": "properties.rosterProfile", "type": "RosterProfile"}, + "lab_plan_id": {"key": "properties.labPlanId", "type": "str"}, + "title": {"key": "properties.title", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "network_profile": {"key": "properties.networkProfile", "type": "LabNetworkProfile"}, + "state": {"key": "properties.state", "type": "str"}, } def __init__( @@ -878,21 +865,21 @@ def __init__( *, location: str, tags: Optional[Dict[str, str]] = None, - auto_shutdown_profile: Optional["AutoShutdownProfile"] = None, - connection_profile: Optional["ConnectionProfile"] = None, - virtual_machine_profile: Optional["VirtualMachineProfile"] = None, - security_profile: Optional["SecurityProfile"] = None, - roster_profile: Optional["RosterProfile"] = None, + auto_shutdown_profile: Optional["_models.AutoShutdownProfile"] = None, + connection_profile: Optional["_models.ConnectionProfile"] = None, + virtual_machine_profile: Optional["_models.VirtualMachineProfile"] = None, + security_profile: Optional["_models.SecurityProfile"] = None, + roster_profile: Optional["_models.RosterProfile"] = None, lab_plan_id: Optional[str] = None, title: Optional[str] = None, description: Optional[str] = None, - network_profile: Optional["LabNetworkProfile"] = None, + network_profile: Optional["_models.LabNetworkProfile"] = None, **kwargs ): """ - :keyword tags: A set of tags. Resource tags. + :keyword tags: Resource tags. :paramtype tags: dict[str, str] - :keyword location: Required. The geo-location where the resource lives. + :keyword location: The geo-location where the resource lives. Required. :paramtype location: str :keyword auto_shutdown_profile: The resource auto shutdown configuration for the lab. This controls whether actions are taken on resources that are sitting idle. @@ -918,7 +905,7 @@ def __init__( This profile cannot be modified once a lab has been created. :paramtype network_profile: ~azure.mgmt.labservices.models.LabNetworkProfile """ - super(Lab, self).__init__(tags=tags, location=location, **kwargs) + super().__init__(tags=tags, location=location, **kwargs) self.system_data = None self.auto_shutdown_profile = auto_shutdown_profile self.connection_profile = connection_profile @@ -933,7 +920,7 @@ def __init__( self.state = None -class LabNetworkProfile(msrest.serialization.Model): +class LabNetworkProfile(_serialization.Model): """Profile for how to handle networking for Labs. :ivar subnet_id: The external subnet resource id. @@ -945,15 +932,15 @@ class LabNetworkProfile(msrest.serialization.Model): """ _validation = { - 'subnet_id': {'max_length': 2000, 'min_length': 3}, - 'load_balancer_id': {'max_length': 2000, 'min_length': 3}, - 'public_ip_id': {'max_length': 2000, 'min_length': 3}, + "subnet_id": {"max_length": 2000, "min_length": 3}, + "load_balancer_id": {"max_length": 2000, "min_length": 3}, + "public_ip_id": {"max_length": 2000, "min_length": 3}, } _attribute_map = { - 'subnet_id': {'key': 'subnetId', 'type': 'str'}, - 'load_balancer_id': {'key': 'loadBalancerId', 'type': 'str'}, - 'public_ip_id': {'key': 'publicIpId', 'type': 'str'}, + "subnet_id": {"key": "subnetId", "type": "str"}, + "load_balancer_id": {"key": "loadBalancerId", "type": "str"}, + "public_ip_id": {"key": "publicIpId", "type": "str"}, } def __init__( @@ -972,13 +959,13 @@ def __init__( :keyword public_ip_id: The external public IP resource id. :paramtype public_ip_id: str """ - super(LabNetworkProfile, self).__init__(**kwargs) + super().__init__(**kwargs) self.subnet_id = subnet_id self.load_balancer_id = load_balancer_id self.public_ip_id = public_ip_id -class LabPlan(TrackedResource): +class LabPlan(TrackedResource): # pylint: disable=too-many-instance-attributes """Lab Plans act as a permission container for creating labs via labs.azure.com. Additionally, they can provide a set of default configurations that will apply at the time of creating a lab, but these defaults can still be overwritten. Variables are only populated by the server, and will be ignored when sending a request. @@ -993,12 +980,14 @@ class LabPlan(TrackedResource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] - :ivar location: Required. The geo-location where the resource lives. + :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar system_data: Metadata pertaining to creation and last modification of the lab plan. :vartype system_data: ~azure.mgmt.labservices.models.SystemData + :ivar identity: Managed Identity Information. + :vartype identity: ~azure.mgmt.labservices.models.Identity :ivar default_connection_profile: The default lab connection profile. This can be changed on a lab resource and only provides a default profile. :vartype default_connection_profile: ~azure.mgmt.labservices.models.ConnectionProfile @@ -1023,37 +1012,41 @@ class LabPlan(TrackedResource): :ivar linked_lms_instance: Base Url of the lms instance this lab plan can link lab rosters against. :vartype linked_lms_instance: str - :ivar provisioning_state: Current provisioning state of the lab plan. Possible values include: - "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Locked". + :ivar provisioning_state: Current provisioning state of the lab plan. Known values are: + "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Locked". :vartype provisioning_state: str or ~azure.mgmt.labservices.models.ProvisioningState """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - 'system_data': {'readonly': True}, - 'shared_gallery_id': {'max_length': 2000, 'min_length': 3}, - 'linked_lms_instance': {'max_length': 2000, 'min_length': 3}, - 'provisioning_state': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - 'default_connection_profile': {'key': 'properties.defaultConnectionProfile', 'type': 'ConnectionProfile'}, - 'default_auto_shutdown_profile': {'key': 'properties.defaultAutoShutdownProfile', 'type': 'AutoShutdownProfile'}, - 'default_network_profile': {'key': 'properties.defaultNetworkProfile', 'type': 'LabPlanNetworkProfile'}, - 'allowed_regions': {'key': 'properties.allowedRegions', 'type': '[str]'}, - 'shared_gallery_id': {'key': 'properties.sharedGalleryId', 'type': 'str'}, - 'support_info': {'key': 'properties.supportInfo', 'type': 'SupportInfo'}, - 'linked_lms_instance': {'key': 'properties.linkedLmsInstance', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + "system_data": {"readonly": True}, + "shared_gallery_id": {"max_length": 2000, "min_length": 3}, + "linked_lms_instance": {"max_length": 2000, "min_length": 3}, + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "identity": {"key": "identity", "type": "Identity"}, + "default_connection_profile": {"key": "properties.defaultConnectionProfile", "type": "ConnectionProfile"}, + "default_auto_shutdown_profile": { + "key": "properties.defaultAutoShutdownProfile", + "type": "AutoShutdownProfile", + }, + "default_network_profile": {"key": "properties.defaultNetworkProfile", "type": "LabPlanNetworkProfile"}, + "allowed_regions": {"key": "properties.allowedRegions", "type": "[str]"}, + "shared_gallery_id": {"key": "properties.sharedGalleryId", "type": "str"}, + "support_info": {"key": "properties.supportInfo", "type": "SupportInfo"}, + "linked_lms_instance": {"key": "properties.linkedLmsInstance", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, } def __init__( @@ -1061,20 +1054,23 @@ def __init__( *, location: str, tags: Optional[Dict[str, str]] = None, - default_connection_profile: Optional["ConnectionProfile"] = None, - default_auto_shutdown_profile: Optional["AutoShutdownProfile"] = None, - default_network_profile: Optional["LabPlanNetworkProfile"] = None, + identity: Optional["_models.Identity"] = None, + default_connection_profile: Optional["_models.ConnectionProfile"] = None, + default_auto_shutdown_profile: Optional["_models.AutoShutdownProfile"] = None, + default_network_profile: Optional["_models.LabPlanNetworkProfile"] = None, allowed_regions: Optional[List[str]] = None, shared_gallery_id: Optional[str] = None, - support_info: Optional["SupportInfo"] = None, + support_info: Optional["_models.SupportInfo"] = None, linked_lms_instance: Optional[str] = None, **kwargs ): """ - :keyword tags: A set of tags. Resource tags. + :keyword tags: Resource tags. :paramtype tags: dict[str, str] - :keyword location: Required. The geo-location where the resource lives. + :keyword location: The geo-location where the resource lives. Required. :paramtype location: str + :keyword identity: Managed Identity Information. + :paramtype identity: ~azure.mgmt.labservices.models.Identity :keyword default_connection_profile: The default lab connection profile. This can be changed on a lab resource and only provides a default profile. :paramtype default_connection_profile: ~azure.mgmt.labservices.models.ConnectionProfile @@ -1100,8 +1096,9 @@ def __init__( against. :paramtype linked_lms_instance: str """ - super(LabPlan, self).__init__(tags=tags, location=location, **kwargs) + super().__init__(tags=tags, location=location, **kwargs) self.system_data = None + self.identity = identity self.default_connection_profile = default_connection_profile self.default_auto_shutdown_profile = default_auto_shutdown_profile self.default_network_profile = default_network_profile @@ -1112,7 +1109,7 @@ def __init__( self.provisioning_state = None -class LabPlanNetworkProfile(msrest.serialization.Model): +class LabPlanNetworkProfile(_serialization.Model): """Profile for how to handle networking for Lab Plans. :ivar subnet_id: The external subnet resource id. @@ -1120,28 +1117,23 @@ class LabPlanNetworkProfile(msrest.serialization.Model): """ _validation = { - 'subnet_id': {'max_length': 2000, 'min_length': 3}, + "subnet_id": {"max_length": 2000, "min_length": 3}, } _attribute_map = { - 'subnet_id': {'key': 'subnetId', 'type': 'str'}, + "subnet_id": {"key": "subnetId", "type": "str"}, } - def __init__( - self, - *, - subnet_id: Optional[str] = None, - **kwargs - ): + def __init__(self, *, subnet_id: Optional[str] = None, **kwargs): """ :keyword subnet_id: The external subnet resource id. :paramtype subnet_id: str """ - super(LabPlanNetworkProfile, self).__init__(**kwargs) + super().__init__(**kwargs) self.subnet_id = subnet_id -class LabPlanUpdateProperties(msrest.serialization.Model): +class LabPlanUpdateProperties(_serialization.Model): """Lab plan resource properties for updates. :ivar default_connection_profile: The default lab connection profile. This can be changed on a @@ -1171,29 +1163,29 @@ class LabPlanUpdateProperties(msrest.serialization.Model): """ _validation = { - 'shared_gallery_id': {'max_length': 2000, 'min_length': 3}, - 'linked_lms_instance': {'max_length': 2000, 'min_length': 3}, + "shared_gallery_id": {"max_length": 2000, "min_length": 3}, + "linked_lms_instance": {"max_length": 2000, "min_length": 3}, } _attribute_map = { - 'default_connection_profile': {'key': 'defaultConnectionProfile', 'type': 'ConnectionProfile'}, - 'default_auto_shutdown_profile': {'key': 'defaultAutoShutdownProfile', 'type': 'AutoShutdownProfile'}, - 'default_network_profile': {'key': 'defaultNetworkProfile', 'type': 'LabPlanNetworkProfile'}, - 'allowed_regions': {'key': 'allowedRegions', 'type': '[str]'}, - 'shared_gallery_id': {'key': 'sharedGalleryId', 'type': 'str'}, - 'support_info': {'key': 'supportInfo', 'type': 'SupportInfo'}, - 'linked_lms_instance': {'key': 'linkedLmsInstance', 'type': 'str'}, + "default_connection_profile": {"key": "defaultConnectionProfile", "type": "ConnectionProfile"}, + "default_auto_shutdown_profile": {"key": "defaultAutoShutdownProfile", "type": "AutoShutdownProfile"}, + "default_network_profile": {"key": "defaultNetworkProfile", "type": "LabPlanNetworkProfile"}, + "allowed_regions": {"key": "allowedRegions", "type": "[str]"}, + "shared_gallery_id": {"key": "sharedGalleryId", "type": "str"}, + "support_info": {"key": "supportInfo", "type": "SupportInfo"}, + "linked_lms_instance": {"key": "linkedLmsInstance", "type": "str"}, } def __init__( self, *, - default_connection_profile: Optional["ConnectionProfile"] = None, - default_auto_shutdown_profile: Optional["AutoShutdownProfile"] = None, - default_network_profile: Optional["LabPlanNetworkProfile"] = None, + default_connection_profile: Optional["_models.ConnectionProfile"] = None, + default_auto_shutdown_profile: Optional["_models.AutoShutdownProfile"] = None, + default_network_profile: Optional["_models.LabPlanNetworkProfile"] = None, allowed_regions: Optional[List[str]] = None, shared_gallery_id: Optional[str] = None, - support_info: Optional["SupportInfo"] = None, + support_info: Optional["_models.SupportInfo"] = None, linked_lms_instance: Optional[str] = None, **kwargs ): @@ -1223,7 +1215,7 @@ def __init__( against. :paramtype linked_lms_instance: str """ - super(LabPlanUpdateProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.default_connection_profile = default_connection_profile self.default_auto_shutdown_profile = default_auto_shutdown_profile self.default_network_profile = default_network_profile @@ -1262,37 +1254,37 @@ class LabPlanProperties(LabPlanUpdateProperties): :ivar linked_lms_instance: Base Url of the lms instance this lab plan can link lab rosters against. :vartype linked_lms_instance: str - :ivar provisioning_state: Current provisioning state of the lab plan. Possible values include: - "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Locked". + :ivar provisioning_state: Current provisioning state of the lab plan. Known values are: + "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Locked". :vartype provisioning_state: str or ~azure.mgmt.labservices.models.ProvisioningState """ _validation = { - 'shared_gallery_id': {'max_length': 2000, 'min_length': 3}, - 'linked_lms_instance': {'max_length': 2000, 'min_length': 3}, - 'provisioning_state': {'readonly': True}, + "shared_gallery_id": {"max_length": 2000, "min_length": 3}, + "linked_lms_instance": {"max_length": 2000, "min_length": 3}, + "provisioning_state": {"readonly": True}, } _attribute_map = { - 'default_connection_profile': {'key': 'defaultConnectionProfile', 'type': 'ConnectionProfile'}, - 'default_auto_shutdown_profile': {'key': 'defaultAutoShutdownProfile', 'type': 'AutoShutdownProfile'}, - 'default_network_profile': {'key': 'defaultNetworkProfile', 'type': 'LabPlanNetworkProfile'}, - 'allowed_regions': {'key': 'allowedRegions', 'type': '[str]'}, - 'shared_gallery_id': {'key': 'sharedGalleryId', 'type': 'str'}, - 'support_info': {'key': 'supportInfo', 'type': 'SupportInfo'}, - 'linked_lms_instance': {'key': 'linkedLmsInstance', 'type': 'str'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, + "default_connection_profile": {"key": "defaultConnectionProfile", "type": "ConnectionProfile"}, + "default_auto_shutdown_profile": {"key": "defaultAutoShutdownProfile", "type": "AutoShutdownProfile"}, + "default_network_profile": {"key": "defaultNetworkProfile", "type": "LabPlanNetworkProfile"}, + "allowed_regions": {"key": "allowedRegions", "type": "[str]"}, + "shared_gallery_id": {"key": "sharedGalleryId", "type": "str"}, + "support_info": {"key": "supportInfo", "type": "SupportInfo"}, + "linked_lms_instance": {"key": "linkedLmsInstance", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, } def __init__( self, *, - default_connection_profile: Optional["ConnectionProfile"] = None, - default_auto_shutdown_profile: Optional["AutoShutdownProfile"] = None, - default_network_profile: Optional["LabPlanNetworkProfile"] = None, + default_connection_profile: Optional["_models.ConnectionProfile"] = None, + default_auto_shutdown_profile: Optional["_models.AutoShutdownProfile"] = None, + default_network_profile: Optional["_models.LabPlanNetworkProfile"] = None, allowed_regions: Optional[List[str]] = None, shared_gallery_id: Optional[str] = None, - support_info: Optional["SupportInfo"] = None, + support_info: Optional["_models.SupportInfo"] = None, linked_lms_instance: Optional[str] = None, **kwargs ): @@ -1322,40 +1314,46 @@ def __init__( against. :paramtype linked_lms_instance: str """ - super(LabPlanProperties, self).__init__(default_connection_profile=default_connection_profile, default_auto_shutdown_profile=default_auto_shutdown_profile, default_network_profile=default_network_profile, allowed_regions=allowed_regions, shared_gallery_id=shared_gallery_id, support_info=support_info, linked_lms_instance=linked_lms_instance, **kwargs) + super().__init__( + default_connection_profile=default_connection_profile, + default_auto_shutdown_profile=default_auto_shutdown_profile, + default_network_profile=default_network_profile, + allowed_regions=allowed_regions, + shared_gallery_id=shared_gallery_id, + support_info=support_info, + linked_lms_instance=linked_lms_instance, + **kwargs + ) self.provisioning_state = None -class TrackedResourceUpdate(msrest.serialization.Model): +class TrackedResourceUpdate(_serialization.Model): """Base tracked resource type for all PATCH updates. - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: list[str] """ _attribute_map = { - 'tags': {'key': 'tags', 'type': '[str]'}, + "tags": {"key": "tags", "type": "[str]"}, } - def __init__( - self, - *, - tags: Optional[List[str]] = None, - **kwargs - ): + def __init__(self, *, tags: Optional[List[str]] = None, **kwargs): """ - :keyword tags: A set of tags. Resource tags. + :keyword tags: Resource tags. :paramtype tags: list[str] """ - super(TrackedResourceUpdate, self).__init__(**kwargs) + super().__init__(**kwargs) self.tags = tags class LabPlanUpdate(TrackedResourceUpdate): """Contains lab configuration and default settings. This variant is used for PATCH. - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: list[str] + :ivar identity: Managed Identity Information. + :vartype identity: ~azure.mgmt.labservices.models.Identity :ivar default_connection_profile: The default lab connection profile. This can be changed on a lab resource and only provides a default profile. :vartype default_connection_profile: ~azure.mgmt.labservices.models.ConnectionProfile @@ -1383,37 +1381,44 @@ class LabPlanUpdate(TrackedResourceUpdate): """ _validation = { - 'shared_gallery_id': {'max_length': 2000, 'min_length': 3}, - 'linked_lms_instance': {'max_length': 2000, 'min_length': 3}, + "shared_gallery_id": {"max_length": 2000, "min_length": 3}, + "linked_lms_instance": {"max_length": 2000, "min_length": 3}, } _attribute_map = { - 'tags': {'key': 'tags', 'type': '[str]'}, - 'default_connection_profile': {'key': 'properties.defaultConnectionProfile', 'type': 'ConnectionProfile'}, - 'default_auto_shutdown_profile': {'key': 'properties.defaultAutoShutdownProfile', 'type': 'AutoShutdownProfile'}, - 'default_network_profile': {'key': 'properties.defaultNetworkProfile', 'type': 'LabPlanNetworkProfile'}, - 'allowed_regions': {'key': 'properties.allowedRegions', 'type': '[str]'}, - 'shared_gallery_id': {'key': 'properties.sharedGalleryId', 'type': 'str'}, - 'support_info': {'key': 'properties.supportInfo', 'type': 'SupportInfo'}, - 'linked_lms_instance': {'key': 'properties.linkedLmsInstance', 'type': 'str'}, + "tags": {"key": "tags", "type": "[str]"}, + "identity": {"key": "identity", "type": "Identity"}, + "default_connection_profile": {"key": "properties.defaultConnectionProfile", "type": "ConnectionProfile"}, + "default_auto_shutdown_profile": { + "key": "properties.defaultAutoShutdownProfile", + "type": "AutoShutdownProfile", + }, + "default_network_profile": {"key": "properties.defaultNetworkProfile", "type": "LabPlanNetworkProfile"}, + "allowed_regions": {"key": "properties.allowedRegions", "type": "[str]"}, + "shared_gallery_id": {"key": "properties.sharedGalleryId", "type": "str"}, + "support_info": {"key": "properties.supportInfo", "type": "SupportInfo"}, + "linked_lms_instance": {"key": "properties.linkedLmsInstance", "type": "str"}, } def __init__( self, *, tags: Optional[List[str]] = None, - default_connection_profile: Optional["ConnectionProfile"] = None, - default_auto_shutdown_profile: Optional["AutoShutdownProfile"] = None, - default_network_profile: Optional["LabPlanNetworkProfile"] = None, + identity: Optional["_models.Identity"] = None, + default_connection_profile: Optional["_models.ConnectionProfile"] = None, + default_auto_shutdown_profile: Optional["_models.AutoShutdownProfile"] = None, + default_network_profile: Optional["_models.LabPlanNetworkProfile"] = None, allowed_regions: Optional[List[str]] = None, shared_gallery_id: Optional[str] = None, - support_info: Optional["SupportInfo"] = None, + support_info: Optional["_models.SupportInfo"] = None, linked_lms_instance: Optional[str] = None, **kwargs ): """ - :keyword tags: A set of tags. Resource tags. + :keyword tags: Resource tags. :paramtype tags: list[str] + :keyword identity: Managed Identity Information. + :paramtype identity: ~azure.mgmt.labservices.models.Identity :keyword default_connection_profile: The default lab connection profile. This can be changed on a lab resource and only provides a default profile. :paramtype default_connection_profile: ~azure.mgmt.labservices.models.ConnectionProfile @@ -1439,7 +1444,8 @@ def __init__( against. :paramtype linked_lms_instance: str """ - super(LabPlanUpdate, self).__init__(tags=tags, **kwargs) + super().__init__(tags=tags, **kwargs) + self.identity = identity self.default_connection_profile = default_connection_profile self.default_auto_shutdown_profile = default_auto_shutdown_profile self.default_network_profile = default_network_profile @@ -1449,7 +1455,7 @@ def __init__( self.linked_lms_instance = linked_lms_instance -class LabUpdateProperties(msrest.serialization.Model): +class LabUpdateProperties(_serialization.Model): """Properties of a lab resource used for updates. :ivar auto_shutdown_profile: The resource auto shutdown configuration for the lab. This @@ -1475,29 +1481,29 @@ class LabUpdateProperties(msrest.serialization.Model): """ _validation = { - 'lab_plan_id': {'max_length': 2000, 'min_length': 3}, - 'title': {'max_length': 120, 'min_length': 1}, + "lab_plan_id": {"max_length": 2000, "min_length": 3}, + "title": {"max_length": 120, "min_length": 1}, } _attribute_map = { - 'auto_shutdown_profile': {'key': 'autoShutdownProfile', 'type': 'AutoShutdownProfile'}, - 'connection_profile': {'key': 'connectionProfile', 'type': 'ConnectionProfile'}, - 'virtual_machine_profile': {'key': 'virtualMachineProfile', 'type': 'VirtualMachineProfile'}, - 'security_profile': {'key': 'securityProfile', 'type': 'SecurityProfile'}, - 'roster_profile': {'key': 'rosterProfile', 'type': 'RosterProfile'}, - 'lab_plan_id': {'key': 'labPlanId', 'type': 'str'}, - 'title': {'key': 'title', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "auto_shutdown_profile": {"key": "autoShutdownProfile", "type": "AutoShutdownProfile"}, + "connection_profile": {"key": "connectionProfile", "type": "ConnectionProfile"}, + "virtual_machine_profile": {"key": "virtualMachineProfile", "type": "VirtualMachineProfile"}, + "security_profile": {"key": "securityProfile", "type": "SecurityProfile"}, + "roster_profile": {"key": "rosterProfile", "type": "RosterProfile"}, + "lab_plan_id": {"key": "labPlanId", "type": "str"}, + "title": {"key": "title", "type": "str"}, + "description": {"key": "description", "type": "str"}, } def __init__( self, *, - auto_shutdown_profile: Optional["AutoShutdownProfile"] = None, - connection_profile: Optional["ConnectionProfile"] = None, - virtual_machine_profile: Optional["VirtualMachineProfile"] = None, - security_profile: Optional["SecurityProfile"] = None, - roster_profile: Optional["RosterProfile"] = None, + auto_shutdown_profile: Optional["_models.AutoShutdownProfile"] = None, + connection_profile: Optional["_models.ConnectionProfile"] = None, + virtual_machine_profile: Optional["_models.VirtualMachineProfile"] = None, + security_profile: Optional["_models.SecurityProfile"] = None, + roster_profile: Optional["_models.RosterProfile"] = None, lab_plan_id: Optional[str] = None, title: Optional[str] = None, description: Optional[str] = None, @@ -1525,7 +1531,7 @@ def __init__( :keyword description: The description of the lab. :paramtype description: str """ - super(LabUpdateProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.auto_shutdown_profile = auto_shutdown_profile self.connection_profile = connection_profile self.virtual_machine_profile = virtual_machine_profile @@ -1536,7 +1542,7 @@ def __init__( self.description = description -class LabProperties(LabUpdateProperties): +class LabProperties(LabUpdateProperties): # pylint: disable=too-many-instance-attributes """Properties of a lab resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -1561,50 +1567,50 @@ class LabProperties(LabUpdateProperties): :vartype title: str :ivar description: The description of the lab. :vartype description: str - :ivar provisioning_state: Current provisioning state of the lab. Possible values include: - "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Locked". + :ivar provisioning_state: Current provisioning state of the lab. Known values are: "Creating", + "Updating", "Deleting", "Succeeded", "Failed", and "Locked". :vartype provisioning_state: str or ~azure.mgmt.labservices.models.ProvisioningState :ivar network_profile: The network profile for the lab, typically applied via a lab plan. This profile cannot be modified once a lab has been created. :vartype network_profile: ~azure.mgmt.labservices.models.LabNetworkProfile - :ivar state: The lab state. Possible values include: "Draft", "Publishing", "Scaling", - "Syncing", "Published". + :ivar state: The lab state. Known values are: "Draft", "Publishing", "Scaling", "Syncing", and + "Published". :vartype state: str or ~azure.mgmt.labservices.models.LabState """ _validation = { - 'lab_plan_id': {'max_length': 2000, 'min_length': 3}, - 'title': {'max_length': 120, 'min_length': 1}, - 'provisioning_state': {'readonly': True}, - 'state': {'readonly': True}, + "lab_plan_id": {"max_length": 2000, "min_length": 3}, + "title": {"max_length": 120, "min_length": 1}, + "provisioning_state": {"readonly": True}, + "state": {"readonly": True}, } _attribute_map = { - 'auto_shutdown_profile': {'key': 'autoShutdownProfile', 'type': 'AutoShutdownProfile'}, - 'connection_profile': {'key': 'connectionProfile', 'type': 'ConnectionProfile'}, - 'virtual_machine_profile': {'key': 'virtualMachineProfile', 'type': 'VirtualMachineProfile'}, - 'security_profile': {'key': 'securityProfile', 'type': 'SecurityProfile'}, - 'roster_profile': {'key': 'rosterProfile', 'type': 'RosterProfile'}, - 'lab_plan_id': {'key': 'labPlanId', 'type': 'str'}, - 'title': {'key': 'title', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, - 'network_profile': {'key': 'networkProfile', 'type': 'LabNetworkProfile'}, - 'state': {'key': 'state', 'type': 'str'}, + "auto_shutdown_profile": {"key": "autoShutdownProfile", "type": "AutoShutdownProfile"}, + "connection_profile": {"key": "connectionProfile", "type": "ConnectionProfile"}, + "virtual_machine_profile": {"key": "virtualMachineProfile", "type": "VirtualMachineProfile"}, + "security_profile": {"key": "securityProfile", "type": "SecurityProfile"}, + "roster_profile": {"key": "rosterProfile", "type": "RosterProfile"}, + "lab_plan_id": {"key": "labPlanId", "type": "str"}, + "title": {"key": "title", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "network_profile": {"key": "networkProfile", "type": "LabNetworkProfile"}, + "state": {"key": "state", "type": "str"}, } def __init__( self, *, - auto_shutdown_profile: Optional["AutoShutdownProfile"] = None, - connection_profile: Optional["ConnectionProfile"] = None, - virtual_machine_profile: Optional["VirtualMachineProfile"] = None, - security_profile: Optional["SecurityProfile"] = None, - roster_profile: Optional["RosterProfile"] = None, + auto_shutdown_profile: Optional["_models.AutoShutdownProfile"] = None, + connection_profile: Optional["_models.ConnectionProfile"] = None, + virtual_machine_profile: Optional["_models.VirtualMachineProfile"] = None, + security_profile: Optional["_models.SecurityProfile"] = None, + roster_profile: Optional["_models.RosterProfile"] = None, lab_plan_id: Optional[str] = None, title: Optional[str] = None, description: Optional[str] = None, - network_profile: Optional["LabNetworkProfile"] = None, + network_profile: Optional["_models.LabNetworkProfile"] = None, **kwargs ): """ @@ -1632,13 +1638,23 @@ def __init__( This profile cannot be modified once a lab has been created. :paramtype network_profile: ~azure.mgmt.labservices.models.LabNetworkProfile """ - super(LabProperties, self).__init__(auto_shutdown_profile=auto_shutdown_profile, connection_profile=connection_profile, virtual_machine_profile=virtual_machine_profile, security_profile=security_profile, roster_profile=roster_profile, lab_plan_id=lab_plan_id, title=title, description=description, **kwargs) + super().__init__( + auto_shutdown_profile=auto_shutdown_profile, + connection_profile=connection_profile, + virtual_machine_profile=virtual_machine_profile, + security_profile=security_profile, + roster_profile=roster_profile, + lab_plan_id=lab_plan_id, + title=title, + description=description, + **kwargs + ) self.provisioning_state = None self.network_profile = network_profile self.state = None -class LabServicesSku(msrest.serialization.Model): +class LabServicesSku(_serialization.Model): """Azure Lab Services resource SKUs. Variables are only populated by the server, and will be ignored when sending a request. @@ -1647,7 +1663,7 @@ class LabServicesSku(msrest.serialization.Model): :vartype resource_type: str :ivar name: The name of the SKU. :vartype name: str - :ivar tier: The tier of the SKU. Possible values include: "Standard", "Premium". + :ivar tier: The tier of the SKU. Known values are: "Standard" and "Premium". :vartype tier: str or ~azure.mgmt.labservices.models.LabServicesSkuTier :ivar size: The SKU size. :vartype size: str @@ -1666,41 +1682,36 @@ class LabServicesSku(msrest.serialization.Model): """ _validation = { - 'resource_type': {'readonly': True}, - 'name': {'readonly': True}, - 'tier': {'readonly': True}, - 'size': {'readonly': True}, - 'family': {'readonly': True}, - 'capabilities': {'readonly': True}, - 'locations': {'readonly': True}, - 'costs': {'readonly': True}, - 'restrictions': {'readonly': True}, - } - - _attribute_map = { - 'resource_type': {'key': 'resourceType', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'tier': {'key': 'tier', 'type': 'str'}, - 'size': {'key': 'size', 'type': 'str'}, - 'family': {'key': 'family', 'type': 'str'}, - 'capacity': {'key': 'capacity', 'type': 'LabServicesSkuCapacity'}, - 'capabilities': {'key': 'capabilities', 'type': '[LabServicesSkuCapabilities]'}, - 'locations': {'key': 'locations', 'type': '[str]'}, - 'costs': {'key': 'costs', 'type': '[LabServicesSkuCost]'}, - 'restrictions': {'key': 'restrictions', 'type': '[LabServicesSkuRestrictions]'}, + "resource_type": {"readonly": True}, + "name": {"readonly": True}, + "tier": {"readonly": True}, + "size": {"readonly": True}, + "family": {"readonly": True}, + "capabilities": {"readonly": True}, + "locations": {"readonly": True}, + "costs": {"readonly": True}, + "restrictions": {"readonly": True}, } - def __init__( - self, - *, - capacity: Optional["LabServicesSkuCapacity"] = None, - **kwargs - ): + _attribute_map = { + "resource_type": {"key": "resourceType", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "tier": {"key": "tier", "type": "str"}, + "size": {"key": "size", "type": "str"}, + "family": {"key": "family", "type": "str"}, + "capacity": {"key": "capacity", "type": "LabServicesSkuCapacity"}, + "capabilities": {"key": "capabilities", "type": "[LabServicesSkuCapabilities]"}, + "locations": {"key": "locations", "type": "[str]"}, + "costs": {"key": "costs", "type": "[LabServicesSkuCost]"}, + "restrictions": {"key": "restrictions", "type": "[LabServicesSkuRestrictions]"}, + } + + def __init__(self, *, capacity: Optional["_models.LabServicesSkuCapacity"] = None, **kwargs): """ :keyword capacity: The scale out/in options of the SKU. :paramtype capacity: ~azure.mgmt.labservices.models.LabServicesSkuCapacity """ - super(LabServicesSku, self).__init__(**kwargs) + super().__init__(**kwargs) self.resource_type = None self.name = None self.tier = None @@ -1713,7 +1724,7 @@ def __init__( self.restrictions = None -class LabServicesSkuCapabilities(msrest.serialization.Model): +class LabServicesSkuCapabilities(_serialization.Model): """The array of capabilities of a lab services SKU. Variables are only populated by the server, and will be ignored when sending a request. @@ -1725,70 +1736,62 @@ class LabServicesSkuCapabilities(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, - 'value': {'readonly': True}, + "name": {"readonly": True}, + "value": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(LabServicesSkuCapabilities, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.value = None -class LabServicesSkuCapacity(msrest.serialization.Model): +class LabServicesSkuCapacity(_serialization.Model): """The scale out/in options of the SKU. Variables are only populated by the server, and will be ignored when sending a request. :ivar default: The default capacity for this resource. - :vartype default: long + :vartype default: int :ivar minimum: The lowest permitted capacity for this resource. - :vartype minimum: long + :vartype minimum: int :ivar maximum: The highest permitted capacity for this resource. - :vartype maximum: long - :ivar scale_type: The localized name of the resource. Possible values include: "None", - "Manual", "Automatic". + :vartype maximum: int + :ivar scale_type: The localized name of the resource. Known values are: "None", "Manual", and + "Automatic". :vartype scale_type: str or ~azure.mgmt.labservices.models.ScaleType """ _validation = { - 'default': {'readonly': True}, - 'minimum': {'readonly': True}, - 'maximum': {'readonly': True}, - 'scale_type': {'readonly': True}, + "default": {"readonly": True}, + "minimum": {"readonly": True}, + "maximum": {"readonly": True}, + "scale_type": {"readonly": True}, } _attribute_map = { - 'default': {'key': 'default', 'type': 'long'}, - 'minimum': {'key': 'minimum', 'type': 'long'}, - 'maximum': {'key': 'maximum', 'type': 'long'}, - 'scale_type': {'key': 'scaleType', 'type': 'str'}, + "default": {"key": "default", "type": "int"}, + "minimum": {"key": "minimum", "type": "int"}, + "maximum": {"key": "maximum", "type": "int"}, + "scale_type": {"key": "scaleType", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(LabServicesSkuCapacity, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.default = None self.minimum = None self.maximum = None self.scale_type = None -class LabServicesSkuCost(msrest.serialization.Model): +class LabServicesSkuCost(_serialization.Model): """The array of costs of a lab services SKU. Variables are only populated by the server, and will be ignored when sending a request. @@ -1802,62 +1805,54 @@ class LabServicesSkuCost(msrest.serialization.Model): """ _validation = { - 'meter_id': {'readonly': True}, - 'quantity': {'readonly': True}, - 'extended_unit': {'readonly': True}, + "meter_id": {"readonly": True}, + "quantity": {"readonly": True}, + "extended_unit": {"readonly": True}, } _attribute_map = { - 'meter_id': {'key': 'meterId', 'type': 'str'}, - 'quantity': {'key': 'quantity', 'type': 'float'}, - 'extended_unit': {'key': 'extendedUnit', 'type': 'str'}, + "meter_id": {"key": "meterId", "type": "str"}, + "quantity": {"key": "quantity", "type": "float"}, + "extended_unit": {"key": "extendedUnit", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(LabServicesSkuCost, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.meter_id = None self.quantity = None self.extended_unit = None -class LabServicesSkuRestrictions(msrest.serialization.Model): +class LabServicesSkuRestrictions(_serialization.Model): """The restriction details. Variables are only populated by the server, and will be ignored when sending a request. - :ivar type: The type of restriction. Possible values include: "Location". + :ivar type: The type of restriction. "Location" :vartype type: str or ~azure.mgmt.labservices.models.RestrictionType :ivar values: The values of the restriction. :vartype values: list[str] - :ivar reason_code: The reason for the restriction. Possible values include: "QuotaId", + :ivar reason_code: The reason for the restriction. Known values are: "QuotaId" and "NotAvailableForSubscription". :vartype reason_code: str or ~azure.mgmt.labservices.models.RestrictionReasonCode """ _validation = { - 'type': {'readonly': True}, - 'values': {'readonly': True}, - 'reason_code': {'readonly': True}, + "type": {"readonly": True}, + "values": {"readonly": True}, + "reason_code": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'values': {'key': 'values', 'type': '[str]'}, - 'reason_code': {'key': 'reasonCode', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "values": {"key": "values", "type": "[str]"}, + "reason_code": {"key": "reasonCode", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(LabServicesSkuRestrictions, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None self.values = None self.reason_code = None @@ -1866,7 +1861,7 @@ def __init__( class LabUpdate(TrackedResourceUpdate): """The lab resource for updates. - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: list[str] :ivar auto_shutdown_profile: The resource auto shutdown configuration for the lab. This controls whether actions are taken on resources that are sitting idle. @@ -1891,38 +1886,38 @@ class LabUpdate(TrackedResourceUpdate): """ _validation = { - 'lab_plan_id': {'max_length': 2000, 'min_length': 3}, - 'title': {'max_length': 120, 'min_length': 1}, + "lab_plan_id": {"max_length": 2000, "min_length": 3}, + "title": {"max_length": 120, "min_length": 1}, } _attribute_map = { - 'tags': {'key': 'tags', 'type': '[str]'}, - 'auto_shutdown_profile': {'key': 'properties.autoShutdownProfile', 'type': 'AutoShutdownProfile'}, - 'connection_profile': {'key': 'properties.connectionProfile', 'type': 'ConnectionProfile'}, - 'virtual_machine_profile': {'key': 'properties.virtualMachineProfile', 'type': 'VirtualMachineProfile'}, - 'security_profile': {'key': 'properties.securityProfile', 'type': 'SecurityProfile'}, - 'roster_profile': {'key': 'properties.rosterProfile', 'type': 'RosterProfile'}, - 'lab_plan_id': {'key': 'properties.labPlanId', 'type': 'str'}, - 'title': {'key': 'properties.title', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, + "tags": {"key": "tags", "type": "[str]"}, + "auto_shutdown_profile": {"key": "properties.autoShutdownProfile", "type": "AutoShutdownProfile"}, + "connection_profile": {"key": "properties.connectionProfile", "type": "ConnectionProfile"}, + "virtual_machine_profile": {"key": "properties.virtualMachineProfile", "type": "VirtualMachineProfile"}, + "security_profile": {"key": "properties.securityProfile", "type": "SecurityProfile"}, + "roster_profile": {"key": "properties.rosterProfile", "type": "RosterProfile"}, + "lab_plan_id": {"key": "properties.labPlanId", "type": "str"}, + "title": {"key": "properties.title", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, } def __init__( self, *, tags: Optional[List[str]] = None, - auto_shutdown_profile: Optional["AutoShutdownProfile"] = None, - connection_profile: Optional["ConnectionProfile"] = None, - virtual_machine_profile: Optional["VirtualMachineProfile"] = None, - security_profile: Optional["SecurityProfile"] = None, - roster_profile: Optional["RosterProfile"] = None, + auto_shutdown_profile: Optional["_models.AutoShutdownProfile"] = None, + connection_profile: Optional["_models.ConnectionProfile"] = None, + virtual_machine_profile: Optional["_models.VirtualMachineProfile"] = None, + security_profile: Optional["_models.SecurityProfile"] = None, + roster_profile: Optional["_models.RosterProfile"] = None, lab_plan_id: Optional[str] = None, title: Optional[str] = None, description: Optional[str] = None, **kwargs ): """ - :keyword tags: A set of tags. Resource tags. + :keyword tags: Resource tags. :paramtype tags: list[str] :keyword auto_shutdown_profile: The resource auto shutdown configuration for the lab. This controls whether actions are taken on resources that are sitting idle. @@ -1945,7 +1940,7 @@ def __init__( :keyword description: The description of the lab. :paramtype description: str """ - super(LabUpdate, self).__init__(tags=tags, **kwargs) + super().__init__(tags=tags, **kwargs) self.auto_shutdown_profile = auto_shutdown_profile self.connection_profile = connection_profile self.virtual_machine_profile = virtual_machine_profile @@ -1956,7 +1951,7 @@ def __init__( self.description = description -class ListUsagesResult(msrest.serialization.Model): +class ListUsagesResult(_serialization.Model): """List of Core Usages. Variables are only populated by the server, and will be ignored when sending a request. @@ -1968,27 +1963,25 @@ class ListUsagesResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Usage]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Usage]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.Usage"]] = None, **kwargs): """ + :keyword value: The array page of Usages. + :paramtype value: list[~azure.mgmt.labservices.models.Usage] """ - super(ListUsagesResult, self).__init__(**kwargs) - self.value = None + super().__init__(**kwargs) + self.value = value self.next_link = None -class Operation(msrest.serialization.Model): +class Operation(_serialization.Model): """Details of a REST API operation, returned from the Resource Provider Operations API. Variables are only populated by the server, and will be ignored when sending a request. @@ -2002,40 +1995,35 @@ class Operation(msrest.serialization.Model): :ivar display: Localized display information for this particular operation. :vartype display: ~azure.mgmt.labservices.models.OperationDisplay :ivar origin: The intended executor of the operation; as in Resource Based Access Control - (RBAC) and audit logs UX. Default value is "user,system". Possible values include: "user", - "system", "user,system". + (RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system", + and "user,system". :vartype origin: str or ~azure.mgmt.labservices.models.Origin :ivar action_type: Enum. Indicates the action type. "Internal" refers to actions that are for - internal only APIs. Possible values include: "Internal". + internal only APIs. "Internal" :vartype action_type: str or ~azure.mgmt.labservices.models.ActionType """ _validation = { - 'name': {'readonly': True}, - 'is_data_action': {'readonly': True}, - 'origin': {'readonly': True}, - 'action_type': {'readonly': True}, + "name": {"readonly": True}, + "is_data_action": {"readonly": True}, + "origin": {"readonly": True}, + "action_type": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - 'origin': {'key': 'origin', 'type': 'str'}, - 'action_type': {'key': 'actionType', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, + "action_type": {"key": "actionType", "type": "str"}, } - def __init__( - self, - *, - display: Optional["OperationDisplay"] = None, - **kwargs - ): + def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs): """ :keyword display: Localized display information for this particular operation. :paramtype display: ~azure.mgmt.labservices.models.OperationDisplay """ - super(Operation, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = None self.is_data_action = None self.display = display @@ -2043,7 +2031,7 @@ def __init__( self.action_type = None -class OperationDisplay(msrest.serialization.Model): +class OperationDisplay(_serialization.Model): """Localized display information for this particular operation. Variables are only populated by the server, and will be ignored when sending a request. @@ -2063,33 +2051,29 @@ class OperationDisplay(msrest.serialization.Model): """ _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - 'description': {'readonly': True}, + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, } _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(OperationDisplay, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.provider = None self.resource = None self.operation = None self.description = None -class OperationListResult(msrest.serialization.Model): +class OperationListResult(_serialization.Model): """A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. Variables are only populated by the server, and will be ignored when sending a request. @@ -2101,27 +2085,23 @@ class OperationListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(OperationListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class OperationResult(msrest.serialization.Model): +class OperationResult(_serialization.Model): """A long running operation result. Variables are only populated by the server, and will be ignored when sending a request. @@ -2133,8 +2113,8 @@ class OperationResult(msrest.serialization.Model): :vartype id: str :ivar name: The name of the resource. :vartype name: str - :ivar status: Required. The operation status. Possible values include: "NotStarted", - "InProgress", "Succeeded", "Failed", "Canceled". + :ivar status: The operation status. Required. Known values are: "NotStarted", "InProgress", + "Succeeded", "Failed", and "Canceled". :vartype status: str or ~azure.mgmt.labservices.models.OperationStatus :ivar start_time: Start time. :vartype start_time: ~datetime.datetime @@ -2147,34 +2127,34 @@ class OperationResult(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'status': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "status": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, - 'end_time': {'key': 'endTime', 'type': 'iso-8601'}, - 'percent_complete': {'key': 'percentComplete', 'type': 'float'}, - 'error': {'key': 'error', 'type': 'ErrorDetail'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "start_time": {"key": "startTime", "type": "iso-8601"}, + "end_time": {"key": "endTime", "type": "iso-8601"}, + "percent_complete": {"key": "percentComplete", "type": "float"}, + "error": {"key": "error", "type": "ErrorDetail"}, } def __init__( self, *, - status: Union[str, "OperationStatus"], + status: Union[str, "_models.OperationStatus"], start_time: Optional[datetime.datetime] = None, end_time: Optional[datetime.datetime] = None, percent_complete: Optional[float] = None, - error: Optional["ErrorDetail"] = None, + error: Optional["_models.ErrorDetail"] = None, **kwargs ): """ - :keyword status: Required. The operation status. Possible values include: "NotStarted", - "InProgress", "Succeeded", "Failed", "Canceled". + :keyword status: The operation status. Required. Known values are: "NotStarted", "InProgress", + "Succeeded", "Failed", and "Canceled". :paramtype status: str or ~azure.mgmt.labservices.models.OperationStatus :keyword start_time: Start time. :paramtype start_time: ~datetime.datetime @@ -2185,7 +2165,7 @@ def __init__( :keyword error: The error for a failure if the operation failed. :paramtype error: ~azure.mgmt.labservices.models.ErrorDetail """ - super(OperationResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = None self.name = None self.status = status @@ -2195,7 +2175,7 @@ def __init__( self.error = error -class PagedImages(msrest.serialization.Model): +class PagedImages(_serialization.Model): """Paged list of Lab services virtual machine images. Variables are only populated by the server, and will be ignored when sending a request. @@ -2207,27 +2187,23 @@ class PagedImages(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Image]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Image]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(PagedImages, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class PagedLabPlans(msrest.serialization.Model): +class PagedLabPlans(_serialization.Model): """Paged list of lab plans. Variables are only populated by the server, and will be ignored when sending a request. @@ -2239,27 +2215,23 @@ class PagedLabPlans(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[LabPlan]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[LabPlan]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(PagedLabPlans, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class PagedLabs(msrest.serialization.Model): +class PagedLabs(_serialization.Model): """Paged list of labs. Variables are only populated by the server, and will be ignored when sending a request. @@ -2271,27 +2243,23 @@ class PagedLabs(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Lab]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Lab]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(PagedLabs, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class PagedLabServicesSkus(msrest.serialization.Model): +class PagedLabServicesSkus(_serialization.Model): """Paged list of lab services skus. Variables are only populated by the server, and will be ignored when sending a request. @@ -2303,27 +2271,23 @@ class PagedLabServicesSkus(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[LabServicesSku]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[LabServicesSku]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(PagedLabServicesSkus, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class PagedSchedules(msrest.serialization.Model): +class PagedSchedules(_serialization.Model): """Paged list of schedules. Variables are only populated by the server, and will be ignored when sending a request. @@ -2335,27 +2299,23 @@ class PagedSchedules(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Schedule]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Schedule]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(PagedSchedules, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class PagedUsers(msrest.serialization.Model): +class PagedUsers(_serialization.Model): """Paged list of users. Variables are only populated by the server, and will be ignored when sending a request. @@ -2367,27 +2327,23 @@ class PagedUsers(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[User]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[User]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(PagedUsers, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class PagedVirtualMachines(msrest.serialization.Model): +class PagedVirtualMachines(_serialization.Model): """Paged list of lab services virtual machines. Variables are only populated by the server, and will be ignored when sending a request. @@ -2399,32 +2355,28 @@ class PagedVirtualMachines(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[VirtualMachine]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[VirtualMachine]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(PagedVirtualMachines, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class RecurrencePattern(msrest.serialization.Model): +class RecurrencePattern(_serialization.Model): """Recurrence pattern of a lab schedule. All required parameters must be populated in order to send to Azure. - :ivar frequency: Required. The frequency of the recurrence. Possible values include: "Daily", + :ivar frequency: The frequency of the recurrence. Required. Known values are: "Daily" and "Weekly". :vartype frequency: str or ~azure.mgmt.labservices.models.RecurrenceFrequency :ivar week_days: The week days the schedule runs. Used for when the Frequency is set to Weekly. @@ -2433,35 +2385,35 @@ class RecurrencePattern(msrest.serialization.Model): RecurrenceFrequency.Daily will run every 2 days. When no interval is supplied, an interval of 1 is used. :vartype interval: int - :ivar expiration_date: Required. When the recurrence will expire. This date is inclusive. - :vartype expiration_date: ~datetime.date + :ivar expiration_date: When the recurrence will expire. This date is inclusive. Required. + :vartype expiration_date: ~datetime.datetime """ _validation = { - 'frequency': {'required': True}, - 'interval': {'maximum': 365, 'minimum': 1}, - 'expiration_date': {'required': True}, + "frequency": {"required": True}, + "interval": {"maximum": 365, "minimum": 1}, + "expiration_date": {"required": True}, } _attribute_map = { - 'frequency': {'key': 'frequency', 'type': 'str'}, - 'week_days': {'key': 'weekDays', 'type': '[str]'}, - 'interval': {'key': 'interval', 'type': 'int'}, - 'expiration_date': {'key': 'expirationDate', 'type': 'date'}, + "frequency": {"key": "frequency", "type": "str"}, + "week_days": {"key": "weekDays", "type": "[str]"}, + "interval": {"key": "interval", "type": "int"}, + "expiration_date": {"key": "expirationDate", "type": "iso-8601"}, } def __init__( self, *, - frequency: Union[str, "RecurrenceFrequency"], - expiration_date: datetime.date, - week_days: Optional[List[Union[str, "WeekDay"]]] = None, + frequency: Union[str, "_models.RecurrenceFrequency"], + expiration_date: datetime.datetime, + week_days: Optional[List[Union[str, "_models.WeekDay"]]] = None, interval: Optional[int] = None, **kwargs ): """ - :keyword frequency: Required. The frequency of the recurrence. Possible values include: - "Daily", "Weekly". + :keyword frequency: The frequency of the recurrence. Required. Known values are: "Daily" and + "Weekly". :paramtype frequency: str or ~azure.mgmt.labservices.models.RecurrenceFrequency :keyword week_days: The week days the schedule runs. Used for when the Frequency is set to Weekly. @@ -2470,56 +2422,50 @@ def __init__( RecurrenceFrequency.Daily will run every 2 days. When no interval is supplied, an interval of 1 is used. :paramtype interval: int - :keyword expiration_date: Required. When the recurrence will expire. This date is inclusive. - :paramtype expiration_date: ~datetime.date + :keyword expiration_date: When the recurrence will expire. This date is inclusive. Required. + :paramtype expiration_date: ~datetime.datetime """ - super(RecurrencePattern, self).__init__(**kwargs) + super().__init__(**kwargs) self.frequency = frequency self.week_days = week_days self.interval = interval self.expiration_date = expiration_date -class ResetPasswordBody(msrest.serialization.Model): +class ResetPasswordBody(_serialization.Model): """Body of a reset password request. All required parameters must be populated in order to send to Azure. - :ivar username: Required. The user whose password is being reset. + :ivar username: The user whose password is being reset. Required. :vartype username: str - :ivar password: Required. The password. + :ivar password: The password. Required. :vartype password: str """ _validation = { - 'username': {'required': True}, - 'password': {'required': True}, + "username": {"required": True}, + "password": {"required": True}, } _attribute_map = { - 'username': {'key': 'username', 'type': 'str'}, - 'password': {'key': 'password', 'type': 'str'}, + "username": {"key": "username", "type": "str"}, + "password": {"key": "password", "type": "str"}, } - def __init__( - self, - *, - username: str, - password: str, - **kwargs - ): + def __init__(self, *, username: str, password: str, **kwargs): """ - :keyword username: Required. The user whose password is being reset. + :keyword username: The user whose password is being reset. Required. :paramtype username: str - :keyword password: Required. The password. + :keyword password: The password. Required. :paramtype password: str """ - super(ResetPasswordBody, self).__init__(**kwargs) + super().__init__(**kwargs) self.username = username self.password = password -class RosterProfile(msrest.serialization.Model): +class RosterProfile(_serialization.Model): """The lab user list management profile. :ivar active_directory_group_id: The AAD group ID which this lab roster is populated from. @@ -2537,11 +2483,11 @@ class attached to this lab. """ _attribute_map = { - 'active_directory_group_id': {'key': 'activeDirectoryGroupId', 'type': 'str'}, - 'lti_context_id': {'key': 'ltiContextId', 'type': 'str'}, - 'lms_instance': {'key': 'lmsInstance', 'type': 'str'}, - 'lti_client_id': {'key': 'ltiClientId', 'type': 'str'}, - 'lti_roster_endpoint': {'key': 'ltiRosterEndpoint', 'type': 'str'}, + "active_directory_group_id": {"key": "activeDirectoryGroupId", "type": "str"}, + "lti_context_id": {"key": "ltiContextId", "type": "str"}, + "lms_instance": {"key": "lmsInstance", "type": "str"}, + "lti_client_id": {"key": "ltiClientId", "type": "str"}, + "lti_roster_endpoint": {"key": "ltiRosterEndpoint", "type": "str"}, } def __init__( @@ -2568,7 +2514,7 @@ def __init__( the class attached to this lab. :paramtype lti_roster_endpoint: str """ - super(RosterProfile, self).__init__(**kwargs) + super().__init__(**kwargs) self.active_directory_group_id = active_directory_group_id self.lti_context_id = lti_context_id self.lms_instance = lms_instance @@ -2576,7 +2522,7 @@ def __init__( self.lti_roster_endpoint = lti_roster_endpoint -class SaveImageBody(msrest.serialization.Model): +class SaveImageBody(_serialization.Model): """Body for the save image POST. :ivar name: The name for the image we create. @@ -2586,21 +2532,15 @@ class SaveImageBody(msrest.serialization.Model): """ _validation = { - 'lab_virtual_machine_id': {'max_length': 2000, 'min_length': 3}, + "lab_virtual_machine_id": {"max_length": 2000, "min_length": 3}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'lab_virtual_machine_id': {'key': 'labVirtualMachineId', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "lab_virtual_machine_id": {"key": "labVirtualMachineId", "type": "str"}, } - def __init__( - self, - *, - name: Optional[str] = None, - lab_virtual_machine_id: Optional[str] = None, - **kwargs - ): + def __init__(self, *, name: Optional[str] = None, lab_virtual_machine_id: Optional[str] = None, **kwargs): """ :keyword name: The name for the image we create. :paramtype name: str @@ -2608,7 +2548,7 @@ def __init__( from. :paramtype lab_virtual_machine_id: str """ - super(SaveImageBody, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.lab_virtual_machine_id = lab_virtual_machine_id @@ -2640,32 +2580,32 @@ class Schedule(ProxyResource): :vartype time_zone_id: str :ivar notes: Notes for this schedule. :vartype notes: str - :ivar provisioning_state: Current provisioning state of the schedule. Possible values include: - "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Locked". + :ivar provisioning_state: Current provisioning state of the schedule. Known values are: + "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Locked". :vartype provisioning_state: str or ~azure.mgmt.labservices.models.ProvisioningState """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - 'time_zone_id': {'max_length': 50, 'min_length': 0}, - 'notes': {'max_length': 1000, 'min_length': 0}, - 'provisioning_state': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "time_zone_id": {"max_length": 50}, + "notes": {"max_length": 1000}, + "provisioning_state": {"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'}, - 'start_at': {'key': 'properties.startAt', 'type': 'iso-8601'}, - 'stop_at': {'key': 'properties.stopAt', 'type': 'iso-8601'}, - 'recurrence_pattern': {'key': 'properties.recurrencePattern', 'type': 'RecurrencePattern'}, - 'time_zone_id': {'key': 'properties.timeZoneId', 'type': 'str'}, - 'notes': {'key': 'properties.notes', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "start_at": {"key": "properties.startAt", "type": "iso-8601"}, + "stop_at": {"key": "properties.stopAt", "type": "iso-8601"}, + "recurrence_pattern": {"key": "properties.recurrencePattern", "type": "RecurrencePattern"}, + "time_zone_id": {"key": "properties.timeZoneId", "type": "str"}, + "notes": {"key": "properties.notes", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, } def __init__( @@ -2673,7 +2613,7 @@ def __init__( *, start_at: Optional[datetime.datetime] = None, stop_at: Optional[datetime.datetime] = None, - recurrence_pattern: Optional["RecurrencePattern"] = None, + recurrence_pattern: Optional["_models.RecurrencePattern"] = None, time_zone_id: Optional[str] = None, notes: Optional[str] = None, **kwargs @@ -2692,7 +2632,7 @@ def __init__( :keyword notes: Notes for this schedule. :paramtype notes: str """ - super(Schedule, self).__init__(**kwargs) + super().__init__(**kwargs) self.system_data = None self.start_at = start_at self.stop_at = stop_at @@ -2702,7 +2642,7 @@ def __init__( self.provisioning_state = None -class ScheduleUpdateProperties(msrest.serialization.Model): +class ScheduleUpdateProperties(_serialization.Model): """Schedule resource properties used for updates. :ivar start_at: When lab user virtual machines will be started. Timestamp offsets will be @@ -2720,16 +2660,16 @@ class ScheduleUpdateProperties(msrest.serialization.Model): """ _validation = { - 'time_zone_id': {'max_length': 50, 'min_length': 0}, - 'notes': {'max_length': 1000, 'min_length': 0}, + "time_zone_id": {"max_length": 50}, + "notes": {"max_length": 1000}, } _attribute_map = { - 'start_at': {'key': 'startAt', 'type': 'iso-8601'}, - 'stop_at': {'key': 'stopAt', 'type': 'iso-8601'}, - 'recurrence_pattern': {'key': 'recurrencePattern', 'type': 'RecurrencePattern'}, - 'time_zone_id': {'key': 'timeZoneId', 'type': 'str'}, - 'notes': {'key': 'notes', 'type': 'str'}, + "start_at": {"key": "startAt", "type": "iso-8601"}, + "stop_at": {"key": "stopAt", "type": "iso-8601"}, + "recurrence_pattern": {"key": "recurrencePattern", "type": "RecurrencePattern"}, + "time_zone_id": {"key": "timeZoneId", "type": "str"}, + "notes": {"key": "notes", "type": "str"}, } def __init__( @@ -2737,7 +2677,7 @@ def __init__( *, start_at: Optional[datetime.datetime] = None, stop_at: Optional[datetime.datetime] = None, - recurrence_pattern: Optional["RecurrencePattern"] = None, + recurrence_pattern: Optional["_models.RecurrencePattern"] = None, time_zone_id: Optional[str] = None, notes: Optional[str] = None, **kwargs @@ -2756,7 +2696,7 @@ def __init__( :keyword notes: Notes for this schedule. :paramtype notes: str """ - super(ScheduleUpdateProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.start_at = start_at self.stop_at = stop_at self.recurrence_pattern = recurrence_pattern @@ -2781,24 +2721,24 @@ class ScheduleProperties(ScheduleUpdateProperties): :vartype time_zone_id: str :ivar notes: Notes for this schedule. :vartype notes: str - :ivar provisioning_state: Current provisioning state of the schedule. Possible values include: - "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Locked". + :ivar provisioning_state: Current provisioning state of the schedule. Known values are: + "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Locked". :vartype provisioning_state: str or ~azure.mgmt.labservices.models.ProvisioningState """ _validation = { - 'time_zone_id': {'max_length': 50, 'min_length': 0}, - 'notes': {'max_length': 1000, 'min_length': 0}, - 'provisioning_state': {'readonly': True}, + "time_zone_id": {"max_length": 50}, + "notes": {"max_length": 1000}, + "provisioning_state": {"readonly": True}, } _attribute_map = { - 'start_at': {'key': 'startAt', 'type': 'iso-8601'}, - 'stop_at': {'key': 'stopAt', 'type': 'iso-8601'}, - 'recurrence_pattern': {'key': 'recurrencePattern', 'type': 'RecurrencePattern'}, - 'time_zone_id': {'key': 'timeZoneId', 'type': 'str'}, - 'notes': {'key': 'notes', 'type': 'str'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, + "start_at": {"key": "startAt", "type": "iso-8601"}, + "stop_at": {"key": "stopAt", "type": "iso-8601"}, + "recurrence_pattern": {"key": "recurrencePattern", "type": "RecurrencePattern"}, + "time_zone_id": {"key": "timeZoneId", "type": "str"}, + "notes": {"key": "notes", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, } def __init__( @@ -2806,7 +2746,7 @@ def __init__( *, start_at: Optional[datetime.datetime] = None, stop_at: Optional[datetime.datetime] = None, - recurrence_pattern: Optional["RecurrencePattern"] = None, + recurrence_pattern: Optional["_models.RecurrencePattern"] = None, time_zone_id: Optional[str] = None, notes: Optional[str] = None, **kwargs @@ -2825,11 +2765,18 @@ def __init__( :keyword notes: Notes for this schedule. :paramtype notes: str """ - super(ScheduleProperties, self).__init__(start_at=start_at, stop_at=stop_at, recurrence_pattern=recurrence_pattern, time_zone_id=time_zone_id, notes=notes, **kwargs) + super().__init__( + start_at=start_at, + stop_at=stop_at, + recurrence_pattern=recurrence_pattern, + time_zone_id=time_zone_id, + notes=notes, + **kwargs + ) self.provisioning_state = None -class ScheduleUpdate(msrest.serialization.Model): +class ScheduleUpdate(_serialization.Model): """Schedule for automatically turning virtual machines in a lab on and off at specified times. Used for updates. :ivar start_at: When lab user virtual machines will be started. Timestamp offsets will be @@ -2847,16 +2794,16 @@ class ScheduleUpdate(msrest.serialization.Model): """ _validation = { - 'time_zone_id': {'max_length': 50, 'min_length': 0}, - 'notes': {'max_length': 1000, 'min_length': 0}, + "time_zone_id": {"max_length": 50}, + "notes": {"max_length": 1000}, } _attribute_map = { - 'start_at': {'key': 'properties.startAt', 'type': 'iso-8601'}, - 'stop_at': {'key': 'properties.stopAt', 'type': 'iso-8601'}, - 'recurrence_pattern': {'key': 'properties.recurrencePattern', 'type': 'RecurrencePattern'}, - 'time_zone_id': {'key': 'properties.timeZoneId', 'type': 'str'}, - 'notes': {'key': 'properties.notes', 'type': 'str'}, + "start_at": {"key": "properties.startAt", "type": "iso-8601"}, + "stop_at": {"key": "properties.stopAt", "type": "iso-8601"}, + "recurrence_pattern": {"key": "properties.recurrencePattern", "type": "RecurrencePattern"}, + "time_zone_id": {"key": "properties.timeZoneId", "type": "str"}, + "notes": {"key": "properties.notes", "type": "str"}, } def __init__( @@ -2864,7 +2811,7 @@ def __init__( *, start_at: Optional[datetime.datetime] = None, stop_at: Optional[datetime.datetime] = None, - recurrence_pattern: Optional["RecurrencePattern"] = None, + recurrence_pattern: Optional["_models.RecurrencePattern"] = None, time_zone_id: Optional[str] = None, notes: Optional[str] = None, **kwargs @@ -2883,7 +2830,7 @@ def __init__( :keyword notes: Notes for this schedule. :paramtype notes: str """ - super(ScheduleUpdate, self).__init__(**kwargs) + super().__init__(**kwargs) self.start_at = start_at self.stop_at = stop_at self.recurrence_pattern = recurrence_pattern @@ -2891,53 +2838,48 @@ def __init__( self.notes = notes -class SecurityProfile(msrest.serialization.Model): +class SecurityProfile(_serialization.Model): """The lab security profile. Variables are only populated by the server, and will be ignored when sending a request. :ivar registration_code: The registration code for the lab. :vartype registration_code: str - :ivar open_access: Whether any user or only specified users can register to a lab. Possible - values include: "Enabled", "Disabled". + :ivar open_access: Whether any user or only specified users can register to a lab. Known values + are: "Enabled" and "Disabled". :vartype open_access: str or ~azure.mgmt.labservices.models.EnableState """ _validation = { - 'registration_code': {'readonly': True}, + "registration_code": {"readonly": True}, } _attribute_map = { - 'registration_code': {'key': 'registrationCode', 'type': 'str'}, - 'open_access': {'key': 'openAccess', 'type': 'str'}, + "registration_code": {"key": "registrationCode", "type": "str"}, + "open_access": {"key": "openAccess", "type": "str"}, } - def __init__( - self, - *, - open_access: Optional[Union[str, "EnableState"]] = None, - **kwargs - ): + def __init__(self, *, open_access: Optional[Union[str, "_models.EnableState"]] = None, **kwargs): """ - :keyword open_access: Whether any user or only specified users can register to a lab. Possible - values include: "Enabled", "Disabled". + :keyword open_access: Whether any user or only specified users can register to a lab. Known + values are: "Enabled" and "Disabled". :paramtype open_access: str or ~azure.mgmt.labservices.models.EnableState """ - super(SecurityProfile, self).__init__(**kwargs) + super().__init__(**kwargs) self.registration_code = None self.open_access = open_access -class Sku(msrest.serialization.Model): +class Sku(_serialization.Model): """The resource model definition representing SKU. All required parameters must be populated in order to send to Azure. - :ivar name: Required. The name of the SKU. Ex - P3. It is typically a letter+number code. + :ivar name: The name of the SKU. Ex - P3. It is typically a letter+number code. Required. :vartype name: str :ivar tier: This field is required to be implemented by the Resource Provider if the service - has more than one tier, but is not required on a PUT. Possible values include: "Free", "Basic", - "Standard", "Premium". + has more than one tier, but is not required on a PUT. Known values are: "Free", "Basic", + "Standard", and "Premium". :vartype tier: str or ~azure.mgmt.labservices.models.SkuTier :ivar size: The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. @@ -2951,33 +2893,33 @@ class Sku(msrest.serialization.Model): """ _validation = { - 'name': {'required': True}, + "name": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'tier': {'key': 'tier', 'type': 'str'}, - 'size': {'key': 'size', 'type': 'str'}, - 'family': {'key': 'family', 'type': 'str'}, - 'capacity': {'key': 'capacity', 'type': 'int'}, + "name": {"key": "name", "type": "str"}, + "tier": {"key": "tier", "type": "str"}, + "size": {"key": "size", "type": "str"}, + "family": {"key": "family", "type": "str"}, + "capacity": {"key": "capacity", "type": "int"}, } def __init__( self, *, name: str, - tier: Optional[Union[str, "SkuTier"]] = None, + tier: Optional[Union[str, "_models.SkuTier"]] = None, size: Optional[str] = None, family: Optional[str] = None, capacity: Optional[int] = None, **kwargs ): """ - :keyword name: Required. The name of the SKU. Ex - P3. It is typically a letter+number code. + :keyword name: The name of the SKU. Ex - P3. It is typically a letter+number code. Required. :paramtype name: str :keyword tier: This field is required to be implemented by the Resource Provider if the service - has more than one tier, but is not required on a PUT. Possible values include: "Free", "Basic", - "Standard", "Premium". + has more than one tier, but is not required on a PUT. Known values are: "Free", "Basic", + "Standard", and "Premium". :paramtype tier: str or ~azure.mgmt.labservices.models.SkuTier :keyword size: The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. @@ -2989,7 +2931,7 @@ def __init__( included. If scale out/in is not possible for the resource this may be omitted. :paramtype capacity: int """ - super(Sku, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.tier = tier self.size = size @@ -2997,7 +2939,7 @@ def __init__( self.capacity = capacity -class SupportInfo(msrest.serialization.Model): +class SupportInfo(_serialization.Model): """Support contact information and instructions. :ivar url: Support web address. @@ -3011,16 +2953,16 @@ class SupportInfo(msrest.serialization.Model): """ _validation = { - 'url': {'max_length': 2000, 'min_length': 3}, - 'email': {'max_length': 254, 'min_length': 6}, - 'phone': {'max_length': 31, 'min_length': 1}, + "url": {"max_length": 2000, "min_length": 3}, + "email": {"max_length": 254, "min_length": 6}, + "phone": {"max_length": 31, "min_length": 1}, } _attribute_map = { - 'url': {'key': 'url', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, - 'phone': {'key': 'phone', 'type': 'str'}, - 'instructions': {'key': 'instructions', 'type': 'str'}, + "url": {"key": "url", "type": "str"}, + "email": {"key": "email", "type": "str"}, + "phone": {"key": "phone", "type": "str"}, + "instructions": {"key": "instructions", "type": "str"}, } def __init__( @@ -3042,69 +2984,69 @@ def __init__( :keyword instructions: Support instructions. :paramtype instructions: str """ - super(SupportInfo, self).__init__(**kwargs) + super().__init__(**kwargs) self.url = url self.email = email self.phone = phone self.instructions = instructions -class SystemData(msrest.serialization.Model): +class SystemData(_serialization.Model): """Metadata pertaining to creation and last modification of the resource. :ivar created_by: The identity that created the resource. :vartype created_by: str - :ivar created_by_type: The type of identity that created the resource. Possible values include: - "User", "Application", "ManagedIdentity", "Key". + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". :vartype created_by_type: str or ~azure.mgmt.labservices.models.CreatedByType :ivar created_at: The timestamp of resource creation (UTC). :vartype created_at: ~datetime.datetime :ivar last_modified_by: The identity that last modified the resource. :vartype last_modified_by: str - :ivar last_modified_by_type: The type of identity that last modified the resource. Possible - values include: "User", "Application", "ManagedIdentity", "Key". + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". :vartype last_modified_by_type: str or ~azure.mgmt.labservices.models.CreatedByType :ivar last_modified_at: The timestamp of resource last modification (UTC). :vartype last_modified_at: ~datetime.datetime """ _attribute_map = { - 'created_by': {'key': 'createdBy', 'type': 'str'}, - 'created_by_type': {'key': 'createdByType', 'type': 'str'}, - 'created_at': {'key': 'createdAt', 'type': 'iso-8601'}, - 'last_modified_by': {'key': 'lastModifiedBy', 'type': 'str'}, - 'last_modified_by_type': {'key': 'lastModifiedByType', 'type': 'str'}, - 'last_modified_at': {'key': 'lastModifiedAt', 'type': 'iso-8601'}, + "created_by": {"key": "createdBy", "type": "str"}, + "created_by_type": {"key": "createdByType", "type": "str"}, + "created_at": {"key": "createdAt", "type": "iso-8601"}, + "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, + "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, } def __init__( self, *, created_by: Optional[str] = None, - created_by_type: Optional[Union[str, "CreatedByType"]] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, created_at: Optional[datetime.datetime] = None, last_modified_by: Optional[str] = None, - last_modified_by_type: Optional[Union[str, "CreatedByType"]] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, last_modified_at: Optional[datetime.datetime] = None, **kwargs ): """ :keyword created_by: The identity that created the resource. :paramtype created_by: str - :keyword created_by_type: The type of identity that created the resource. Possible values - include: "User", "Application", "ManagedIdentity", "Key". + :keyword created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". :paramtype created_by_type: str or ~azure.mgmt.labservices.models.CreatedByType :keyword created_at: The timestamp of resource creation (UTC). :paramtype created_at: ~datetime.datetime :keyword last_modified_by: The identity that last modified the resource. :paramtype last_modified_by: str - :keyword last_modified_by_type: The type of identity that last modified the resource. Possible - values include: "User", "Application", "ManagedIdentity", "Key". + :keyword last_modified_by_type: The type of identity that last modified the resource. Known + values are: "User", "Application", "ManagedIdentity", and "Key". :paramtype last_modified_by_type: str or ~azure.mgmt.labservices.models.CreatedByType :keyword last_modified_at: The timestamp of resource last modification (UTC). :paramtype last_modified_at: ~datetime.datetime """ - super(SystemData, self).__init__(**kwargs) + super().__init__(**kwargs) self.created_by = created_by self.created_by_type = created_by_type self.created_at = created_at @@ -3113,14 +3055,14 @@ def __init__( self.last_modified_at = last_modified_at -class Usage(msrest.serialization.Model): +class Usage(_serialization.Model): """The core usage details. :ivar current_value: The current usage. - :vartype current_value: long + :vartype current_value: int :ivar limit: The limit integer. - :vartype limit: long - :ivar unit: The unit details. Possible values include: "Count". + :vartype limit: int + :ivar unit: The unit details. "Count" :vartype unit: str or ~azure.mgmt.labservices.models.UsageUnit :ivar name: The name. :vartype name: ~azure.mgmt.labservices.models.UsageName @@ -3129,11 +3071,11 @@ class Usage(msrest.serialization.Model): """ _attribute_map = { - 'current_value': {'key': 'currentValue', 'type': 'long'}, - 'limit': {'key': 'limit', 'type': 'long'}, - 'unit': {'key': 'unit', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'UsageName'}, - 'id': {'key': 'id', 'type': 'str'}, + "current_value": {"key": "currentValue", "type": "int"}, + "limit": {"key": "limit", "type": "int"}, + "unit": {"key": "unit", "type": "str"}, + "name": {"key": "name", "type": "UsageName"}, + "id": {"key": "id", "type": "str"}, } def __init__( @@ -3141,24 +3083,24 @@ def __init__( *, current_value: Optional[int] = None, limit: Optional[int] = None, - unit: Optional[Union[str, "UsageUnit"]] = None, - name: Optional["UsageName"] = None, - id: Optional[str] = None, + unit: Optional[Union[str, "_models.UsageUnit"]] = None, + name: Optional["_models.UsageName"] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin **kwargs ): """ :keyword current_value: The current usage. - :paramtype current_value: long + :paramtype current_value: int :keyword limit: The limit integer. - :paramtype limit: long - :keyword unit: The unit details. Possible values include: "Count". + :paramtype limit: int + :keyword unit: The unit details. "Count" :paramtype unit: str or ~azure.mgmt.labservices.models.UsageUnit :keyword name: The name. :paramtype name: ~azure.mgmt.labservices.models.UsageName :keyword id: The fully qualified arm resource id. :paramtype id: str """ - super(Usage, self).__init__(**kwargs) + super().__init__(**kwargs) self.current_value = current_value self.limit = limit self.unit = unit @@ -3166,39 +3108,46 @@ def __init__( self.id = id -class UsageName(msrest.serialization.Model): +class UsageName(_serialization.Model): """The Usage Names. :ivar localized_value: The localized name of the resource. :vartype localized_value: str + :ivar sku_instances: The instances of the resource. + :vartype sku_instances: list[str] :ivar value: The name of the resource. :vartype value: str """ _attribute_map = { - 'localized_value': {'key': 'localizedValue', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, + "localized_value": {"key": "localizedValue", "type": "str"}, + "sku_instances": {"key": "skuInstances", "type": "[str]"}, + "value": {"key": "value", "type": "str"}, } def __init__( self, *, localized_value: Optional[str] = None, + sku_instances: Optional[List[str]] = None, value: Optional[str] = None, **kwargs ): """ :keyword localized_value: The localized name of the resource. :paramtype localized_value: str + :keyword sku_instances: The instances of the resource. + :paramtype sku_instances: list[str] :keyword value: The name of the resource. :paramtype value: str """ - super(UsageName, self).__init__(**kwargs) + super().__init__(**kwargs) self.localized_value = localized_value + self.sku_instances = sku_instances self.value = value -class User(ProxyResource): +class User(ProxyResource): # pylint: disable=too-many-instance-attributes """User of a lab that can register for and use virtual machines within the lab. Variables are only populated by the server, and will be ignored when sending a request. @@ -3218,18 +3167,18 @@ class User(ProxyResource): :ivar additional_usage_quota: The amount of usage quota time the user gets in addition to the lab usage quota. :vartype additional_usage_quota: ~datetime.timedelta - :ivar provisioning_state: Current provisioning state of the user resource. Possible values - include: "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Locked". + :ivar provisioning_state: Current provisioning state of the user resource. Known values are: + "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Locked". :vartype provisioning_state: str or ~azure.mgmt.labservices.models.ProvisioningState :ivar display_name: Display name of the user, for example user's full name. :vartype display_name: str - :ivar email: Required. Email address of the user. + :ivar email: Email address of the user. Required. :vartype email: str - :ivar registration_state: State of the user's registration within the lab. Possible values - include: "Registered", "NotRegistered". + :ivar registration_state: State of the user's registration within the lab. Known values are: + "Registered" and "NotRegistered". :vartype registration_state: str or ~azure.mgmt.labservices.models.RegistrationState - :ivar invitation_state: State of the invitation message for the user. Possible values include: - "NotSent", "Sending", "Sent", "Failed". + :ivar invitation_state: State of the invitation message for the user. Known values are: + "NotSent", "Sending", "Sent", and "Failed". :vartype invitation_state: str or ~azure.mgmt.labservices.models.InvitationState :ivar invitation_sent: Date and time when the invitation message was sent to the user. :vartype invitation_sent: ~datetime.datetime @@ -3238,49 +3187,43 @@ class User(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'display_name': {'readonly': True}, - 'email': {'required': True, 'max_length': 254, 'min_length': 6}, - 'registration_state': {'readonly': True}, - 'invitation_state': {'readonly': True}, - 'invitation_sent': {'readonly': True}, - 'total_usage': {'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'}, - 'additional_usage_quota': {'key': 'properties.additionalUsageQuota', 'type': 'duration'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'email': {'key': 'properties.email', 'type': 'str'}, - 'registration_state': {'key': 'properties.registrationState', 'type': 'str'}, - 'invitation_state': {'key': 'properties.invitationState', 'type': 'str'}, - 'invitation_sent': {'key': 'properties.invitationSent', 'type': 'iso-8601'}, - 'total_usage': {'key': 'properties.totalUsage', 'type': 'duration'}, - } - - def __init__( - self, - *, - email: str, - additional_usage_quota: Optional[datetime.timedelta] = None, - **kwargs - ): + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "display_name": {"readonly": True}, + "email": {"required": True, "max_length": 254, "min_length": 6}, + "registration_state": {"readonly": True}, + "invitation_state": {"readonly": True}, + "invitation_sent": {"readonly": True}, + "total_usage": {"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"}, + "additional_usage_quota": {"key": "properties.additionalUsageQuota", "type": "duration"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "email": {"key": "properties.email", "type": "str"}, + "registration_state": {"key": "properties.registrationState", "type": "str"}, + "invitation_state": {"key": "properties.invitationState", "type": "str"}, + "invitation_sent": {"key": "properties.invitationSent", "type": "iso-8601"}, + "total_usage": {"key": "properties.totalUsage", "type": "duration"}, + } + + def __init__(self, *, email: str, additional_usage_quota: Optional[datetime.timedelta] = None, **kwargs): """ :keyword additional_usage_quota: The amount of usage quota time the user gets in addition to the lab usage quota. :paramtype additional_usage_quota: ~datetime.timedelta - :keyword email: Required. Email address of the user. + :keyword email: Email address of the user. Required. :paramtype email: str """ - super(User, self).__init__(**kwargs) + super().__init__(**kwargs) self.system_data = None self.additional_usage_quota = additional_usage_quota self.provisioning_state = None @@ -3292,7 +3235,7 @@ def __init__( self.total_usage = None -class UserUpdateProperties(msrest.serialization.Model): +class UserUpdateProperties(_serialization.Model): """User resource properties used for updates. :ivar additional_usage_quota: The amount of usage quota time the user gets in addition to the @@ -3301,21 +3244,16 @@ class UserUpdateProperties(msrest.serialization.Model): """ _attribute_map = { - 'additional_usage_quota': {'key': 'additionalUsageQuota', 'type': 'duration'}, + "additional_usage_quota": {"key": "additionalUsageQuota", "type": "duration"}, } - def __init__( - self, - *, - additional_usage_quota: Optional[datetime.timedelta] = None, - **kwargs - ): + def __init__(self, *, additional_usage_quota: Optional[datetime.timedelta] = None, **kwargs): """ :keyword additional_usage_quota: The amount of usage quota time the user gets in addition to the lab usage quota. :paramtype additional_usage_quota: ~datetime.timedelta """ - super(UserUpdateProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.additional_usage_quota = additional_usage_quota @@ -3329,18 +3267,18 @@ class UserProperties(UserUpdateProperties): :ivar additional_usage_quota: The amount of usage quota time the user gets in addition to the lab usage quota. :vartype additional_usage_quota: ~datetime.timedelta - :ivar provisioning_state: Current provisioning state of the user resource. Possible values - include: "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Locked". + :ivar provisioning_state: Current provisioning state of the user resource. Known values are: + "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Locked". :vartype provisioning_state: str or ~azure.mgmt.labservices.models.ProvisioningState :ivar display_name: Display name of the user, for example user's full name. :vartype display_name: str - :ivar email: Required. Email address of the user. + :ivar email: Email address of the user. Required. :vartype email: str - :ivar registration_state: State of the user's registration within the lab. Possible values - include: "Registered", "NotRegistered". + :ivar registration_state: State of the user's registration within the lab. Known values are: + "Registered" and "NotRegistered". :vartype registration_state: str or ~azure.mgmt.labservices.models.RegistrationState - :ivar invitation_state: State of the invitation message for the user. Possible values include: - "NotSent", "Sending", "Sent", "Failed". + :ivar invitation_state: State of the invitation message for the user. Known values are: + "NotSent", "Sending", "Sent", and "Failed". :vartype invitation_state: str or ~azure.mgmt.labservices.models.InvitationState :ivar invitation_sent: Date and time when the invitation message was sent to the user. :vartype invitation_sent: ~datetime.datetime @@ -3349,41 +3287,35 @@ class UserProperties(UserUpdateProperties): """ _validation = { - 'provisioning_state': {'readonly': True}, - 'display_name': {'readonly': True}, - 'email': {'required': True, 'max_length': 254, 'min_length': 6}, - 'registration_state': {'readonly': True}, - 'invitation_state': {'readonly': True}, - 'invitation_sent': {'readonly': True}, - 'total_usage': {'readonly': True}, + "provisioning_state": {"readonly": True}, + "display_name": {"readonly": True}, + "email": {"required": True, "max_length": 254, "min_length": 6}, + "registration_state": {"readonly": True}, + "invitation_state": {"readonly": True}, + "invitation_sent": {"readonly": True}, + "total_usage": {"readonly": True}, } _attribute_map = { - 'additional_usage_quota': {'key': 'additionalUsageQuota', 'type': 'duration'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, - 'registration_state': {'key': 'registrationState', 'type': 'str'}, - 'invitation_state': {'key': 'invitationState', 'type': 'str'}, - 'invitation_sent': {'key': 'invitationSent', 'type': 'iso-8601'}, - 'total_usage': {'key': 'totalUsage', 'type': 'duration'}, + "additional_usage_quota": {"key": "additionalUsageQuota", "type": "duration"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "email": {"key": "email", "type": "str"}, + "registration_state": {"key": "registrationState", "type": "str"}, + "invitation_state": {"key": "invitationState", "type": "str"}, + "invitation_sent": {"key": "invitationSent", "type": "iso-8601"}, + "total_usage": {"key": "totalUsage", "type": "duration"}, } - def __init__( - self, - *, - email: str, - additional_usage_quota: Optional[datetime.timedelta] = None, - **kwargs - ): + def __init__(self, *, email: str, additional_usage_quota: Optional[datetime.timedelta] = None, **kwargs): """ :keyword additional_usage_quota: The amount of usage quota time the user gets in addition to the lab usage quota. :paramtype additional_usage_quota: ~datetime.timedelta - :keyword email: Required. Email address of the user. + :keyword email: Email address of the user. Required. :paramtype email: str """ - super(UserProperties, self).__init__(additional_usage_quota=additional_usage_quota, **kwargs) + super().__init__(additional_usage_quota=additional_usage_quota, **kwargs) self.provisioning_state = None self.display_name = None self.email = email @@ -3393,7 +3325,7 @@ def __init__( self.total_usage = None -class UserUpdate(msrest.serialization.Model): +class UserUpdate(_serialization.Model): """User of a lab that can register for and use virtual machines within the lab. Used for updates. :ivar additional_usage_quota: The amount of usage quota time the user gets in addition to the @@ -3402,21 +3334,16 @@ class UserUpdate(msrest.serialization.Model): """ _attribute_map = { - 'additional_usage_quota': {'key': 'properties.additionalUsageQuota', 'type': 'duration'}, + "additional_usage_quota": {"key": "properties.additionalUsageQuota", "type": "duration"}, } - def __init__( - self, - *, - additional_usage_quota: Optional[datetime.timedelta] = None, - **kwargs - ): + def __init__(self, *, additional_usage_quota: Optional[datetime.timedelta] = None, **kwargs): """ :keyword additional_usage_quota: The amount of usage quota time the user gets in addition to the lab usage quota. :paramtype additional_usage_quota: ~datetime.timedelta """ - super(UserUpdate, self).__init__(**kwargs) + super().__init__(**kwargs) self.additional_usage_quota = additional_usage_quota @@ -3435,51 +3362,47 @@ class VirtualMachine(ProxyResource): :vartype type: str :ivar system_data: System data of the Lab virtual machine. :vartype system_data: ~azure.mgmt.labservices.models.SystemData - :ivar provisioning_state: Current provisioning state of the virtual machine. Possible values - include: "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Locked". + :ivar provisioning_state: Current provisioning state of the virtual machine. Known values are: + "Creating", "Updating", "Deleting", "Succeeded", "Failed", and "Locked". :vartype provisioning_state: str or ~azure.mgmt.labservices.models.ProvisioningState - :ivar state: The current state of the virtual machine. Possible values include: "Stopped", - "Starting", "Running", "Stopping", "ResettingPassword", "Reimaging", "Redeploying". + :ivar state: The current state of the virtual machine. Known values are: "Stopped", "Starting", + "Running", "Stopping", "ResettingPassword", "Reimaging", and "Redeploying". :vartype state: str or ~azure.mgmt.labservices.models.VirtualMachineState :ivar connection_profile: Profile for information about connecting to the virtual machine. :vartype connection_profile: ~azure.mgmt.labservices.models.VirtualMachineConnectionProfile :ivar claimed_by_user_id: The lab user ID (not the PUID!) of who claimed the virtual machine. :vartype claimed_by_user_id: str - :ivar vm_type: The type of this VM resource. Possible values include: "User", "Template". + :ivar vm_type: The type of this VM resource. Known values are: "User" and "Template". :vartype vm_type: str or ~azure.mgmt.labservices.models.VirtualMachineType """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'state': {'readonly': True}, - 'connection_profile': {'readonly': True}, - 'claimed_by_user_id': {'readonly': True}, - 'vm_type': {'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'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'state': {'key': 'properties.state', 'type': 'str'}, - 'connection_profile': {'key': 'properties.connectionProfile', 'type': 'VirtualMachineConnectionProfile'}, - 'claimed_by_user_id': {'key': 'properties.claimedByUserId', 'type': 'str'}, - 'vm_type': {'key': 'properties.vmType', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(VirtualMachine, self).__init__(**kwargs) + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "state": {"readonly": True}, + "connection_profile": {"readonly": True}, + "claimed_by_user_id": {"readonly": True}, + "vm_type": {"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"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "state": {"key": "properties.state", "type": "str"}, + "connection_profile": {"key": "properties.connectionProfile", "type": "VirtualMachineConnectionProfile"}, + "claimed_by_user_id": {"key": "properties.claimedByUserId", "type": "str"}, + "vm_type": {"key": "properties.vmType", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.system_data = None self.provisioning_state = None self.state = None @@ -3488,34 +3411,29 @@ def __init__( self.vm_type = None -class VirtualMachineAdditionalCapabilities(msrest.serialization.Model): +class VirtualMachineAdditionalCapabilities(_serialization.Model): """The additional capabilities for a lab VM. - :ivar install_gpu_drivers: Flag to pre-install dedicated GPU drivers. Possible values include: - "Enabled", "Disabled". + :ivar install_gpu_drivers: Flag to pre-install dedicated GPU drivers. Known values are: + "Enabled" and "Disabled". :vartype install_gpu_drivers: str or ~azure.mgmt.labservices.models.EnableState """ _attribute_map = { - 'install_gpu_drivers': {'key': 'installGpuDrivers', 'type': 'str'}, + "install_gpu_drivers": {"key": "installGpuDrivers", "type": "str"}, } - def __init__( - self, - *, - install_gpu_drivers: Optional[Union[str, "EnableState"]] = None, - **kwargs - ): + def __init__(self, *, install_gpu_drivers: Optional[Union[str, "_models.EnableState"]] = None, **kwargs): """ - :keyword install_gpu_drivers: Flag to pre-install dedicated GPU drivers. Possible values - include: "Enabled", "Disabled". + :keyword install_gpu_drivers: Flag to pre-install dedicated GPU drivers. Known values are: + "Enabled" and "Disabled". :paramtype install_gpu_drivers: str or ~azure.mgmt.labservices.models.EnableState """ - super(VirtualMachineAdditionalCapabilities, self).__init__(**kwargs) + super().__init__(**kwargs) self.install_gpu_drivers = install_gpu_drivers -class VirtualMachineConnectionProfile(msrest.serialization.Model): +class VirtualMachineConnectionProfile(_serialization.Model): """The connection information for the virtual machine. Variables are only populated by the server, and will be ignored when sending a request. @@ -3542,32 +3460,28 @@ class VirtualMachineConnectionProfile(msrest.serialization.Model): """ _validation = { - 'private_ip_address': {'readonly': True}, - 'ssh_authority': {'readonly': True}, - 'ssh_in_browser_url': {'readonly': True, 'max_length': 2000, 'min_length': 3}, - 'rdp_authority': {'readonly': True}, - 'rdp_in_browser_url': {'readonly': True, 'max_length': 2000, 'min_length': 3}, - 'admin_username': {'readonly': True}, - 'non_admin_username': {'readonly': True}, + "private_ip_address": {"readonly": True}, + "ssh_authority": {"readonly": True}, + "ssh_in_browser_url": {"readonly": True, "max_length": 2000, "min_length": 3}, + "rdp_authority": {"readonly": True}, + "rdp_in_browser_url": {"readonly": True, "max_length": 2000, "min_length": 3}, + "admin_username": {"readonly": True}, + "non_admin_username": {"readonly": True}, } _attribute_map = { - 'private_ip_address': {'key': 'privateIpAddress', 'type': 'str'}, - 'ssh_authority': {'key': 'sshAuthority', 'type': 'str'}, - 'ssh_in_browser_url': {'key': 'sshInBrowserUrl', 'type': 'str'}, - 'rdp_authority': {'key': 'rdpAuthority', 'type': 'str'}, - 'rdp_in_browser_url': {'key': 'rdpInBrowserUrl', 'type': 'str'}, - 'admin_username': {'key': 'adminUsername', 'type': 'str'}, - 'non_admin_username': {'key': 'nonAdminUsername', 'type': 'str'}, + "private_ip_address": {"key": "privateIpAddress", "type": "str"}, + "ssh_authority": {"key": "sshAuthority", "type": "str"}, + "ssh_in_browser_url": {"key": "sshInBrowserUrl", "type": "str"}, + "rdp_authority": {"key": "rdpAuthority", "type": "str"}, + "rdp_in_browser_url": {"key": "rdpInBrowserUrl", "type": "str"}, + "admin_username": {"key": "adminUsername", "type": "str"}, + "non_admin_username": {"key": "nonAdminUsername", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(VirtualMachineConnectionProfile, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.private_ip_address = None self.ssh_authority = None self.ssh_in_browser_url = None @@ -3577,95 +3491,95 @@ def __init__( self.non_admin_username = None -class VirtualMachineProfile(msrest.serialization.Model): +class VirtualMachineProfile(_serialization.Model): """The base virtual machine configuration for a lab. 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. - :ivar create_option: Required. Indicates what lab virtual machines are created from. Possible - values include: "Image", "TemplateVM". + :ivar create_option: Indicates what lab virtual machines are created from. Required. Known + values are: "Image" and "TemplateVM". :vartype create_option: str or ~azure.mgmt.labservices.models.CreateOption - :ivar image_reference: Required. The image configuration for lab virtual machines. + :ivar image_reference: The image configuration for lab virtual machines. Required. :vartype image_reference: ~azure.mgmt.labservices.models.ImageReference - :ivar os_type: The OS type of the image. Possible values include: "Windows", "Linux". + :ivar os_type: The OS type of the image. Known values are: "Windows" and "Linux". :vartype os_type: str or ~azure.mgmt.labservices.models.OsType - :ivar sku: Required. The SKU for the lab. Defines the type of virtual machines used in the lab. + :ivar sku: The SKU for the lab. Defines the type of virtual machines used in the lab. Required. :vartype sku: ~azure.mgmt.labservices.models.Sku :ivar additional_capabilities: Additional VM capabilities. :vartype additional_capabilities: ~azure.mgmt.labservices.models.VirtualMachineAdditionalCapabilities - :ivar usage_quota: Required. The initial quota alloted to each lab user. Must be a time span - between 0 and 9999 hours. + :ivar usage_quota: The initial quota alloted to each lab user. Must be a time span between 0 + and 9999 hours. Required. :vartype usage_quota: ~datetime.timedelta :ivar use_shared_password: Enabling this option will use the same password for all user VMs. - Possible values include: "Enabled", "Disabled". + Known values are: "Enabled" and "Disabled". :vartype use_shared_password: str or ~azure.mgmt.labservices.models.EnableState - :ivar admin_user: Required. Credentials for the admin user on the VM. + :ivar admin_user: Credentials for the admin user on the VM. Required. :vartype admin_user: ~azure.mgmt.labservices.models.Credentials :ivar non_admin_user: Credentials for the non-admin user on the VM, if one exists. :vartype non_admin_user: ~azure.mgmt.labservices.models.Credentials """ _validation = { - 'create_option': {'required': True}, - 'image_reference': {'required': True}, - 'os_type': {'readonly': True}, - 'sku': {'required': True}, - 'usage_quota': {'required': True}, - 'admin_user': {'required': True}, + "create_option": {"required": True}, + "image_reference": {"required": True}, + "os_type": {"readonly": True}, + "sku": {"required": True}, + "usage_quota": {"required": True}, + "admin_user": {"required": True}, } _attribute_map = { - 'create_option': {'key': 'createOption', 'type': 'str'}, - 'image_reference': {'key': 'imageReference', 'type': 'ImageReference'}, - 'os_type': {'key': 'osType', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'Sku'}, - 'additional_capabilities': {'key': 'additionalCapabilities', 'type': 'VirtualMachineAdditionalCapabilities'}, - 'usage_quota': {'key': 'usageQuota', 'type': 'duration'}, - 'use_shared_password': {'key': 'useSharedPassword', 'type': 'str'}, - 'admin_user': {'key': 'adminUser', 'type': 'Credentials'}, - 'non_admin_user': {'key': 'nonAdminUser', 'type': 'Credentials'}, + "create_option": {"key": "createOption", "type": "str"}, + "image_reference": {"key": "imageReference", "type": "ImageReference"}, + "os_type": {"key": "osType", "type": "str"}, + "sku": {"key": "sku", "type": "Sku"}, + "additional_capabilities": {"key": "additionalCapabilities", "type": "VirtualMachineAdditionalCapabilities"}, + "usage_quota": {"key": "usageQuota", "type": "duration"}, + "use_shared_password": {"key": "useSharedPassword", "type": "str"}, + "admin_user": {"key": "adminUser", "type": "Credentials"}, + "non_admin_user": {"key": "nonAdminUser", "type": "Credentials"}, } def __init__( self, *, - create_option: Union[str, "CreateOption"], - image_reference: "ImageReference", - sku: "Sku", + create_option: Union[str, "_models.CreateOption"], + image_reference: "_models.ImageReference", + sku: "_models.Sku", usage_quota: datetime.timedelta, - admin_user: "Credentials", - additional_capabilities: Optional["VirtualMachineAdditionalCapabilities"] = None, - use_shared_password: Optional[Union[str, "EnableState"]] = None, - non_admin_user: Optional["Credentials"] = None, + admin_user: "_models.Credentials", + additional_capabilities: Optional["_models.VirtualMachineAdditionalCapabilities"] = None, + use_shared_password: Optional[Union[str, "_models.EnableState"]] = None, + non_admin_user: Optional["_models.Credentials"] = None, **kwargs ): """ - :keyword create_option: Required. Indicates what lab virtual machines are created from. - Possible values include: "Image", "TemplateVM". + :keyword create_option: Indicates what lab virtual machines are created from. Required. Known + values are: "Image" and "TemplateVM". :paramtype create_option: str or ~azure.mgmt.labservices.models.CreateOption - :keyword image_reference: Required. The image configuration for lab virtual machines. + :keyword image_reference: The image configuration for lab virtual machines. Required. :paramtype image_reference: ~azure.mgmt.labservices.models.ImageReference - :keyword sku: Required. The SKU for the lab. Defines the type of virtual machines used in the - lab. + :keyword sku: The SKU for the lab. Defines the type of virtual machines used in the lab. + Required. :paramtype sku: ~azure.mgmt.labservices.models.Sku :keyword additional_capabilities: Additional VM capabilities. :paramtype additional_capabilities: ~azure.mgmt.labservices.models.VirtualMachineAdditionalCapabilities - :keyword usage_quota: Required. The initial quota alloted to each lab user. Must be a time span - between 0 and 9999 hours. + :keyword usage_quota: The initial quota alloted to each lab user. Must be a time span between 0 + and 9999 hours. Required. :paramtype usage_quota: ~datetime.timedelta :keyword use_shared_password: Enabling this option will use the same password for all user VMs. - Possible values include: "Enabled", "Disabled". + Known values are: "Enabled" and "Disabled". :paramtype use_shared_password: str or ~azure.mgmt.labservices.models.EnableState - :keyword admin_user: Required. Credentials for the admin user on the VM. + :keyword admin_user: Credentials for the admin user on the VM. Required. :paramtype admin_user: ~azure.mgmt.labservices.models.Credentials :keyword non_admin_user: Credentials for the non-admin user on the VM, if one exists. :paramtype non_admin_user: ~azure.mgmt.labservices.models.Credentials """ - super(VirtualMachineProfile, self).__init__(**kwargs) + super().__init__(**kwargs) self.create_option = create_option self.image_reference = image_reference self.os_type = None diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_patch.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/__init__.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/__init__.py index f4c911b36ab4..dfde78e0230c 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/__init__.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/__init__.py @@ -12,20 +12,26 @@ from ._labs_operations import LabsOperations from ._operation_results_operations import OperationResultsOperations from ._schedules_operations import SchedulesOperations +from ._skus_operations import SkusOperations +from ._usages_operations import UsagesOperations from ._users_operations import UsersOperations from ._virtual_machines_operations import VirtualMachinesOperations -from ._usages_operations import UsagesOperations -from ._skus_operations import SkusOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'ImagesOperations', - 'LabPlansOperations', - 'Operations', - 'LabsOperations', - 'OperationResultsOperations', - 'SchedulesOperations', - 'UsersOperations', - 'VirtualMachinesOperations', - 'UsagesOperations', - 'SkusOperations', + "ImagesOperations", + "LabPlansOperations", + "Operations", + "LabsOperations", + "OperationResultsOperations", + "SchedulesOperations", + "SkusOperations", + "UsagesOperations", + "UsersOperations", + "VirtualMachinesOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_images_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_images_operations.py index ebd08332db8d..10395ff48329 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_images_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_images_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,270 +6,257 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) 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.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_by_lab_plan_request( - subscription_id: str, - resource_group_name: str, - lab_plan_name: str, - *, - filter: Optional[str] = None, - **kwargs: Any + resource_group_name: str, lab_plan_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, 'str', max_length=100, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, "str", max_length=100, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: - query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, - resource_group_name: str, - lab_plan_name: str, - image_name: str, - **kwargs: Any + resource_group_name: str, lab_plan_name: str, image_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, 'str', max_length=100, min_length=1), - "imageName": _SERIALIZER.url("image_name", image_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, "str", max_length=100, min_length=1), + "imageName": _SERIALIZER.url( + "image_name", image_name, "str", max_length=100, min_length=1, pattern=r"^[-\w\\._\\(\\)]+$" + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_create_or_update_request( - subscription_id: str, - resource_group_name: str, - lab_plan_name: str, - image_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + resource_group_name: str, lab_plan_name: str, image_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-11-15-preview" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, 'str', max_length=100, min_length=1), - "imageName": _SERIALIZER.url("image_name", image_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, "str", max_length=100, min_length=1), + "imageName": _SERIALIZER.url( + "image_name", image_name, "str", max_length=100, min_length=1, pattern=r"^[-\w\\._\\(\\)]+$" + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( - subscription_id: str, - resource_group_name: str, - lab_plan_name: str, - image_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + resource_group_name: str, lab_plan_name: str, image_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-11-15-preview" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, 'str', max_length=100, min_length=1), - "imageName": _SERIALIZER.url("image_name", image_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, "str", max_length=100, min_length=1), + "imageName": _SERIALIZER.url( + "image_name", image_name, "str", max_length=100, min_length=1, pattern=r"^[-\w\\._\\(\\)]+$" + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PATCH", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - -class ImagesOperations(object): - """ImagesOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _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 ImagesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.ManagedLabsClient`'s + :attr:`images` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_by_lab_plan( - self, - resource_group_name: str, - lab_plan_name: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.PagedImages"]: + self, resource_group_name: str, lab_plan_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.Image"]: """Gets all images. Gets all images from galleries attached to a lab plan. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 PagedImages or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.PagedImages] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Image or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.Image] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedImages"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedImages] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_lab_plan_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, + subscription_id=self._config.subscription_id, filter=filter, - template_url=self.list_by_lab_plan.metadata['url'], + api_version=api_version, + template_url=self.list_by_lab_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) # type: ignore else: - - request = build_list_by_lab_plan_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - lab_plan_name=lab_plan_name, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -282,7 +270,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -292,54 +282,55 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_lab_plan.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images'} # type: ignore + list_by_lab_plan.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - lab_plan_name: str, - image_name: str, - **kwargs: Any - ) -> "_models.Image": + def get(self, resource_group_name: str, lab_plan_name: str, image_name: str, **kwargs: Any) -> _models.Image: """Gets an image. Gets an image resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str - :param image_name: The image name. + :param image_name: The image name. Required. :type image_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Image, or the result of cls(response) + :return: Image or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.Image - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Image"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Image] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, image_name=image_name, - template_url=self.get.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -347,15 +338,82 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Image', pipeline_response) + deserialized = self._deserialize("Image", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}"} # type: ignore + @overload + def create_or_update( + self, + resource_group_name: str, + lab_plan_name: str, + image_name: str, + body: _models.Image, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Image: + """Updates an image via PUT. + + Updates an image resource via PUT. Creating new resources via PUT will not function. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param image_name: The image name. Required. + :type image_name: str + :param body: The request body. Required. + :type body: ~azure.mgmt.labservices.models.Image + :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: Image or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Image + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + lab_plan_name: str, + image_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Image: + """Updates an image via PUT. + + Updates an image resource via PUT. Creating new resources via PUT will not function. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param image_name: The image name. Required. + :type image_name: str + :param body: The request body. Required. + :type body: IO + :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: Image or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Image + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def create_or_update( @@ -363,50 +421,69 @@ def create_or_update( resource_group_name: str, lab_plan_name: str, image_name: str, - body: "_models.Image", + body: Union[_models.Image, IO], **kwargs: Any - ) -> "_models.Image": + ) -> _models.Image: """Updates an image via PUT. Updates an image resource via PUT. Creating new resources via PUT will not function. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str - :param image_name: The image name. + :param image_name: The image name. Required. :type image_name: str - :param body: The request body. - :type body: ~azure.mgmt.labservices.models.Image + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.Image 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 - :return: Image, or the result of cls(response) + :return: Image or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.Image - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Image"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(body, 'Image') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Image] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "Image") request = build_create_or_update_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, image_name=image_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.create_or_update.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -414,15 +491,82 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Image', pipeline_response) + deserialized = self._deserialize("Image", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}'} # type: ignore + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}"} # type: ignore + + @overload + def update( + self, + resource_group_name: str, + lab_plan_name: str, + image_name: str, + body: _models.ImageUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Image: + """Updates an image. + Updates an image resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param image_name: The image name. Required. + :type image_name: str + :param body: The request body. Required. + :type body: ~azure.mgmt.labservices.models.ImageUpdate + :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: Image or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Image + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + lab_plan_name: str, + image_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Image: + """Updates an image. + + Updates an image resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param image_name: The image name. Required. + :type image_name: str + :param body: The request body. Required. + :type body: IO + :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: Image or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Image + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def update( @@ -430,50 +574,69 @@ def update( resource_group_name: str, lab_plan_name: str, image_name: str, - body: "_models.ImageUpdate", + body: Union[_models.ImageUpdate, IO], **kwargs: Any - ) -> "_models.Image": + ) -> _models.Image: """Updates an image. Updates an image resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str - :param image_name: The image name. + :param image_name: The image name. Required. :type image_name: str - :param body: The request body. - :type body: ~azure.mgmt.labservices.models.ImageUpdate + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.ImageUpdate 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 - :return: Image, or the result of cls(response) + :return: Image or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.Image - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Image"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(body, 'ImageUpdate') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Image] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ImageUpdate") request = build_update_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, image_name=image_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -481,12 +644,11 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Image', pipeline_response) + deserialized = self._deserialize("Image", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}'} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/images/{imageName}"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_lab_plans_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_lab_plans_operations.py index c27a09849585..4d0b1d66e2a8 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_lab_plans_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_lab_plans_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,363 +6,330 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + 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.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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_by_subscription_request( - subscription_id: str, - *, - filter: Optional[str] = None, - **kwargs: Any + subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/labPlans') + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/labPlans") path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: - query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_list_by_resource_group_request( - subscription_id: str, - resource_group_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request(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 = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_get_request( - subscription_id: str, - resource_group_name: str, - lab_plan_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _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, lab_plan_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 = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, 'str', max_length=100, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, "str", max_length=100, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_create_or_update_request_initial( - subscription_id: str, - resource_group_name: str, - lab_plan_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + _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, lab_plan_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-11-15-preview" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, 'str', max_length=100, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, "str", max_length=100, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - - -def build_update_request_initial( - subscription_id: str, - resource_group_name: str, - lab_plan_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + _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, lab_plan_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-11-15-preview" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, 'str', max_length=100, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, "str", max_length=100, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PATCH", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - lab_plan_name: str, - **kwargs: Any + _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, lab_plan_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, 'str', max_length=100, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, "str", max_length=100, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_save_image_request_initial( - subscription_id: str, - resource_group_name: str, - lab_plan_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_save_image_request( + resource_group_name: str, lab_plan_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-11-15-preview" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/saveImage') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/saveImage", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, 'str', max_length=100, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labPlanName": _SERIALIZER.url("lab_plan_name", lab_plan_name, "str", max_length=100, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - -class LabPlansOperations(object): - """LabPlansOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _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 LabPlansOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.ManagedLabsClient`'s + :attr:`lab_plans` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_by_subscription( - self, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.PagedLabPlans"]: + def list_by_subscription(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.LabPlan"]: """Get all lab plans for a subscription. Returns a list of all lab plans within a subscription. - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 PagedLabPlans or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.PagedLabPlans] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either LabPlan or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.LabPlan] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedLabPlans"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedLabPlans] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, filter=filter, - template_url=self.list_by_subscription.metadata['url'], + api_version=api_version, + template_url=self.list_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) # type: ignore else: - - request = build_list_by_subscription_request( - subscription_id=self._config.subscription_id, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -375,7 +343,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -385,54 +355,55 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/labPlans'} # type: ignore + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/labPlans"} # type: ignore @distributed_trace - def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> Iterable["_models.PagedLabPlans"]: + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.LabPlan"]: """Get all lab plans for a subscription and resource group. Returns a list of all lab plans for a subscription and 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 PagedLabPlans or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.PagedLabPlans] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either LabPlan or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.LabPlan] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedLabPlans"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedLabPlans] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, - template_url=self.list_by_resource_group.metadata['url'], + 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) # type: ignore else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -446,7 +417,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -456,50 +429,52 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans'} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - lab_plan_name: str, - **kwargs: Any - ) -> "_models.LabPlan": + def get(self, resource_group_name: str, lab_plan_name: str, **kwargs: Any) -> _models.LabPlan: """Retrieves a Lab Plan resource. Retrieves the properties of a Lab Plan. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: LabPlan, or the result of cls(response) + :return: LabPlan or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.LabPlan - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.LabPlan"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.LabPlan] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, - template_url=self.get.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -507,87 +482,103 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}"} # type: ignore def _create_or_update_initial( - self, - resource_group_name: str, - lab_plan_name: str, - body: "_models.LabPlan", - **kwargs: Any - ) -> "_models.LabPlan": - cls = kwargs.pop('cls', None) # type: ClsType["_models.LabPlan"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(body, 'LabPlan') + self, resource_group_name: str, lab_plan_name: str, body: Union[_models.LabPlan, IO], **kwargs: Any + ) -> _models.LabPlan: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.LabPlan] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "LabPlan") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}'} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}"} # type: ignore - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, lab_plan_name: str, - body: "_models.LabPlan", + body: _models.LabPlan, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller["_models.LabPlan"]: + ) -> LROPoller[_models.LabPlan]: """Updates or creates a Lab Plan resource. Operation to create or update a Lab Plan resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str - :param body: The request body. + :param body: The request body. Required. :type body: ~azure.mgmt.labservices.models.LabPlan + :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 @@ -598,118 +589,211 @@ def begin_create_or_update( Retry-After header is present. :return: An instance of LROPoller that returns either LabPlan or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.LabPlan] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.LabPlan"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + lab_plan_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.LabPlan]: + """Updates or creates a Lab Plan resource. + + Operation to create or update a Lab Plan resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param body: The request body. Required. + :type body: IO + :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 LabPlan or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.LabPlan] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, resource_group_name: str, lab_plan_name: str, body: Union[_models.LabPlan, IO], **kwargs: Any + ) -> LROPoller[_models.LabPlan]: + """Updates or creates a Lab Plan resource. + + Operation to create or update a Lab Plan resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.LabPlan 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. + :return: An instance of LROPoller that returns either LabPlan or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.LabPlan] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.LabPlan] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._create_or_update_initial( + raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'original-uri'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}"} # type: ignore def _update_initial( - self, - resource_group_name: str, - lab_plan_name: str, - body: "_models.LabPlanUpdate", - **kwargs: Any - ) -> "_models.LabPlan": - cls = kwargs.pop('cls', None) # type: ClsType["_models.LabPlan"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(body, 'LabPlanUpdate') + self, resource_group_name: str, lab_plan_name: str, body: Union[_models.LabPlanUpdate, IO], **kwargs: Any + ) -> _models.LabPlan: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.LabPlan] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "LabPlanUpdate") - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_update_request( resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}'} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}"} # type: ignore - - @distributed_trace + @overload def begin_update( self, resource_group_name: str, lab_plan_name: str, - body: "_models.LabPlanUpdate", + body: _models.LabPlanUpdate, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller["_models.LabPlan"]: + ) -> LROPoller[_models.LabPlan]: """Updates a Lab Plan resource. Operation to update a Lab Plan resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str - :param body: The request body. + :param body: The request body. Required. :type body: ~azure.mgmt.labservices.models.LabPlanUpdate + :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 @@ -720,92 +804,168 @@ def begin_update( Retry-After header is present. :return: An instance of LROPoller that returns either LabPlan or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.LabPlan] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.LabPlan"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_update( + self, + resource_group_name: str, + lab_plan_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.LabPlan]: + """Updates a Lab Plan resource. + + Operation to update a Lab Plan resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param body: The request body. Required. + :type body: IO + :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 LabPlan or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.LabPlan] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, resource_group_name: str, lab_plan_name: str, body: Union[_models.LabPlanUpdate, IO], **kwargs: Any + ) -> LROPoller[_models.LabPlan]: + """Updates a Lab Plan resource. + + Operation to update a Lab Plan resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.LabPlanUpdate 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. + :return: An instance of LROPoller that returns either LabPlan or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.LabPlan] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.LabPlan] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._update_initial( + raw_result = self._update_initial( # type: ignore resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('LabPlan', pipeline_response) + deserialized = self._deserialize("LabPlan", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}'} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}"} # type: ignore - def _delete_initial( - self, - resource_group_name: str, - lab_plan_name: str, - **kwargs: Any + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_plan_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, - template_url=self._delete_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}"} # type: ignore @distributed_trace - def begin_delete( - self, - resource_group_name: str, - lab_plan_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_delete(self, resource_group_name: str, lab_plan_name: str, **kwargs: Any) -> LROPoller[None]: """Deletes a Lab Plan resource. Operation to delete a Lab Plan resource. Deleting a lab plan does not delete labs associated @@ -813,9 +973,10 @@ def begin_delete( permission container. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_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. @@ -827,91 +988,111 @@ def begin_delete( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._delete_initial( + raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}"} # type: ignore - def _save_image_initial( - self, - resource_group_name: str, - lab_plan_name: str, - body: "_models.SaveImageBody", - **kwargs: Any + def _save_image_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_plan_name: str, body: Union[_models.SaveImageBody, IO], **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(body, 'SaveImageBody') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] - request = build_save_image_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "SaveImageBody") + + request = build_save_image_request( resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._save_image_initial.metadata['url'], + content=_content, + template_url=self._save_image_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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _save_image_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/saveImage'} # type: ignore + _save_image_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/saveImage"} # type: ignore - - @distributed_trace + @overload def begin_save_image( self, resource_group_name: str, lab_plan_name: str, - body: "_models.SaveImageBody", + body: _models.SaveImageBody, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[None]: """Save an image from a lab VM to the attached shared image gallery. @@ -919,12 +1100,16 @@ def begin_save_image( Saves an image from a lab VM to the attached shared image gallery. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing - resource group. Used in resource URIs and in UI. + resource group. Used in resource URIs and in UI. Required. :type lab_plan_name: str - :param body: The request body. + :param body: The request body. Required. :type body: ~azure.mgmt.labservices.models.SaveImageBody + :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 @@ -935,43 +1120,120 @@ def begin_save_image( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_save_image( + self, + resource_group_name: str, + lab_plan_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Save an image from a lab VM to the attached shared image gallery. + + Saves an image from a lab VM to the attached shared image gallery. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param body: The request body. Required. + :type body: IO + :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 None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_save_image( + self, resource_group_name: str, lab_plan_name: str, body: Union[_models.SaveImageBody, IO], **kwargs: Any + ) -> LROPoller[None]: + """Save an image from a lab VM to the attached shared image gallery. + + Saves an image from a lab VM to the attached shared image gallery. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_plan_name: The name of the lab plan that uniquely identifies it within containing + resource group. Used in resource URIs and in UI. Required. + :type lab_plan_name: str + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.SaveImageBody 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. + :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 = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._save_image_initial( + raw_result = self._save_image_initial( # type: ignore resource_group_name=resource_group_name, lab_plan_name=lab_plan_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_save_image.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/saveImage'} # type: ignore + begin_save_image.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labPlans/{labPlanName}/saveImage"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_labs_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_labs_operations.py index 1bc6c0b25292..02704d9d4d16 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_labs_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_labs_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,389 +6,354 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + 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.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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_by_subscription_request( - subscription_id: str, - *, - filter: Optional[str] = None, - **kwargs: Any + subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/labs') + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/labs") path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: - query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_list_by_resource_group_request( - subscription_id: str, - resource_group_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request(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 = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_get_request( - subscription_id: str, - resource_group_name: str, - lab_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _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, lab_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 = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_create_or_update_request_initial( - subscription_id: str, - resource_group_name: str, - lab_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + _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, lab_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-11-15-preview" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - - -def build_update_request_initial( - subscription_id: str, - resource_group_name: str, - lab_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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, lab_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 = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-11-15-preview" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PATCH", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - lab_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _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, lab_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 = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_publish_request_initial( - subscription_id: str, - resource_group_name: str, - lab_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_publish_request(resource_group_name: str, lab_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 = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/publish') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/publish", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_sync_group_request_initial( - subscription_id: str, - resource_group_name: str, - lab_name: str, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_sync_group_request( + resource_group_name: str, lab_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/syncGroup') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/syncGroup", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class LabsOperations(object): - """LabsOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class LabsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.ManagedLabsClient`'s + :attr:`labs` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_by_subscription( - self, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.PagedLabs"]: + def list_by_subscription(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.Lab"]: """Get all labs for a subscription. Returns a list of all labs for a subscription. - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 PagedLabs or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.PagedLabs] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Lab or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.Lab] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedLabs"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedLabs] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, filter=filter, - template_url=self.list_by_subscription.metadata['url'], + api_version=api_version, + template_url=self.list_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) # type: ignore else: - - request = build_list_by_subscription_request( - subscription_id=self._config.subscription_id, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -401,7 +367,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -411,54 +379,55 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/labs'} # type: ignore + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/labs"} # type: ignore @distributed_trace - def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> Iterable["_models.PagedLabs"]: + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.Lab"]: """Get all labs for a subscription and resource group. Returns a list of all labs in a 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 PagedLabs or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.PagedLabs] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Lab or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.Lab] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedLabs"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedLabs] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, - template_url=self.list_by_resource_group.metadata['url'], + 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) # type: ignore else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -472,7 +441,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -482,50 +453,52 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs'} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - lab_name: str, - **kwargs: Any - ) -> "_models.Lab": + def get(self, resource_group_name: str, lab_name: str, **kwargs: Any) -> _models.Lab: """Get a lab resource. Returns the properties of a lab resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Lab, or the result of cls(response) + :return: Lab or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.Lab - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Lab"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Lab] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, - template_url=self.get.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -533,87 +506,103 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}"} # type: ignore def _create_or_update_initial( - self, - resource_group_name: str, - lab_name: str, - body: "_models.Lab", - **kwargs: Any - ) -> "_models.Lab": - cls = kwargs.pop('cls', None) # type: ClsType["_models.Lab"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(body, 'Lab') + self, resource_group_name: str, lab_name: str, body: Union[_models.Lab, IO], **kwargs: Any + ) -> _models.Lab: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Lab] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "Lab") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, lab_name=lab_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}'} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}"} # type: ignore - - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, lab_name: str, - body: "_models.Lab", + body: _models.Lab, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller["_models.Lab"]: + ) -> LROPoller[_models.Lab]: """Create or update a lab resource. Operation to create or update a lab resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str - :param body: The request body. + :param body: The request body. Required. :type body: ~azure.mgmt.labservices.models.Lab + :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 @@ -624,118 +613,211 @@ def begin_create_or_update( Retry-After header is present. :return: An instance of LROPoller that returns either Lab or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.Lab] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.Lab"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + lab_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Lab]: + """Create or update a lab resource. + + Operation to create or update a lab resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param body: The request body. Required. + :type body: IO + :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 Lab or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.Lab] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, resource_group_name: str, lab_name: str, body: Union[_models.Lab, IO], **kwargs: Any + ) -> LROPoller[_models.Lab]: + """Create or update a lab resource. + + Operation to create or update a lab resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.Lab 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. + :return: An instance of LROPoller that returns either Lab or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.Lab] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Lab] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._create_or_update_initial( + raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'original-uri'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}"} # type: ignore def _update_initial( - self, - resource_group_name: str, - lab_name: str, - body: "_models.LabUpdate", - **kwargs: Any - ) -> "_models.Lab": - cls = kwargs.pop('cls', None) # type: ClsType["_models.Lab"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(body, 'LabUpdate') + self, resource_group_name: str, lab_name: str, body: Union[_models.LabUpdate, IO], **kwargs: Any + ) -> _models.Lab: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Lab] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "LabUpdate") - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_update_request( resource_group_name=resource_group_name, lab_name=lab_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}'} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}"} # type: ignore - - @distributed_trace + @overload def begin_update( self, resource_group_name: str, lab_name: str, - body: "_models.LabUpdate", + body: _models.LabUpdate, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller["_models.Lab"]: + ) -> LROPoller[_models.Lab]: """Update a lab resource. Operation to update a lab resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str - :param body: The request body. + :param body: The request body. Required. :type body: ~azure.mgmt.labservices.models.LabUpdate + :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 @@ -746,100 +828,177 @@ def begin_update( Retry-After header is present. :return: An instance of LROPoller that returns either Lab or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.Lab] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.Lab"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_update( + self, + resource_group_name: str, + lab_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Lab]: + """Update a lab resource. + + Operation to update a lab resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param body: The request body. Required. + :type body: IO + :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 Lab or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.Lab] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, resource_group_name: str, lab_name: str, body: Union[_models.LabUpdate, IO], **kwargs: Any + ) -> LROPoller[_models.Lab]: + """Update a lab resource. + + Operation to update a lab resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.LabUpdate 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. + :return: An instance of LROPoller that returns either Lab or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.Lab] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Lab] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._update_initial( + raw_result = self._update_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('Lab', pipeline_response) + deserialized = self._deserialize("Lab", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}'} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}"} # type: ignore - def _delete_initial( - self, - resource_group_name: str, - lab_name: str, - **kwargs: Any + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( resource_group_name=resource_group_name, lab_name=lab_name, - template_url=self._delete_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}"} # type: ignore @distributed_trace - def begin_delete( - self, - resource_group_name: str, - lab_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_delete(self, resource_group_name: str, lab_name: str, **kwargs: Any) -> LROPoller[None]: """Deletes a lab resource. Operation to delete a lab resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_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. @@ -851,95 +1010,103 @@ def begin_delete( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._delete_initial( + raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}"} # type: ignore - def _publish_initial( - self, - resource_group_name: str, - lab_name: str, - **kwargs: Any + def _publish_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_publish_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_publish_request( resource_group_name=resource_group_name, lab_name=lab_name, - template_url=self._publish_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._publish_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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _publish_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/publish'} # type: ignore - + _publish_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/publish"} # type: ignore @distributed_trace - def begin_publish( - self, - resource_group_name: str, - lab_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_publish(self, resource_group_name: str, lab_name: str, **kwargs: Any) -> LROPoller[None]: """Publish or re-publish a lab. Publish or re-publish a lab. This will create or update all lab resources, such as virtual machines. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_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. @@ -951,94 +1118,102 @@ def begin_publish( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._publish_initial( + raw_result = self._publish_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_publish.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/publish'} # type: ignore + begin_publish.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/publish"} # type: ignore - def _sync_group_initial( - self, - resource_group_name: str, - lab_name: str, - **kwargs: Any + def _sync_group_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_sync_group_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_sync_group_request( resource_group_name=resource_group_name, lab_name=lab_name, - template_url=self._sync_group_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._sync_group_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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _sync_group_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/syncGroup'} # type: ignore - + _sync_group_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/syncGroup"} # type: ignore @distributed_trace - def begin_sync_group( - self, - resource_group_name: str, - lab_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_sync_group(self, resource_group_name: str, lab_name: str, **kwargs: Any) -> LROPoller[None]: """Manually sync the lab group. Action used to manually kick off an AAD group sync job. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_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. @@ -1050,40 +1225,47 @@ def begin_sync_group( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._sync_group_initial( + raw_result = self._sync_group_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_sync_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/syncGroup'} # type: ignore + begin_sync_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/syncGroup"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_operation_results_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_operation_results_operations.py index d9dad6fa52a8..1a9d088e0b78 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_operation_results_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_operation_results_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,113 +6,124 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import 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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_request( - subscription_id: str, - operation_result_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + +def build_get_request(operation_result_id: 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 = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/operationResults/{operationResultId}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/operationResults/{operationResultId}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "operationResultId": _SERIALIZER.url("operation_result_id", operation_result_id, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "operationResultId": _SERIALIZER.url( + "operation_result_id", + operation_result_id, + "str", + max_length=100, + min_length=1, + pattern=r"^[-\w\\._\\(\\)]+$", + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class OperationResultsOperations(object): - """OperationResultsOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class OperationResultsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.ManagedLabsClient`'s + :attr:`operation_results` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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 get( - self, - operation_result_id: str, - **kwargs: Any - ) -> Optional["_models.OperationResult"]: + def get(self, operation_result_id: str, **kwargs: Any) -> Optional[_models.OperationResult]: """Get an azure operation result. Returns an azure operation result. - :param operation_result_id: The operation result ID / name. + :param operation_result_id: The operation result ID / name. Required. :type operation_result_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: OperationResult, or the result of cls(response) + :return: OperationResult or None or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.OperationResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationResult"]] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.OperationResult]] - request = build_get_request( - subscription_id=self._config.subscription_id, operation_result_id=operation_result_id, - template_url=self.get.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -121,12 +133,11 @@ def get( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('OperationResult', pipeline_response) + deserialized = self._deserialize("OperationResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/operationResults/{operationResultId}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/operationResults/{operationResultId}"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_operations.py index baf0840bc06c..637bfaf00f5b 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,108 +6,113 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) 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.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request -T = TypeVar('T') + +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( - **kwargs: Any -) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + +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 = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/providers/Microsoft.LabServices/operations') + _url = kwargs.pop("template_url", "/providers/Microsoft.LabServices/operations") # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class Operations(object): - """Operations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.ManagedLabsClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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, - **kwargs: Any - ) -> Iterable["_models.OperationListResult"]: + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Get all operations. Returns a list of all operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - template_url=self.list.metadata['url'], + 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) # type: ignore else: - - request = build_list_request( - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -120,7 +126,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -130,8 +138,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.LabServices/operations'} # type: ignore + list.metadata = {"url": "/providers/Microsoft.LabServices/operations"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_patch.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_schedules_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_schedules_operations.py index 44748708fa03..1b4087284f5b 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_schedules_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_schedules_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,309 +6,295 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + 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.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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_by_lab_request( - subscription_id: str, - resource_group_name: str, - lab_name: str, - *, - filter: Optional[str] = None, - **kwargs: Any + resource_group_name: str, lab_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: - query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, - resource_group_name: str, - lab_name: str, - schedule_name: str, - **kwargs: Any + resource_group_name: str, lab_name: str, schedule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), - "scheduleName": _SERIALIZER.url("schedule_name", schedule_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), + "scheduleName": _SERIALIZER.url( + "schedule_name", schedule_name, "str", max_length=100, min_length=1, pattern=r"^[-\w\\._\\(\\)]+$" + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_create_or_update_request( - subscription_id: str, - resource_group_name: str, - lab_name: str, - schedule_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + resource_group_name: str, lab_name: str, schedule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-11-15-preview" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), - "scheduleName": _SERIALIZER.url("schedule_name", schedule_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), + "scheduleName": _SERIALIZER.url( + "schedule_name", schedule_name, "str", max_length=100, min_length=1, pattern=r"^[-\w\\._\\(\\)]+$" + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( - subscription_id: str, - resource_group_name: str, - lab_name: str, - schedule_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + resource_group_name: str, lab_name: str, schedule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-11-15-preview" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), - "scheduleName": _SERIALIZER.url("schedule_name", schedule_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), + "scheduleName": _SERIALIZER.url( + "schedule_name", schedule_name, "str", max_length=100, min_length=1, pattern=r"^[-\w\\._\\(\\)]+$" + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PATCH", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - lab_name: str, - schedule_name: str, - **kwargs: Any + _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, lab_name: str, schedule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), - "scheduleName": _SERIALIZER.url("schedule_name", schedule_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), + "scheduleName": _SERIALIZER.url( + "schedule_name", schedule_name, "str", max_length=100, min_length=1, pattern=r"^[-\w\\._\\(\\)]+$" + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class SchedulesOperations(object): - """SchedulesOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class SchedulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.ManagedLabsClient`'s + :attr:`schedules` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_by_lab( - self, - resource_group_name: str, - lab_name: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.PagedSchedules"]: + self, resource_group_name: str, lab_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.Schedule"]: """Get all schedules for a lab. Returns a list of all schedules for a lab. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 PagedSchedules or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.PagedSchedules] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Schedule or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.Schedule] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedSchedules"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedSchedules] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_lab_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, + subscription_id=self._config.subscription_id, filter=filter, - template_url=self.list_by_lab.metadata['url'], + api_version=api_version, + template_url=self.list_by_lab.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) # type: ignore else: - - request = build_list_by_lab_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - lab_name=lab_name, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -321,7 +308,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -331,55 +320,56 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_lab.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules'} # type: ignore + list_by_lab.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - lab_name: str, - schedule_name: str, - **kwargs: Any - ) -> "_models.Schedule": + def get(self, resource_group_name: str, lab_name: str, schedule_name: str, **kwargs: Any) -> _models.Schedule: """Get a lab Schedule. Returns the properties of a lab Schedule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param schedule_name: The name of the schedule that uniquely identifies it within containing - lab. Used in resource URIs. + lab. Used in resource URIs. Required. :type schedule_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Schedule, or the result of cls(response) + :return: Schedule or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.Schedule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Schedule"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Schedule] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, schedule_name=schedule_name, - template_url=self.get.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -387,15 +377,84 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Schedule', pipeline_response) + deserialized = self._deserialize("Schedule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}"} # type: ignore + @overload + def create_or_update( + self, + resource_group_name: str, + lab_name: str, + schedule_name: str, + body: _models.Schedule, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Schedule: + """Create or update a lab schedule. + + Operation to create or update a lab schedule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param schedule_name: The name of the schedule that uniquely identifies it within containing + lab. Used in resource URIs. Required. + :type schedule_name: str + :param body: The request body. Required. + :type body: ~azure.mgmt.labservices.models.Schedule + :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: Schedule or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Schedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + lab_name: str, + schedule_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Schedule: + """Create or update a lab schedule. + + Operation to create or update a lab schedule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param schedule_name: The name of the schedule that uniquely identifies it within containing + lab. Used in resource URIs. Required. + :type schedule_name: str + :param body: The request body. Required. + :type body: IO + :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: Schedule or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Schedule + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def create_or_update( @@ -403,51 +462,70 @@ def create_or_update( resource_group_name: str, lab_name: str, schedule_name: str, - body: "_models.Schedule", + body: Union[_models.Schedule, IO], **kwargs: Any - ) -> "_models.Schedule": + ) -> _models.Schedule: """Create or update a lab schedule. Operation to create or update a lab schedule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param schedule_name: The name of the schedule that uniquely identifies it within containing - lab. Used in resource URIs. + lab. Used in resource URIs. Required. :type schedule_name: str - :param body: The request body. - :type body: ~azure.mgmt.labservices.models.Schedule + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.Schedule 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 - :return: Schedule, or the result of cls(response) + :return: Schedule or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.Schedule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Schedule"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(body, 'Schedule') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Schedule] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "Schedule") request = build_create_or_update_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, schedule_name=schedule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.create_or_update.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -456,18 +534,87 @@ def create_or_update( raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Schedule', pipeline_response) + deserialized = self._deserialize("Schedule", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Schedule', pipeline_response) + deserialized = self._deserialize("Schedule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}'} # type: ignore + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}"} # type: ignore + @overload + def update( + self, + resource_group_name: str, + lab_name: str, + schedule_name: str, + body: _models.ScheduleUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Schedule: + """Update a lab schedule. + + Operation to update a lab schedule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param schedule_name: The name of the schedule that uniquely identifies it within containing + lab. Used in resource URIs. Required. + :type schedule_name: str + :param body: The request body. Required. + :type body: ~azure.mgmt.labservices.models.ScheduleUpdate + :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: Schedule or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Schedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + lab_name: str, + schedule_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Schedule: + """Update a lab schedule. + + Operation to update a lab schedule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param schedule_name: The name of the schedule that uniquely identifies it within containing + lab. Used in resource URIs. Required. + :type schedule_name: str + :param body: The request body. Required. + :type body: IO + :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: Schedule or the result of cls(response) + :rtype: ~azure.mgmt.labservices.models.Schedule + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def update( @@ -475,51 +622,70 @@ def update( resource_group_name: str, lab_name: str, schedule_name: str, - body: "_models.ScheduleUpdate", + body: Union[_models.ScheduleUpdate, IO], **kwargs: Any - ) -> "_models.Schedule": + ) -> _models.Schedule: """Update a lab schedule. Operation to update a lab schedule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param schedule_name: The name of the schedule that uniquely identifies it within containing - lab. Used in resource URIs. + lab. Used in resource URIs. Required. :type schedule_name: str - :param body: The request body. - :type body: ~azure.mgmt.labservices.models.ScheduleUpdate + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.ScheduleUpdate 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 - :return: Schedule, or the result of cls(response) + :return: Schedule or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.Schedule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Schedule"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Schedule] - _json = self._serialize.body(body, 'ScheduleUpdate') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ScheduleUpdate") request = build_update_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, schedule_name=schedule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -527,72 +693,72 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Schedule', pipeline_response) + deserialized = self._deserialize("Schedule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}'} # type: ignore + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}"} # type: ignore - - def _delete_initial( - self, - resource_group_name: str, - lab_name: str, - schedule_name: str, - **kwargs: Any + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, schedule_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( resource_group_name=resource_group_name, lab_name=lab_name, schedule_name=schedule_name, - template_url=self._delete_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}"} # type: ignore @distributed_trace def begin_delete( - self, - resource_group_name: str, - lab_name: str, - schedule_name: str, - **kwargs: Any + self, resource_group_name: str, lab_name: str, schedule_name: str, **kwargs: Any ) -> LROPoller[None]: """Deletes a schedule resource. Operation to delete a schedule resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param schedule_name: The name of the schedule that uniquely identifies it within containing - lab. Used in resource URIs. + lab. Used in resource URIs. Required. :type schedule_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. @@ -604,41 +770,48 @@ def begin_delete( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._delete_initial( + raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, schedule_name=schedule_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/schedules/{scheduleName}"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_skus_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_skus_operations.py index bec473144396..66f99da0a68a 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_skus_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_skus_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,126 +6,124 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) 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.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +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, - *, - filter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + +def build_list_request(subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/skus') + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/skus") path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: - query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class SkusOperations(object): - """SkusOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class SkusOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.ManagedLabsClient`'s + :attr:`skus` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.PagedLabServicesSkus"]: - """Gets all the Azure Lab Services resource SKUs. + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.LabServicesSku"]: + """Gets the Azure Lab Services resource SKUs. - Returns a list of all the Azure Lab Services resource SKUs. + Returns a list of Azure Lab Services resource SKUs. - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 PagedLabServicesSkus or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.PagedLabServicesSkus] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either LabServicesSku or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.LabServicesSku] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedLabServicesSkus"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedLabServicesSkus] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + 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, filter=filter, - template_url=self.list.metadata['url'], + 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) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -138,7 +137,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -148,8 +149,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/skus'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/skus"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_usages_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_usages_operations.py index fa66982130ca..9b99925f1d4d 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_usages_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_usages_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,132 +6,132 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) 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.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_by_location_request( - subscription_id: str, - location: str, - *, - filter: Optional[str] = None, - **kwargs: Any + location: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/locations/{location}/usages') + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/locations/{location}/usages" + ) # 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', max_length=100, min_length=1, pattern=r'^[-\w\._]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "location": _SERIALIZER.url("location", location, "str", max_length=100, min_length=1, pattern=r"^[-\w\._]+$"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: - query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class UsagesOperations(object): - """UsagesOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class UsagesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.ManagedLabsClient`'s + :attr:`usages` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_by_location( - self, - location: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.ListUsagesResult"]: + def list_by_location(self, location: str, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.Usage"]: """Gets the list of usages. Returns list of usage per SKU family for the specified subscription in the specified region. - :param location: The location name. + :param location: The location name. Required. :type location: str - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 ListUsagesResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.ListUsagesResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Usage or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.Usage] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ListUsagesResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ListUsagesResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_location_request( - subscription_id=self._config.subscription_id, location=location, + subscription_id=self._config.subscription_id, filter=filter, - template_url=self.list_by_location.metadata['url'], + api_version=api_version, + template_url=self.list_by_location.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) # type: ignore else: - - request = build_list_by_location_request( - subscription_id=self._config.subscription_id, - location=location, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -144,7 +145,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -154,8 +157,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_location.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/locations/{location}/usages'} # type: ignore + list_by_location.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.LabServices/locations/{location}/usages"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_users_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_users_operations.py index 85021251b5fb..592e0693365b 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_users_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_users_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,355 +6,334 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + 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.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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_by_lab_request( - subscription_id: str, - resource_group_name: str, - lab_name: str, - *, - filter: Optional[str] = None, - **kwargs: Any + resource_group_name: str, lab_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: - query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, - resource_group_name: str, - lab_name: str, - user_name: str, - **kwargs: Any + resource_group_name: str, lab_name: str, user_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), - "userName": _SERIALIZER.url("user_name", user_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), + "userName": _SERIALIZER.url( + "user_name", user_name, "str", max_length=100, min_length=1, pattern=r"^[-\w\\._\\(\\)]+$" + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_create_or_update_request_initial( - subscription_id: str, - resource_group_name: str, - lab_name: str, - user_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + _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, lab_name: str, user_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-11-15-preview" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), - "userName": _SERIALIZER.url("user_name", user_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), + "userName": _SERIALIZER.url( + "user_name", user_name, "str", max_length=100, min_length=1, pattern=r"^[-\w\\._\\(\\)]+$" + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - - -def build_update_request_initial( - subscription_id: str, - resource_group_name: str, - lab_name: str, - user_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + _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, lab_name: str, user_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-11-15-preview" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), - "userName": _SERIALIZER.url("user_name", user_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), + "userName": _SERIALIZER.url( + "user_name", user_name, "str", max_length=100, min_length=1, pattern=r"^[-\w\\._\\(\\)]+$" + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PATCH", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - lab_name: str, - user_name: str, - **kwargs: Any + _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, lab_name: str, user_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), - "userName": _SERIALIZER.url("user_name", user_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), + "userName": _SERIALIZER.url( + "user_name", user_name, "str", max_length=100, min_length=1, pattern=r"^[-\w\\._\\(\\)]+$" + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_invite_request_initial( - subscription_id: str, - resource_group_name: str, - lab_name: str, - user_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_invite_request( + resource_group_name: str, lab_name: str, user_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-11-15-preview" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}/invite') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}/invite", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), - "userName": _SERIALIZER.url("user_name", user_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), + "userName": _SERIALIZER.url( + "user_name", user_name, "str", max_length=100, min_length=1, pattern=r"^[-\w\\._\\(\\)]+$" + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - -class UsersOperations(object): - """UsersOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _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 UsersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.ManagedLabsClient`'s + :attr:`users` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_by_lab( - self, - resource_group_name: str, - lab_name: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.PagedUsers"]: + self, resource_group_name: str, lab_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.User"]: """Get all users for a lab. Returns a list of all users for a lab. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 PagedUsers or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.PagedUsers] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either User or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.User] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedUsers"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedUsers] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_lab_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, + subscription_id=self._config.subscription_id, filter=filter, - template_url=self.list_by_lab.metadata['url'], + api_version=api_version, + template_url=self.list_by_lab.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) # type: ignore else: - - request = build_list_by_lab_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - lab_name=lab_name, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -367,7 +347,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -377,55 +359,56 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_lab.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users'} # type: ignore + list_by_lab.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - lab_name: str, - user_name: str, - **kwargs: Any - ) -> "_models.User": + def get(self, resource_group_name: str, lab_name: str, user_name: str, **kwargs: Any) -> _models.User: """Get a lab user. Returns the properties of a lab user. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param user_name: The name of the user that uniquely identifies it within containing lab. Used - in resource URIs. + in resource URIs. Required. :type user_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: User, or the result of cls(response) + :return: User or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.User - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.User"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.User] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, - template_url=self.get.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -433,93 +416,108 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}"} # type: ignore def _create_or_update_initial( - self, - resource_group_name: str, - lab_name: str, - user_name: str, - body: "_models.User", - **kwargs: Any - ) -> "_models.User": - cls = kwargs.pop('cls', None) # type: ClsType["_models.User"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(body, 'User') + self, resource_group_name: str, lab_name: str, user_name: str, body: Union[_models.User, IO], **kwargs: Any + ) -> _models.User: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.User] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "User") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}'} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}"} # type: ignore - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, lab_name: str, user_name: str, - body: "_models.User", + body: _models.User, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller["_models.User"]: + ) -> LROPoller[_models.User]: """Create or update a lab user. Operation to create or update a lab user. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param user_name: The name of the user that uniquely identifies it within containing lab. Used - in resource URIs. + in resource URIs. Required. :type user_name: str - :param body: The request body. + :param body: The request body. Required. :type body: ~azure.mgmt.labservices.models.User + :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 @@ -530,101 +528,283 @@ def begin_create_or_update( Retry-After header is present. :return: An instance of LROPoller that returns either User or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.User] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.User"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + lab_name: str, + user_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.User]: + """Create or update a lab user. + + Operation to create or update a lab user. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param user_name: The name of the user that uniquely identifies it within containing lab. Used + in resource URIs. Required. + :type user_name: str + :param body: The request body. Required. + :type body: IO + :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 User or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.User] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, resource_group_name: str, lab_name: str, user_name: str, body: Union[_models.User, IO], **kwargs: Any + ) -> LROPoller[_models.User]: + """Create or update a lab user. + + Operation to create or update a lab user. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param user_name: The name of the user that uniquely identifies it within containing lab. Used + in resource URIs. Required. + :type user_name: str + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.User 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. + :return: An instance of LROPoller that returns either User or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.User] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.User] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._create_or_update_initial( + raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'original-uri'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}"} # type: ignore def _update_initial( self, resource_group_name: str, lab_name: str, user_name: str, - body: "_models.UserUpdate", + body: Union[_models.UserUpdate, IO], **kwargs: Any - ) -> "_models.User": - cls = kwargs.pop('cls', None) # type: ClsType["_models.User"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(body, 'UserUpdate') + ) -> _models.User: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.User] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "UserUpdate") - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_update_request( resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}'} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}"} # type: ignore + @overload + def begin_update( + self, + resource_group_name: str, + lab_name: str, + user_name: str, + body: _models.UserUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.User]: + """Update a lab user. + + Operation to update a lab user. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param user_name: The name of the user that uniquely identifies it within containing lab. Used + in resource URIs. Required. + :type user_name: str + :param body: The request body. Required. + :type body: ~azure.mgmt.labservices.models.UserUpdate + :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 User or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.User] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + lab_name: str, + user_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.User]: + """Update a lab user. + + Operation to update a lab user. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param user_name: The name of the user that uniquely identifies it within containing lab. Used + in resource URIs. Required. + :type user_name: str + :param body: The request body. Required. + :type body: IO + :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 User or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.User] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_update( @@ -632,23 +812,27 @@ def begin_update( resource_group_name: str, lab_name: str, user_name: str, - body: "_models.UserUpdate", + body: Union[_models.UserUpdate, IO], **kwargs: Any - ) -> LROPoller["_models.User"]: + ) -> LROPoller[_models.User]: """Update a lab user. Operation to update a lab user. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param user_name: The name of the user that uniquely identifies it within containing lab. Used - in resource URIs. + in resource URIs. Required. :type user_name: str - :param body: The request body. - :type body: ~azure.mgmt.labservices.models.UserUpdate + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.UserUpdate 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 @@ -659,107 +843,112 @@ def begin_update( Retry-After header is present. :return: An instance of LROPoller that returns either User or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.labservices.models.User] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.User"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.User] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._update_initial( + raw_result = self._update_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('User', pipeline_response) + deserialized = self._deserialize("User", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}'} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}"} # type: ignore - def _delete_initial( - self, - resource_group_name: str, - lab_name: str, - user_name: str, - **kwargs: Any + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, user_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, - template_url=self._delete_initial.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}"} # type: ignore @distributed_trace - def begin_delete( - self, - resource_group_name: str, - lab_name: str, - user_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_delete(self, resource_group_name: str, lab_name: str, user_name: str, **kwargs: Any) -> LROPoller[None]: """Deletes a user resource. Operation to delete a user resource. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param user_name: The name of the user that uniquely identifies it within containing lab. Used - in resource URIs. + in resource URIs. Required. :type user_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. @@ -771,87 +960,193 @@ def begin_delete( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._delete_initial( + raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}"} # type: ignore - def _invite_initial( + def _invite_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, lab_name: str, user_name: str, - body: "_models.InviteBody", + body: Union[_models.InviteBody, IO], **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(body, 'InviteBody') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] - request = build_invite_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "InviteBody") + + request = build_invite_request( resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._invite_initial.metadata['url'], + content=_content, + template_url=self._invite_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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _invite_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}/invite'} # type: ignore + _invite_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}/invite"} # type: ignore + @overload + def begin_invite( + self, + resource_group_name: str, + lab_name: str, + user_name: str, + body: _models.InviteBody, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Invite a user to a lab. + + Operation to invite a user to a lab. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param user_name: The name of the user that uniquely identifies it within containing lab. Used + in resource URIs. Required. + :type user_name: str + :param body: The request body. Required. + :type body: ~azure.mgmt.labservices.models.InviteBody + :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 None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_invite( + self, + resource_group_name: str, + lab_name: str, + user_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Invite a user to a lab. + + Operation to invite a user to a lab. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param user_name: The name of the user that uniquely identifies it within containing lab. Used + in resource URIs. Required. + :type user_name: str + :param body: The request body. Required. + :type body: IO + :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 None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_invite( @@ -859,7 +1154,7 @@ def begin_invite( resource_group_name: str, lab_name: str, user_name: str, - body: "_models.InviteBody", + body: Union[_models.InviteBody, IO], **kwargs: Any ) -> LROPoller[None]: """Invite a user to a lab. @@ -867,15 +1162,19 @@ def begin_invite( Operation to invite a user to a lab. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param user_name: The name of the user that uniquely identifies it within containing lab. Used - in resource URIs. + in resource URIs. Required. :type user_name: str - :param body: The request body. - :type body: ~azure.mgmt.labservices.models.InviteBody + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.InviteBody 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 @@ -886,44 +1185,51 @@ def begin_invite( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._invite_initial( + raw_result = self._invite_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, user_name=user_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_invite.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}/invite'} # type: ignore + begin_invite.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/users/{userName}/invite"} # type: ignore diff --git a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_virtual_machines_operations.py b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_virtual_machines_operations.py index a359b3419b91..66e91c311efb 100644 --- a/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_virtual_machines_operations.py +++ b/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_virtual_machines_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,375 +6,394 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + 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.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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_by_lab_request( - subscription_id: str, - resource_group_name: str, - lab_name: str, - *, - filter: Optional[str] = None, - **kwargs: Any + resource_group_name: str, lab_name: str, subscription_id: str, *, filter: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: - query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + resource_group_name: str, lab_name: str, virtual_machine_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), - "virtualMachineName": _SERIALIZER.url("virtual_machine_name", virtual_machine_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), + "virtualMachineName": _SERIALIZER.url( + "virtual_machine_name", + virtual_machine_name, + "str", + max_length=100, + min_length=1, + pattern=r"^[-\w\\._\\(\\)]+$", + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_start_request_initial( - subscription_id: str, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_start_request( + resource_group_name: str, lab_name: str, virtual_machine_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/start') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/start", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), - "virtualMachineName": _SERIALIZER.url("virtual_machine_name", virtual_machine_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), + "virtualMachineName": _SERIALIZER.url( + "virtual_machine_name", + virtual_machine_name, + "str", + max_length=100, + min_length=1, + pattern=r"^[-\w\\._\\(\\)]+$", + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_stop_request_initial( - subscription_id: str, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_stop_request( + resource_group_name: str, lab_name: str, virtual_machine_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/stop') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/stop", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), - "virtualMachineName": _SERIALIZER.url("virtual_machine_name", virtual_machine_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), + "virtualMachineName": _SERIALIZER.url( + "virtual_machine_name", + virtual_machine_name, + "str", + max_length=100, + min_length=1, + pattern=r"^[-\w\\._\\(\\)]+$", + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_reimage_request_initial( - subscription_id: str, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reimage_request( + resource_group_name: str, lab_name: str, virtual_machine_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/reimage') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/reimage", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), - "virtualMachineName": _SERIALIZER.url("virtual_machine_name", virtual_machine_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), + "virtualMachineName": _SERIALIZER.url( + "virtual_machine_name", + virtual_machine_name, + "str", + max_length=100, + min_length=1, + pattern=r"^[-\w\\._\\(\\)]+$", + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_redeploy_request_initial( - subscription_id: str, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_redeploy_request( + resource_group_name: str, lab_name: str, virtual_machine_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-11-15-preview" - accept = "application/json" + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/redeploy') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/redeploy", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), - "virtualMachineName": _SERIALIZER.url("virtual_machine_name", virtual_machine_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), + "virtualMachineName": _SERIALIZER.url( + "virtual_machine_name", + virtual_machine_name, + "str", + max_length=100, + min_length=1, + pattern=r"^[-\w\\._\\(\\)]+$", + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_reset_password_request_initial( - subscription_id: str, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reset_password_request( + resource_group_name: str, lab_name: str, virtual_machine_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-11-15-preview" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/resetPassword') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/resetPassword", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "labName": _SERIALIZER.url("lab_name", lab_name, 'str', max_length=100, min_length=1), - "virtualMachineName": _SERIALIZER.url("virtual_machine_name", virtual_machine_name, 'str', max_length=100, min_length=1, pattern=r'^[-\w\\._\\(\\)]+$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "labName": _SERIALIZER.url("lab_name", lab_name, "str", max_length=100, min_length=1), + "virtualMachineName": _SERIALIZER.url( + "virtual_machine_name", + virtual_machine_name, + "str", + max_length=100, + min_length=1, + pattern=r"^[-\w\\._\\(\\)]+$", + ), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - -class VirtualMachinesOperations(object): - """VirtualMachinesOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.labservices.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _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 VirtualMachinesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.labservices.ManagedLabsClient`'s + :attr:`virtual_machines` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_by_lab( - self, - resource_group_name: str, - lab_name: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.PagedVirtualMachines"]: + self, resource_group_name: str, lab_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.VirtualMachine"]: """Get all virtual machines for a lab. Returns a list of all virtual machines for a lab. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str - :param filter: The filter to apply to the operation. + :param filter: The filter to apply to the operation. 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 PagedVirtualMachines or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.PagedVirtualMachines] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either VirtualMachine or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.labservices.models.VirtualMachine] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PagedVirtualMachines"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PagedVirtualMachines] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_lab_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, + subscription_id=self._config.subscription_id, filter=filter, - template_url=self.list_by_lab.metadata['url'], + api_version=api_version, + template_url=self.list_by_lab.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) # type: ignore else: - - request = build_list_by_lab_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - lab_name=lab_name, - filter=filter, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -387,7 +407,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -397,55 +419,58 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_lab.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines'} # type: ignore + list_by_lab.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines"} # type: ignore @distributed_trace def get( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any - ) -> "_models.VirtualMachine": + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any + ) -> _models.VirtualMachine: """Get a lab virtual machine. Returns the properties for a lab virtual machine. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within - the containing lab. Used in resource URIs. + the containing lab. Used in resource URIs. Required. :type virtual_machine_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: VirtualMachine, or the result of cls(response) + :return: VirtualMachine or the result of cls(response) :rtype: ~azure.mgmt.labservices.models.VirtualMachine - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualMachine"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.VirtualMachine] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - template_url=self.get.metadata['url'], + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -453,72 +478,72 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('VirtualMachine', pipeline_response) + deserialized = self._deserialize("VirtualMachine", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}"} # type: ignore - def _start_initial( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + def _start_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_start_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_start_request( resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - template_url=self._start_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._start_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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _start_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/start'} # type: ignore - + _start_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/start"} # type: ignore @distributed_trace def begin_start( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> LROPoller[None]: """Start a lab virtual machine. Action to start a lab virtual machine. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within - the containing lab. Used in resource URIs. + the containing lab. Used in resource URIs. Required. :type virtual_machine_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. @@ -530,101 +555,109 @@ def begin_start( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._start_initial( + raw_result = self._start_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_start.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/start'} # type: ignore + begin_start.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/start"} # type: ignore - def _stop_initial( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + def _stop_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_stop_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_stop_request( resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - template_url=self._stop_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._stop_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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _stop_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/stop'} # type: ignore - + _stop_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/stop"} # type: ignore @distributed_trace def begin_stop( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> LROPoller[None]: """Stop a lab virtual machine. Action to stop a lab virtual machine. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within - the containing lab. Used in resource URIs. + the containing lab. Used in resource URIs. Required. :type virtual_machine_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. @@ -636,89 +669,96 @@ def begin_stop( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._stop_initial( + raw_result = self._stop_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_stop.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/stop'} # type: ignore + begin_stop.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/stop"} # type: ignore - def _reimage_initial( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + def _reimage_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_reimage_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_reimage_request( resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - template_url=self._reimage_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._reimage_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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _reimage_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/reimage'} # type: ignore - + _reimage_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/reimage"} # type: ignore @distributed_trace def begin_reimage( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> LROPoller[None]: """Re-image a lab virtual machine. @@ -726,12 +766,13 @@ def begin_reimage( latest published snapshot of the reference environment of the lab. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within - the containing lab. Used in resource URIs. + the containing lab. Used in resource URIs. Required. :type virtual_machine_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. @@ -743,89 +784,96 @@ def begin_reimage( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._reimage_initial( + raw_result = self._reimage_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_reimage.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/reimage'} # type: ignore + begin_reimage.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/reimage"} # type: ignore - def _redeploy_initial( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + def _redeploy_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_redeploy_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_redeploy_request( resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - template_url=self._redeploy_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._redeploy_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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _redeploy_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/redeploy'} # type: ignore - + _redeploy_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/redeploy"} # type: ignore @distributed_trace def begin_redeploy( - self, - resource_group_name: str, - lab_name: str, - virtual_machine_name: str, - **kwargs: Any + self, resource_group_name: str, lab_name: str, virtual_machine_name: str, **kwargs: Any ) -> LROPoller[None]: """Redeploy a lab virtual machine to a different compute node. For troubleshooting connectivity. @@ -833,12 +881,13 @@ def begin_redeploy( connectivity. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within - the containing lab. Used in resource URIs. + the containing lab. Used in resource URIs. Required. :type virtual_machine_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. @@ -850,87 +899,193 @@ def begin_redeploy( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._redeploy_initial( + raw_result = self._redeploy_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_redeploy.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/redeploy'} # type: ignore + begin_redeploy.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/redeploy"} # type: ignore - def _reset_password_initial( + def _reset_password_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, lab_name: str, virtual_machine_name: str, - body: "_models.ResetPasswordBody", + body: Union[_models.ResetPasswordBody, IO], **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(body, 'ResetPasswordBody') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] - request = build_reset_password_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ResetPasswordBody") + + request = build_reset_password_request( resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._reset_password_initial.metadata['url'], + content=_content, + template_url=self._reset_password_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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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, {}) - _reset_password_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/resetPassword'} # type: ignore + _reset_password_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/resetPassword"} # type: ignore + @overload + def begin_reset_password( + self, + resource_group_name: str, + lab_name: str, + virtual_machine_name: str, + body: _models.ResetPasswordBody, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Reset a lab virtual machine password. + + Resets a lab virtual machine password. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within + the containing lab. Used in resource URIs. Required. + :type virtual_machine_name: str + :param body: The request body. Required. + :type body: ~azure.mgmt.labservices.models.ResetPasswordBody + :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 None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_reset_password( + self, + resource_group_name: str, + lab_name: str, + virtual_machine_name: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Reset a lab virtual machine password. + + Resets a lab virtual machine password. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. + :type lab_name: str + :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within + the containing lab. Used in resource URIs. Required. + :type virtual_machine_name: str + :param body: The request body. Required. + :type body: IO + :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 None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_reset_password( @@ -938,7 +1093,7 @@ def begin_reset_password( resource_group_name: str, lab_name: str, virtual_machine_name: str, - body: "_models.ResetPasswordBody", + body: Union[_models.ResetPasswordBody, IO], **kwargs: Any ) -> LROPoller[None]: """Reset a lab virtual machine password. @@ -946,15 +1101,19 @@ def begin_reset_password( Resets a lab virtual machine password. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param lab_name: The name of the lab that uniquely identifies it within containing lab account. - Used in resource URIs. + :param lab_name: The name of the lab that uniquely identifies it within containing lab plan. + Used in resource URIs. Required. :type lab_name: str :param virtual_machine_name: The ID of the virtual machine that uniquely identifies it within - the containing lab. Used in resource URIs. + the containing lab. Used in resource URIs. Required. :type virtual_machine_name: str - :param body: The request body. - :type body: ~azure.mgmt.labservices.models.ResetPasswordBody + :param body: The request body. Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.labservices.models.ResetPasswordBody 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 @@ -965,44 +1124,51 @@ def begin_reset_password( 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 + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._reset_password_initial( + raw_result = self._reset_password_initial( # type: ignore resource_group_name=resource_group_name, lab_name=lab_name, virtual_machine_name=virtual_machine_name, body=body, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_reset_password.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/resetPassword'} # type: ignore + begin_reset_password.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/resetPassword"} # type: ignore