diff --git a/sdk/orbital/azure-mgmt-orbital/CHANGELOG.md b/sdk/orbital/azure-mgmt-orbital/CHANGELOG.md index b929ed45f091..2f99706f7b7e 100644 --- a/sdk/orbital/azure-mgmt-orbital/CHANGELOG.md +++ b/sdk/orbital/azure-mgmt-orbital/CHANGELOG.md @@ -1,5 +1,67 @@ # Release History +## 3.0.0 (2025-05-06) + +### Features Added + + - Added model `AzureResourceManagerArmResponseAvailableContactsListResult` + - Method `ContactProfilesOperations.begin_create_or_update` has a new overload `def begin_create_or_update(self: None, resource_group_name: str, contact_profile_name: str, parameters: ContactProfile, content_type: str)` + - Method `ContactProfilesOperations.begin_create_or_update` has a new overload `def begin_create_or_update(self: None, resource_group_name: str, contact_profile_name: str, parameters: IO[bytes], content_type: str)` + - Method `ContactProfilesOperations.begin_update_tags` has a new overload `def begin_update_tags(self: None, resource_group_name: str, contact_profile_name: str, parameters: IO[bytes], content_type: str)` + - Method `ContactsOperations.begin_create` has a new overload `def begin_create(self: None, resource_group_name: str, spacecraft_name: str, contact_name: str, parameters: IO[bytes], content_type: str)` + - Method `SpacecraftsOperations.begin_create_or_update` has a new overload `def begin_create_or_update(self: None, resource_group_name: str, spacecraft_name: str, parameters: Spacecraft, content_type: str)` + - Method `SpacecraftsOperations.begin_create_or_update` has a new overload `def begin_create_or_update(self: None, resource_group_name: str, spacecraft_name: str, parameters: IO[bytes], content_type: str)` + - Method `SpacecraftsOperations.begin_list_available_contacts` has a new overload `def begin_list_available_contacts(self: None, resource_group_name: str, spacecraft_name: str, parameters: ContactParameters, content_type: str)` + - Method `SpacecraftsOperations.begin_list_available_contacts` has a new overload `def begin_list_available_contacts(self: None, resource_group_name: str, spacecraft_name: str, parameters: IO[bytes], content_type: str)` + - Method `SpacecraftsOperations.begin_update_tags` has a new overload `def begin_update_tags(self: None, resource_group_name: str, spacecraft_name: str, parameters: IO[bytes], content_type: str)` + +### Breaking Changes + + - Method `AvailableContactsListResult.__init__` removed default value `None` from its parameter `value` + - Method `AvailableGroundStationListResult.__init__` removed default value `None` from its parameter `value` + - Method `ContactListResult.__init__` removed default value `None` from its parameter `value` + - Method `ContactProfileListResult.__init__` removed default value `None` from its parameter `value` + - Method `SpacecraftListResult.__init__` removed default value `None` from its parameter `value` + - Deleted or renamed model `AvailableContactsProperties` + - Deleted or renamed model `AvailableContactsSpacecraft` + - Deleted or renamed model `AvailableGroundStationProperties` + - Deleted or renamed model `AvailableGroundStationPropertiesAutoGenerated` + - Deleted or renamed model `Capability` + - Deleted or renamed model `ContactInstanceProperties` + - Deleted or renamed model `ContactParametersContactProfile` + - Deleted or renamed model `ContactProfileProperties` + - Deleted or renamed model `ContactProfilesProperties` + - Deleted or renamed model `ContactProfilesPropertiesProvisioningState` + - Deleted or renamed model `ContactsPropertiesContactProfile` + - Deleted or renamed model `ContactsPropertiesProvisioningState` + - Deleted or renamed model `ResourceIdListResultValueItem` + - Method `ContactProfilesOperations.begin_create_or_update` inserted a `positional_or_keyword` parameter `parameters` + - Method `ContactProfilesOperations.begin_create_or_update` deleted or renamed its parameter `location` of kind `positional_or_keyword` + - Method `ContactProfilesOperations.begin_create_or_update` deleted or renamed its parameter `network_configuration` of kind `positional_or_keyword` + - Method `ContactProfilesOperations.begin_create_or_update` deleted or renamed its parameter `links` of kind `positional_or_keyword` + - Method `ContactProfilesOperations.begin_create_or_update` deleted or renamed its parameter `tags` of kind `positional_or_keyword` + - Method `ContactProfilesOperations.begin_create_or_update` deleted or renamed its parameter `provisioning_state` of kind `positional_or_keyword` + - Method `ContactProfilesOperations.begin_create_or_update` deleted or renamed its parameter `minimum_viable_contact_duration` of kind `positional_or_keyword` + - Method `ContactProfilesOperations.begin_create_or_update` deleted or renamed its parameter `minimum_elevation_degrees` of kind `positional_or_keyword` + - Method `ContactProfilesOperations.begin_create_or_update` deleted or renamed its parameter `auto_tracking_configuration` of kind `positional_or_keyword` + - Method `ContactProfilesOperations.begin_create_or_update` deleted or renamed its parameter `event_hub_uri` of kind `positional_or_keyword` + - Method `ContactProfilesOperations.begin_create_or_update` deleted or renamed its parameter `third_party_configurations` of kind `positional_or_keyword` + - Deleted or renamed method `OperationsResultsOperations.begin_get` + - Method `SpacecraftsOperations.begin_create_or_update` inserted a `positional_or_keyword` parameter `parameters` + - Method `SpacecraftsOperations.begin_create_or_update` deleted or renamed its parameter `location` of kind `positional_or_keyword` + - Method `SpacecraftsOperations.begin_create_or_update` deleted or renamed its parameter `title_line` of kind `positional_or_keyword` + - Method `SpacecraftsOperations.begin_create_or_update` deleted or renamed its parameter `tle_line1` of kind `positional_or_keyword` + - Method `SpacecraftsOperations.begin_create_or_update` deleted or renamed its parameter `tle_line2` of kind `positional_or_keyword` + - Method `SpacecraftsOperations.begin_create_or_update` deleted or renamed its parameter `links` of kind `positional_or_keyword` + - Method `SpacecraftsOperations.begin_create_or_update` deleted or renamed its parameter `tags` of kind `positional_or_keyword` + - Method `SpacecraftsOperations.begin_create_or_update` deleted or renamed its parameter `provisioning_state` of kind `positional_or_keyword` + - Method `SpacecraftsOperations.begin_create_or_update` deleted or renamed its parameter `norad_id` of kind `positional_or_keyword` + - Method `SpacecraftsOperations.begin_list_available_contacts` inserted a `positional_or_keyword` parameter `parameters` + - Method `SpacecraftsOperations.begin_list_available_contacts` deleted or renamed its parameter `contact_profile` of kind `positional_or_keyword` + - Method `SpacecraftsOperations.begin_list_available_contacts` deleted or renamed its parameter `ground_station_name` of kind `positional_or_keyword` + - Method `SpacecraftsOperations.begin_list_available_contacts` deleted or renamed its parameter `start_time` of kind `positional_or_keyword` + - Method `SpacecraftsOperations.begin_list_available_contacts` deleted or renamed its parameter `end_time` of kind `positional_or_keyword` + ## 2.0.0 (2023-03-20) ### Features Added diff --git a/sdk/orbital/azure-mgmt-orbital/README.md b/sdk/orbital/azure-mgmt-orbital/README.md index 484b5ce766f7..f416b1f3081c 100644 --- a/sdk/orbital/azure-mgmt-orbital/README.md +++ b/sdk/orbital/azure-mgmt-orbital/README.md @@ -1,7 +1,7 @@ # Microsoft Azure SDK for Python This is the Microsoft Azure Orbital Management Client Library. -This package has been tested with Python 3.7+. +This package has been tested with Python 3.9+. For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). ## _Disclaimer_ @@ -12,7 +12,7 @@ _Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For ### Prerequisites -- Python 3.7+ is required to use this package. +- Python 3.9+ is required to use this package. - [Azure subscription](https://azure.microsoft.com/free/) ### Install the package @@ -24,7 +24,7 @@ pip install azure-identity ### Authentication -By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configure of following environment variables. +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. - `AZURE_CLIENT_ID` for Azure client ID. - `AZURE_TENANT_ID` for Azure tenant ID. @@ -45,8 +45,9 @@ client = AzureOrbital(credential=DefaultAzureCredential(), subscription_id=sub_i ## Examples - -Code samples for this package can be found at [Orbital Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com and [Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) +Code samples for this package can be found at: +- [Search Orbital Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) ## Troubleshooting @@ -58,6 +59,3 @@ Code samples for this package can be found at [Orbital Management](https://docs. If you encounter any bugs or have suggestions, please file an issue in the [Issues](https://github.com/Azure/azure-sdk-for-python/issues) section of the project. - - - diff --git a/sdk/orbital/azure-mgmt-orbital/_meta.json b/sdk/orbital/azure-mgmt-orbital/_meta.json index ab9eef4839f7..bd91aae511e4 100644 --- a/sdk/orbital/azure-mgmt-orbital/_meta.json +++ b/sdk/orbital/azure-mgmt-orbital/_meta.json @@ -1,11 +1,11 @@ { - "commit": "66174681c09b101de03fd35399080cfbccc93e8f", + "commit": "14ddb11bf9f301e56ffae91fddb70d797b8918ca", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest": "3.9.2", + "autorest": "3.10.2", "use": [ - "@autorest/python@6.4.0", - "@autorest/modelerfour@4.24.3" + "@autorest/python@6.34.1", + "@autorest/modelerfour@4.27.0" ], - "autorest_command": "autorest specification/orbital/resource-manager/readme.md --generate-sample=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/home/vsts/work/1/azure-sdk-for-python/sdk --use=@autorest/python@6.4.0 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", + "autorest_command": "autorest specification/orbital/resource-manager/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.34.1 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", "readme": "specification/orbital/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/__init__.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/__init__.py index 287bf8d3df3b..7b552e8af9e7 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/__init__.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/__init__.py @@ -5,15 +5,21 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._azure_orbital import AzureOrbital +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._azure_orbital import AzureOrbital # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk @@ -21,6 +27,6 @@ __all__ = [ "AzureOrbital", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_azure_orbital.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_azure_orbital.py index 724de415c12b..d0915ff2d4ba 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_azure_orbital.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_azure_orbital.py @@ -7,14 +7,19 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, TYPE_CHECKING +from typing import Any, Optional, TYPE_CHECKING, cast +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints from . import models as _models from ._configuration import AzureOrbitalConfiguration -from ._serialization import Deserializer, Serializer +from ._utils.serialization import Deserializer, Serializer from .operations import ( AvailableGroundStationsOperations, ContactProfilesOperations, @@ -25,31 +30,30 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class AzureOrbital: # pylint: disable=client-accepts-api-version-keyword +class AzureOrbital: """Azure Orbital service. :ivar operations: Operations operations :vartype operations: azure.mgmt.orbital.operations.Operations - :ivar spacecrafts: SpacecraftsOperations operations - :vartype spacecrafts: azure.mgmt.orbital.operations.SpacecraftsOperations - :ivar contacts: ContactsOperations operations - :vartype contacts: azure.mgmt.orbital.operations.ContactsOperations - :ivar contact_profiles: ContactProfilesOperations operations - :vartype contact_profiles: azure.mgmt.orbital.operations.ContactProfilesOperations :ivar available_ground_stations: AvailableGroundStationsOperations operations :vartype available_ground_stations: azure.mgmt.orbital.operations.AvailableGroundStationsOperations + :ivar contact_profiles: ContactProfilesOperations operations + :vartype contact_profiles: azure.mgmt.orbital.operations.ContactProfilesOperations :ivar operations_results: OperationsResultsOperations operations :vartype operations_results: azure.mgmt.orbital.operations.OperationsResultsOperations + :ivar spacecrafts: SpacecraftsOperations operations + :vartype spacecrafts: azure.mgmt.orbital.operations.SpacecraftsOperations + :ivar contacts: ContactsOperations operations + :vartype contacts: azure.mgmt.orbital.operations.ContactsOperations :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". + :param base_url: Service URL. Default value is None. :type base_url: str :keyword api_version: Api Version. Default value is "2022-11-01". Note that overriding this default value may result in unsupported behavior. @@ -59,33 +63,55 @@ class AzureOrbital: # pylint: disable=client-accepts-api-version-keyword """ def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - base_url: str = "https://management.azure.com", - **kwargs: Any + self, credential: "TokenCredential", subscription_id: str, base_url: Optional[str] = None, **kwargs: Any ) -> None: - self._config = AzureOrbitalConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) - self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + _cloud = kwargs.pop("cloud_setting", None) or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = AzureOrbitalConfiguration( + credential=credential, subscription_id=subscription_id, credential_scopes=credential_scopes, **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.spacecrafts = SpacecraftsOperations(self._client, self._config, self._serialize, self._deserialize) - self.contacts = ContactsOperations(self._client, self._config, self._serialize, self._deserialize) - self.contact_profiles = ContactProfilesOperations( + self.available_ground_stations = AvailableGroundStationsOperations( self._client, self._config, self._serialize, self._deserialize ) - self.available_ground_stations = AvailableGroundStationsOperations( + self.contact_profiles = ContactProfilesOperations( self._client, self._config, self._serialize, self._deserialize ) self.operations_results = OperationsResultsOperations( self._client, self._config, self._serialize, self._deserialize ) + self.spacecrafts = SpacecraftsOperations(self._client, self._config, self._serialize, self._deserialize) + self.contacts = ContactsOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -105,12 +131,12 @@ def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore def close(self) -> None: self._client.close() - def __enter__(self) -> "AzureOrbital": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_configuration.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_configuration.py index 208b1cae18f2..21a61e97b084 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_configuration.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_configuration.py @@ -6,26 +6,18 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports - if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class AzureOrbitalConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class AzureOrbitalConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for AzureOrbital. Note that all parameters used to create this instance are saved as instance @@ -41,8 +33,7 @@ class AzureOrbitalConfiguration(Configuration): # pylint: disable=too-many-inst """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(AzureOrbitalConfiguration, self).__init__(**kwargs) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", "2022-11-01") + api_version: str = kwargs.pop("api_version", "2022-11-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -54,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-orbital/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -62,9 +54,9 @@ def _configure(self, **kwargs: Any) -> None: self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = ARMChallengeAuthenticationPolicy( diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_patch.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_patch.py index f99e77fef986..17dbc073e01b 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_patch.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_patch.py @@ -25,6 +25,7 @@ # # -------------------------------------------------------------------------- + # 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(): diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_utils/__init__.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_utils/__init__.py new file mode 100644 index 000000000000..0af9b28f6607 --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_serialization.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_utils/serialization.py similarity index 79% rename from sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_serialization.py rename to sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_utils/serialization.py index f17c068e833e..f5187701d7be 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_serialization.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_utils/serialization.py @@ -1,30 +1,12 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# 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. # -------------------------------------------------------------------------- -# pylint: skip-file # pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode @@ -48,11 +30,8 @@ IO, Mapping, Callable, - TypeVar, MutableMapping, - Type, List, - Mapping, ) try: @@ -62,13 +41,13 @@ import xml.etree.ElementTree as ET import isodate # type: ignore +from typing_extensions import Self -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback -from azure.core.serialization import NULL as AzureCoreNull +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") -ModelType = TypeVar("ModelType", bound="Model") JSON = MutableMapping[str, Any] @@ -91,6 +70,8 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: :param data: Input, could be bytes or stream (will be decoded with UTF8) or text :type data: str or bytes or IO :param str content_type: The content type. + :return: The deserialized data. + :rtype: object """ if hasattr(data, "read"): # Assume a stream @@ -112,7 +93,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: try: return json.loads(data_as_str) except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) + raise DeserializationError("JSON is invalid: {}".format(err), err) from err elif "xml" in (content_type or []): try: @@ -124,7 +105,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: pass return ET.fromstring(data_as_str) # nosec - except ET.ParseError: + except ET.ParseError as err: # It might be because the server has an issue, and returned JSON with # content-type XML.... # So let's try a JSON load, and if it's still broken @@ -143,7 +124,9 @@ def _json_attemp(data): # The function hack is because Py2.7 messes up with exception # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod @@ -153,6 +136,11 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], Use bytes and headers to NOT use any requests/aiohttp or whatever specific implementation. Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object """ # Try to use content-type from headers if available content_type = None @@ -170,13 +158,6 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], return None -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str - unicode_str = str - _LOGGER = logging.getLogger(__name__) try: @@ -184,80 +165,31 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], 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 # type: ignore -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 -except ImportError: - TZ_UTC = UTC() # type: ignore +TZ_UTC = datetime.timezone.utc _FLATTEN = re.compile(r"(? None: - self.additional_properties: Dict[str, Any] = {} - for k in kwargs: + self.additional_properties: Optional[Dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items if k not in self._attribute_map: _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) elif k in self._validation and self._validation[k].get("readonly", False): @@ -305,13 +244,23 @@ def __init__(self, **kwargs: Any) -> None: setattr(self, k, kwargs[k]) def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ return not self.__eq__(other) def __str__(self) -> str: @@ -331,7 +280,11 @@ def is_xml_model(cls) -> bool: @classmethod def _create_xml_node(cls): - """Create XML node.""" + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ try: xml_map = cls._xml_map # type: ignore except AttributeError: @@ -340,7 +293,7 @@ def _create_xml_node(cls): return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to azure from this model. + """Return the JSON that would be sent to server from this model. This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. @@ -351,7 +304,9 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) def as_dict( self, @@ -385,12 +340,15 @@ def my_key_transformer(key, attr_desc, value): If you want XML serialization, you can pass the kwargs is_xml=True. + :param bool keep_readonly: If you want to serialize the readonly attributes :param function key_transformer: A key transformer function. :returns: A dict JSON compatible object :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) @classmethod def _infer_class_models(cls): @@ -400,30 +358,31 @@ def _infer_class_models(cls): client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} if cls.__name__ not in client_models: raise ValueError("Not Autorest generated code") - except Exception: + except Exception: # pylint: disable=broad-exception-caught # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. client_models = {cls.__name__: cls} return client_models @classmethod - def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: """Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def from_dict( - cls: Type[ModelType], + cls, data: Any, key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, content_type: Optional[str] = None, - ) -> ModelType: + ) -> Self: """Parse a dict using given key extractor return a model. By default consider key @@ -431,9 +390,11 @@ def from_dict( and last_rest_key_case_insensitive_extractor) :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = ( # type: ignore @@ -445,7 +406,7 @@ def from_dict( if key_extractors is None else key_extractors ) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def _flatten_subtype(cls, key, objects): @@ -453,21 +414,25 @@ def _flatten_subtype(cls, key, objects): return {} result = dict(cls._subtype_map[key]) for valuetype in cls._subtype_map[key].values(): - result.update(objects[valuetype]._flatten_subtype(key, objects)) + result.update(objects[valuetype]._flatten_subtype(key, objects)) # pylint: disable=protected-access return result @classmethod def _classify(cls, response, objects): """Check the class _subtype_map for any child classes. We want to ignore any inherited _subtype_maps. - Remove the polymorphic key from the initial data. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class """ for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): subtype_value = None if not isinstance(response, ET.Element): rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) else: subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) if subtype_value: @@ -506,11 +471,13 @@ def _decode_attribute_map_key(key): inside the received data. :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str """ return key.replace("\\.", ".") -class Serializer(object): +class Serializer: # pylint: disable=too-many-public-methods """Request object model serializer.""" basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -545,7 +512,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -561,17 +528,20 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_transformer = full_restapi_key_transformer self.client_side_validation = True - def _serialize(self, target_obj, data_type=None, **kwargs): + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): """Serialize data into a string according to type. - :param target_obj: The data to be serialized. + :param object target_obj: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str, dict - :raises: SerializationError if serialization fails. + :raises SerializationError: if serialization fails. + :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) @@ -597,12 +567,14 @@ def _serialize(self, target_obj, data_type=None, **kwargs): serialized = {} if is_xml_model_serialization: - serialized = target_obj._create_xml_node() + serialized = target_obj._create_xml_node() # pylint: disable=protected-access try: - attributes = target_obj._attribute_map + attributes = target_obj._attribute_map # pylint: disable=protected-access for attr, attr_desc in attributes.items(): attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): continue if attr_name == "additional_properties" and attr_desc["key"] == "": @@ -629,7 +601,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if xml_desc.get("attr", False): if xml_ns: ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) serialized.set(xml_name, new_attr) # type: ignore continue if xml_desc.get("text", False): @@ -638,7 +610,8 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if isinstance(new_attr, list): serialized.extend(new_attr) # type: ignore elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. if "name" not in getattr(orig_attr, "_xml_map", {}): splitted_tag = new_attr.tag.split("}") if len(splitted_tag) == 2: # Namespace @@ -649,7 +622,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): else: # That's a basic type # Integrate namespace if necessary local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) + local_node.text = str(new_attr) serialized.append(local_node) # type: ignore else: # JSON for k in reversed(keys): # type: ignore @@ -662,23 +635,24 @@ def _serialize(self, target_obj, data_type=None, **kwargs): _serialized.update(_new_attr) # type: ignore _new_attr = _new_attr[k] # type: ignore _serialized = _serialized[k] - except ValueError: - continue + except ValueError as err: + if isinstance(err, SerializationError): + raise except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized + raise SerializationError(msg) from err + return serialized def body(self, data, data_type, **kwargs): """Serialize data intended for a request body. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body """ # Just in case this is a dict @@ -707,20 +681,22 @@ def body(self, data, data_type, **kwargs): attribute_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, ] - data = deserializer._deserialize(data_type, data) + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + raise SerializationError("Unable to build a model: " + str(err)) from err return self._serialize(data, data_type, **kwargs) def url(self, name, data, data_type, **kwargs): """Serialize data intended for a URL path. - :param data: The data to be serialized. + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None """ try: output = self.serialize_data(data, data_type, **kwargs) @@ -729,30 +705,30 @@ def url(self, name, data, data_type, **kwargs): if kwargs.get("skip_quote") is True: output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output def query(self, name, data, data_type, **kwargs): """Serialize data intended for a URL query. - :param data: The data to be serialized. + :param str name: The name of the query parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter """ try: # Treat the list aside, since we don't want to encode the div separator if data_type.startswith("["): internal_data_type = data_type[1:-1] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) # Not a list, regular serialization output = self.serialize_data(data, data_type, **kwargs) @@ -762,19 +738,20 @@ def query(self, name, data, data_type, **kwargs): output = str(output) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def header(self, name, data, data_type, **kwargs): """Serialize data intended for a request header. - :param data: The data to be serialized. + :param str name: The name of the header. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header """ try: if data_type in ["[str]"]: @@ -783,32 +760,31 @@ def header(self, name, data, data_type, **kwargs): output = self.serialize_data(data, data_type, **kwargs) if data_type == "bool": output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def serialize_data(self, data, data_type, **kwargs): """Serialize generic data according to supplied data type. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list """ if data is None: raise ValueError("No value for given attribute") try: - if data is AzureCoreNull: + if data is CoreNull: return None if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) - elif data_type in self.serialize_type: + if data_type in self.serialize_type: return self.serialize_type[data_type](data, **kwargs) # If dependencies is empty, try with current data class @@ -823,12 +799,11 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) if custom_serializer: return custom_serializer @@ -844,23 +819,26 @@ def serialize_basic(cls, data, data_type, **kwargs): - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - is_xml bool : If set, use xml_basic_types_serializers - :param data: Object to be serialized. + :param obj data: Object to be serialized. :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec + return eval(data_type)(data) # nosec # pylint: disable=eval-used @classmethod def serialize_unicode(cls, data): """Special handling for serializing unicode strings in Py2. Encode to UTF-8 if unicode, otherwise handle as a str. - :param data: Object to be serialized. + :param str data: Object to be serialized. :rtype: str + :return: serialized object """ try: # If I received an enum, return its value return data.value @@ -874,8 +852,7 @@ def serialize_unicode(cls, data): return data except NameError: return str(data) - else: - return str(data) + return str(data) def serialize_iter(self, data, iter_type, div=None, **kwargs): """Serialize iterable. @@ -885,13 +862,13 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): serialization_ctxt['type'] should be same as data_type. - is_xml bool : If set, serialize as XML - :param list attr: Object to be serialized. + :param list data: Object to be serialized. :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. :param str div: If set, this str will be used to combine the elements in the iterable into a combined string. Default is 'None'. + Defaults to False. :rtype: list, str + :return: serialized iterable """ if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") @@ -903,9 +880,14 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): for d in data: try: serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized.append(None) + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + if div: serialized = ["" if s is None else str(s) for s in serialized] serialized = div.join(serialized) @@ -941,16 +923,17 @@ def serialize_dict(self, attr, dict_type, **kwargs): :param dict attr: Object to be serialized. :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. :rtype: dict + :return: serialized dictionary """ serialization_ctxt = kwargs.get("serialization_ctxt", {}) serialized = {} for key, value in attr.items(): try: serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized[self.serialize_unicode(key)] = None if "xml" in serialization_ctxt: @@ -965,7 +948,7 @@ def serialize_dict(self, attr, dict_type, **kwargs): return serialized - def serialize_object(self, attr, **kwargs): + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Serialize a generic object. This will be handled as a dictionary. If object passed in is not a basic type (str, int, float, dict, list) it will simply be @@ -973,6 +956,7 @@ def serialize_object(self, attr, **kwargs): :param dict attr: Object to be serialized. :rtype: dict or str + :return: serialized object """ if attr is None: return None @@ -983,7 +967,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) if obj_type is _long_type: return self.serialize_long(attr) - if obj_type is unicode_str: + if obj_type is str: return self.serialize_unicode(attr) if obj_type is datetime.datetime: return self.serialize_iso(attr) @@ -997,7 +981,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_decimal(attr) # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): + if obj_type in self.dependencies.values() or isinstance(attr, Model): return self._serialize(attr) if obj_type == dict: @@ -1028,56 +1012,61 @@ def serialize_enum(attr, enum_obj=None): try: enum_obj(result) # type: ignore return result - except ValueError: + except ValueError as exc: for enum_value in enum_obj: # type: ignore if enum_value.value.lower() == str(attr).lower(): return enum_value.value error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) + raise SerializationError(error.format(attr, enum_obj)) from exc @staticmethod - def serialize_bytearray(attr, **kwargs): + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument """Serialize bytearray into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ return b64encode(attr).decode() @staticmethod - def serialize_base64(attr, **kwargs): + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument """Serialize str into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ encoded = b64encode(attr).decode("ascii") return encoded.strip("=").replace("+", "-").replace("/", "_") @staticmethod - def serialize_decimal(attr, **kwargs): + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument """Serialize Decimal object to float. - :param attr: Object to be serialized. + :param decimal attr: Object to be serialized. :rtype: float + :return: serialized decimal """ return float(attr) @staticmethod - def serialize_long(attr, **kwargs): + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument """Serialize long (Py2) or int (Py3). - :param attr: Object to be serialized. + :param int attr: Object to be serialized. :rtype: int/long + :return: serialized long """ return _long_type(attr) @staticmethod - def serialize_date(attr, **kwargs): + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument """Serialize Date object into ISO-8601 formatted string. :param Date attr: Object to be serialized. :rtype: str + :return: serialized date """ if isinstance(attr, str): attr = isodate.parse_date(attr) @@ -1085,11 +1074,12 @@ def serialize_date(attr, **kwargs): return t @staticmethod - def serialize_time(attr, **kwargs): + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument """Serialize Time object into ISO-8601 formatted string. :param datetime.time attr: Object to be serialized. :rtype: str + :return: serialized time """ if isinstance(attr, str): attr = isodate.parse_time(attr) @@ -1099,30 +1089,32 @@ def serialize_time(attr, **kwargs): return t @staticmethod - def serialize_duration(attr, **kwargs): + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument """Serialize TimeDelta object into ISO-8601 formatted string. :param TimeDelta attr: Object to be serialized. :rtype: str + :return: serialized duration """ if isinstance(attr, str): attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) @staticmethod - def serialize_rfc(attr, **kwargs): + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: TypeError if format invalid. + :raises TypeError: if format invalid. + :return: serialized rfc """ try: if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( Serializer.days[utc.tm_wday], @@ -1135,12 +1127,13 @@ def serialize_rfc(attr, **kwargs): ) @staticmethod - def serialize_iso(attr, **kwargs): + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into ISO-8601 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: SerializationError if format invalid. + :raises SerializationError: if format invalid. + :return: serialized iso """ if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -1160,19 +1153,20 @@ def serialize_iso(attr, **kwargs): return date + microseconds + "Z" except (ValueError, OverflowError) as err: msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err except AttributeError as err: msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) + raise TypeError(msg) from err @staticmethod - def serialize_unix(attr, **kwargs): + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into IntTime format. This is represented as seconds. :param Datetime attr: Object to be serialized. :rtype: int - :raises: SerializationError if format invalid + :raises SerializationError: if format invalid + :return: serialied unix """ if isinstance(attr, int): return attr @@ -1180,11 +1174,11 @@ def serialize_unix(attr, **kwargs): if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc -def rest_key_extractor(attr, attr_desc, data): +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument key = attr_desc["key"] working_data = data @@ -1199,14 +1193,15 @@ def rest_key_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) return working_data.get(key) -def rest_key_case_insensitive_extractor(attr, attr_desc, data): +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): key = attr_desc["key"] working_data = data @@ -1220,7 +1215,6 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1228,17 +1222,29 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): return attribute_key_case_insensitive_extractor(key, None, working_data) -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) return attribute_key_extractor(dict_keys[-1], None, data) -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument """Extract the attribute in "data" based on the last part of the JSON path key. This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) @@ -1271,11 +1277,11 @@ def _extract_name_from_internal_type(internal_type): 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) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) return xml_name -def xml_key_extractor(attr, attr_desc, data): +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements if isinstance(data, dict): return None @@ -1295,7 +1301,7 @@ def xml_key_extractor(attr, attr_desc, data): # 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) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) # If it's an attribute, that's simple if xml_desc.get("attr", False): @@ -1327,22 +1333,21 @@ def xml_key_extractor(attr, attr_desc, data): if is_iter_type: if is_wrapped: return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list + return [] # not wrapped, assume empty list return None # Assume it's not there, maybe an optional node. # If is_iter_type and not wrapped, return all found children if is_iter_type: if not is_wrapped: return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name ) - return list(children[0]) # Might be empty list and that's ok. + ) + return list(children[0]) # Might be empty list and that's ok. # Here it's not a itertype, we should have found one element only or empty if len(children) > 1: @@ -1350,7 +1355,7 @@ def xml_key_extractor(attr, attr_desc, data): return children[0] -class Deserializer(object): +class Deserializer: """Response object model deserializer. :param dict classes: Class type dictionary for deserializing complex types. @@ -1359,9 +1364,9 @@ class Deserializer(object): basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1381,7 +1386,7 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_extractors = [rest_key_extractor, xml_key_extractor] # Additional properties only works if the "rest_key_extractor" is used to # extract the keys. Making it to work whatever the key extractor is too much @@ -1397,27 +1402,29 @@ def __call__(self, target_obj, response_data, content_type=None): :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. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) - def _deserialize(self, target_obj, data): + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements """Call the deserializer on a model. Data needs to be already deserialized as JSON or XML ElementTree :param str target_obj: Target data type to deserialize to. :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ # This is already a model, go recursive just in case if hasattr(data, "_attribute_map"): constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] try: - for attr, mapconfig in data._attribute_map.items(): + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access if attr in constants: continue value = getattr(data, attr) @@ -1434,15 +1441,15 @@ def _deserialize(self, target_obj, data): response, class_name = self._classify_target(target_obj, data) - if isinstance(response, basestring): + if isinstance(response, str): return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): + if isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) - if data is None: + if data is None or data is CoreNull: return data try: - attributes = response._attribute_map # type: ignore + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access d_attrs = {} for attr, attr_desc in attributes.items(): # Check empty string. If it's not empty, someone has a real "additionalProperties"... @@ -1471,10 +1478,9 @@ def _deserialize(self, target_obj, data): d_attrs[attr] = value except (AttributeError, TypeError, KeyError) as err: msg = "Unable to deserialize to object: " + class_name # type: ignore - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) + raise DeserializationError(msg) from err + 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: @@ -1501,18 +1507,20 @@ def _classify_target(self, target, data): :param str target: The target object type to deserialize to. :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple """ if target is None: return None, None - if isinstance(target, basestring): + if isinstance(target, str): try: target = self.dependencies[target] except KeyError: return target, target try: - target = target._classify(data, self.dependencies) + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access except AttributeError: pass # Target is not a Model, no classify return target, target.__class__.__name__ # type: ignore @@ -1527,10 +1535,12 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): :param str target_obj: The target object type to deserialize to. :param str/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object """ try: return self(target_obj, data, content_type=content_type) - except: + except: # pylint: disable=bare-except _LOGGER.debug( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) @@ -1548,10 +1558,12 @@ def _unpack_content(raw_data, content_type=None): If raw_data is something else, bypass all logic and return it directly. - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. :raises JSONDecodeError: If JSON is requested and parsing is impossible. :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. """ # Assume this is enough to detect a Pipeline Response without importing it context = getattr(raw_data, "context", {}) @@ -1568,31 +1580,42 @@ def _unpack_content(raw_data, content_type=None): if hasattr(raw_data, "_content_consumed"): return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore return raw_data def _instantiate_model(self, response, attrs, additional_properties=None): """Instantiate a response model passing in deserialized args. - :param response: The response model class. - :param d_attrs: The deserialized response attributes. + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. """ if callable(response): subtype = getattr(response, "_subtype_map", {}) try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + 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 + response_obj.additional_properties = additional_properties # type: ignore return response_obj except TypeError as err: msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) + raise DeserializationError(msg + str(err)) from err else: try: for attr, value in attrs.items(): @@ -1601,15 +1624,16 @@ def _instantiate_model(self, response, attrs, additional_properties=None): except Exception as exp: msg = "Unable to populate response model. " msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) + raise DeserializationError(msg) from exp - def deserialize_data(self, data, data_type): + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements """Process data for deserialization according to data type. :param str data: The response string to be deserialized. :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ if data is None: return data @@ -1623,7 +1647,11 @@ def deserialize_data(self, data, data_type): if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): return data - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: return None data_val = self.deserialize_type[data_type](data) @@ -1642,15 +1670,15 @@ def deserialize_data(self, data, data_type): except (ValueError, TypeError, AttributeError) as err: msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) def deserialize_iter(self, attr, iter_type): """Deserialize an iterable. :param list attr: Iterable to be deserialized. :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. :rtype: list """ if attr is None: @@ -1667,6 +1695,7 @@ def deserialize_dict(self, attr, dict_type): :param dict/list attr: Dictionary to be deserialized. Also accepts a list of key, value pairs. :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. :rtype: dict """ if isinstance(attr, list): @@ -1677,20 +1706,21 @@ def deserialize_dict(self, attr, dict_type): attr = {el.tag: el.text for el in attr} return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - def deserialize_object(self, attr, **kwargs): + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Deserialize a generic object. This will be handled as a dictionary. :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. :rtype: dict - :raises: TypeError if non-builtin datatype encountered. + :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): + if isinstance(attr, str): return self.deserialize_basic(attr, "str") obj_type = type(attr) if obj_type in self.basic_types: @@ -1716,11 +1746,10 @@ def deserialize_object(self, attr, **kwargs): pass return deserialized - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) - def deserialize_basic(self, attr, data_type): + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements """Deserialize basic builtin data type from string. Will attempt to convert to str, int, float and bool. This function will also accept '1', '0', 'true' and 'false' as @@ -1728,8 +1757,9 @@ def deserialize_basic(self, attr, data_type): :param str attr: response string to be deserialized. :param str data_type: deserialization data type. + :return: Deserialized basic type. :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. + :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 @@ -1739,24 +1769,23 @@ def deserialize_basic(self, attr, data_type): if data_type == "str": # None or '', node is empty string. return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, basestring): + if isinstance(attr, str): if attr.lower() in ["true", "1"]: return True - elif attr.lower() in ["false", "0"]: + if attr.lower() in ["false", "0"]: return False raise TypeError("Invalid boolean value: {}".format(attr)) if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec + return eval(data_type)(attr) # nosec # pylint: disable=eval-used @staticmethod def deserialize_unicode(data): @@ -1764,6 +1793,7 @@ def deserialize_unicode(data): as a string. :param str data: response string to be deserialized. + :return: Deserialized string. :rtype: str or unicode """ # We might be here because we have an enum modeled as string, @@ -1777,8 +1807,7 @@ def deserialize_unicode(data): return data except NameError: return str(data) - else: - return str(data) + return str(data) @staticmethod def deserialize_enum(data, enum_obj): @@ -1790,6 +1819,7 @@ def deserialize_enum(data, enum_obj): :param str data: Response string to be deserialized. If this value is None or invalid it will be returned as-is. :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. :rtype: Enum """ if isinstance(data, enum_obj) or data is None: @@ -1798,12 +1828,11 @@ def deserialize_enum(data, enum_obj): data = data.value if isinstance(data, int): # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 try: return list(enum_obj.__members__.values())[data] - except IndexError: + except IndexError as exc: error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) + raise DeserializationError(error.format(data, enum_obj)) from exc try: return enum_obj(str(data)) except ValueError: @@ -1819,8 +1848,9 @@ def deserialize_bytearray(attr): """Deserialize string into bytearray. :param str attr: response string to be deserialized. + :return: Deserialized bytearray :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1831,8 +1861,9 @@ def deserialize_base64(attr): """Deserialize base64 encoded string into string. :param str attr: response string to be deserialized. + :return: Deserialized base64 string :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1846,24 +1877,26 @@ 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. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal """ if isinstance(attr, ET.Element): attr = attr.text try: - return decimal.Decimal(attr) # type: ignore + return decimal.Decimal(str(attr)) # type: ignore except decimal.DecimalException as err: msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err @staticmethod def deserialize_long(attr): """Deserialize string into long (Py2) or int (Py3). :param str attr: response string to be deserialized. + :return: Deserialized int :rtype: long or int - :raises: ValueError if string format invalid. + :raises ValueError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1874,8 +1907,9 @@ def deserialize_duration(attr): """Deserialize ISO-8601 formatted string into TimeDelta object. :param str attr: response string to be deserialized. + :return: Deserialized duration :rtype: TimeDelta - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1883,32 +1917,33 @@ def deserialize_duration(attr): duration = isodate.parse_duration(attr) except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration + raise DeserializationError(msg) from err + return duration @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. :param str attr: response string to be deserialized. + :return: Deserialized date :rtype: Date - :raises: DeserializationError if string format invalid. + :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): # type: ignore raise DeserializationError("Date must have only digits and -. Received: %s" % attr) # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) @staticmethod def deserialize_time(attr): """Deserialize ISO-8601 formatted string into time object. :param str attr: response string to be deserialized. + :return: Deserialized time :rtype: datetime.time - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1921,31 +1956,32 @@ def deserialize_rfc(attr): """Deserialize RFC-1123 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text try: parsed_date = email.utils.parsedate_tz(attr) # type: ignore date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + *parsed_date[:6], tzinfo=datetime.timezone(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 + raise DeserializationError(msg) from err + return date_obj @staticmethod def deserialize_iso(attr): """Deserialize ISO-8601 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1972,9 +2008,8 @@ def deserialize_iso(attr): raise OverflowError("Hit max or min date") except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + return date_obj @staticmethod def deserialize_unix(attr): @@ -1982,15 +2017,16 @@ def deserialize_unix(attr): This is represented as seconds. :param int attr: Object to be serialized. + :return: Deserialized datetime :rtype: Datetime - :raises: DeserializationError if format invalid + :raises DeserializationError: if format invalid """ if isinstance(attr, ET.Element): attr = int(attr.text) # type: ignore try: + attr = int(attr) date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) except ValueError as err: msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_vendor.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_vendor.py +++ /dev/null @@ -1,30 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import List, cast - -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) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_version.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_version.py index 48944bf3938a..cac9f5d10f8b 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_version.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0" +VERSION = "3.0.0" diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/__init__.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/__init__.py index 3246e0fd8647..e7a28d1a802c 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/__init__.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/__init__.py @@ -5,12 +5,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._azure_orbital import AzureOrbital +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._azure_orbital import AzureOrbital # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk @@ -18,6 +24,6 @@ __all__ = [ "AzureOrbital", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/_azure_orbital.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/_azure_orbital.py index 85035e93f02b..b4f0e0d091d6 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/_azure_orbital.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/_azure_orbital.py @@ -7,13 +7,18 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints from .. import models as _models -from .._serialization import Deserializer, Serializer +from .._utils.serialization import Deserializer, Serializer from ._configuration import AzureOrbitalConfiguration from .operations import ( AvailableGroundStationsOperations, @@ -25,31 +30,30 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class AzureOrbital: # pylint: disable=client-accepts-api-version-keyword +class AzureOrbital: """Azure Orbital service. :ivar operations: Operations operations :vartype operations: azure.mgmt.orbital.aio.operations.Operations - :ivar spacecrafts: SpacecraftsOperations operations - :vartype spacecrafts: azure.mgmt.orbital.aio.operations.SpacecraftsOperations - :ivar contacts: ContactsOperations operations - :vartype contacts: azure.mgmt.orbital.aio.operations.ContactsOperations - :ivar contact_profiles: ContactProfilesOperations operations - :vartype contact_profiles: azure.mgmt.orbital.aio.operations.ContactProfilesOperations :ivar available_ground_stations: AvailableGroundStationsOperations operations :vartype available_ground_stations: azure.mgmt.orbital.aio.operations.AvailableGroundStationsOperations + :ivar contact_profiles: ContactProfilesOperations operations + :vartype contact_profiles: azure.mgmt.orbital.aio.operations.ContactProfilesOperations :ivar operations_results: OperationsResultsOperations operations :vartype operations_results: azure.mgmt.orbital.aio.operations.OperationsResultsOperations + :ivar spacecrafts: SpacecraftsOperations operations + :vartype spacecrafts: azure.mgmt.orbital.aio.operations.SpacecraftsOperations + :ivar contacts: ContactsOperations operations + :vartype contacts: azure.mgmt.orbital.aio.operations.ContactsOperations :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". + :param base_url: Service URL. Default value is None. :type base_url: str :keyword api_version: Api Version. Default value is "2022-11-01". Note that overriding this default value may result in unsupported behavior. @@ -59,33 +63,59 @@ class AzureOrbital: # pylint: disable=client-accepts-api-version-keyword """ def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - base_url: str = "https://management.azure.com", - **kwargs: Any + self, credential: "AsyncTokenCredential", subscription_id: str, base_url: Optional[str] = None, **kwargs: Any ) -> None: - self._config = AzureOrbitalConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) - self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + _cloud = kwargs.pop("cloud_setting", None) or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = AzureOrbitalConfiguration( + credential=credential, subscription_id=subscription_id, credential_scopes=credential_scopes, **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, base_url), policies=_policies, **kwargs + ) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.spacecrafts = SpacecraftsOperations(self._client, self._config, self._serialize, self._deserialize) - self.contacts = ContactsOperations(self._client, self._config, self._serialize, self._deserialize) - self.contact_profiles = ContactProfilesOperations( + self.available_ground_stations = AvailableGroundStationsOperations( self._client, self._config, self._serialize, self._deserialize ) - self.available_ground_stations = AvailableGroundStationsOperations( + self.contact_profiles = ContactProfilesOperations( self._client, self._config, self._serialize, self._deserialize ) self.operations_results = OperationsResultsOperations( self._client, self._config, self._serialize, self._deserialize ) + self.spacecrafts = SpacecraftsOperations(self._client, self._config, self._serialize, self._deserialize) + self.contacts = ContactsOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -105,12 +135,12 @@ def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncH request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "AzureOrbital": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/_configuration.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/_configuration.py index a262b5161896..5d1fe9cf63a2 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/_configuration.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/_configuration.py @@ -6,26 +6,18 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports - if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class AzureOrbitalConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class AzureOrbitalConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for AzureOrbital. Note that all parameters used to create this instance are saved as instance @@ -41,8 +33,7 @@ class AzureOrbitalConfiguration(Configuration): # pylint: disable=too-many-inst """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(AzureOrbitalConfiguration, self).__init__(**kwargs) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", "2022-11-01") + api_version: str = kwargs.pop("api_version", "2022-11-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -54,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-orbital/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -62,9 +54,9 @@ def _configure(self, **kwargs: Any) -> None: self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/_patch.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/_patch.py index f99e77fef986..17dbc073e01b 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/_patch.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/_patch.py @@ -25,6 +25,7 @@ # # -------------------------------------------------------------------------- + # 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(): diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/__init__.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/__init__.py index d97b0cb1b651..0ce0e44f988f 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/__init__.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/__init__.py @@ -5,25 +5,31 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import Operations -from ._spacecrafts_operations import SpacecraftsOperations -from ._contacts_operations import ContactsOperations -from ._contact_profiles_operations import ContactProfilesOperations -from ._available_ground_stations_operations import AvailableGroundStationsOperations -from ._operations_results_operations import OperationsResultsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._available_ground_stations_operations import AvailableGroundStationsOperations # type: ignore +from ._contact_profiles_operations import ContactProfilesOperations # type: ignore +from ._operations_results_operations import OperationsResultsOperations # type: ignore +from ._spacecrafts_operations import SpacecraftsOperations # type: ignore +from ._contacts_operations import ContactsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "Operations", - "SpacecraftsOperations", - "ContactsOperations", - "ContactProfilesOperations", "AvailableGroundStationsOperations", + "ContactProfilesOperations", "OperationsResultsOperations", + "SpacecraftsOperations", + "ContactsOperations", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_available_ground_stations_operations.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_available_ground_stations_operations.py index 4b3162e4f8db..63a7077fb46d 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_available_ground_stations_operations.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_available_ground_stations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys +from collections.abc import MutableMapping from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -20,20 +20,16 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._available_ground_stations_operations import build_list_by_capability_request +from .._configuration import AzureOrbitalConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,10 +48,10 @@ class AvailableGroundStationsOperations: 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") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureOrbitalConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_capability( @@ -66,7 +62,6 @@ def list_by_capability( :param capability: Ground Station Capability. Known values are: "EarthObservation" and "Communication". Required. :type capability: str or ~azure.mgmt.orbital.models.CapabilityParameter - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AvailableGroundStation or the result of cls(response) :rtype: @@ -76,12 +71,10 @@ def list_by_capability( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AvailableGroundStationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -92,16 +85,14 @@ def list_by_capability( def prepare_request(next_link=None): if not next_link: - request = build_list_by_capability_request( + _request = build_list_by_capability_request( subscription_id=self._config.subscription_id, capability=capability, api_version=api_version, - template_url=self.list_by_capability.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -113,13 +104,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AvailableGroundStationListResult", pipeline_response) @@ -129,10 +119,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -144,7 +135,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_capability.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Orbital/availableGroundStations" - } diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_contact_profiles_operations.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_contact_profiles_operations.py index 003cbe34ffec..e544926c4c5b 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_contact_profiles_operations.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_contact_profiles_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,12 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -17,12 +18,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict @@ -30,7 +32,7 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._contact_profiles_operations import ( build_create_or_update_request, build_delete_request, @@ -39,11 +41,8 @@ build_list_request, build_update_tags_request, ) +from .._configuration import AzureOrbitalConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -62,10 +61,182 @@ class ContactProfilesOperations: 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") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureOrbitalConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_subscription( + self, skiptoken: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.ContactProfile"]: + """Returns list of contact profiles by Subscription. + + :param skiptoken: An opaque string that the resource provider uses to skip over + previously-returned results. This is used when a previous list operation call returned a + partial result. If a previous response contains a nextLink element, the value of the nextLink + element will include a skiptoken parameter that specifies a starting point to use for + subsequent calls. Default value is None. + :type skiptoken: str + :return: An iterator like instance of either ContactProfile or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.orbital.models.ContactProfile] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ContactProfileListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_subscription_request( + subscription_id=self._config.subscription_id, + skiptoken=skiptoken, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ContactProfileListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list( + self, resource_group_name: str, skiptoken: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.ContactProfile"]: + """Returns list of contact profiles by Resource Group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param skiptoken: An opaque string that the resource provider uses to skip over + previously-returned results. This is used when a previous list operation call returned a + partial result. If a previous response contains a nextLink element, the value of the nextLink + element will include a skiptoken parameter that specifies a starting point to use for + subsequent calls. Default value is None. + :type skiptoken: str + :return: An iterator like instance of either ContactProfile or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.orbital.models.ContactProfile] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ContactProfileListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + skiptoken=skiptoken, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ContactProfileListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) @distributed_trace_async async def get(self, resource_group_name: str, contact_profile_name: str, **kwargs: Any) -> _models.ContactProfile: @@ -76,12 +247,11 @@ async def get(self, resource_group_name: str, contact_profile_name: str, **kwarg :type resource_group_name: str :param contact_profile_name: Contact Profile name. Required. :type contact_profile_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ContactProfile or the result of cls(response) :rtype: ~azure.mgmt.orbital.models.ContactProfile :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -92,25 +262,22 @@ async def get(self, resource_group_name: str, contact_profile_name: str, **kwarg _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ContactProfile] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, contact_profile_name=contact_profile_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -120,34 +287,21 @@ async def get(self, resource_group_name: str, contact_profile_name: str, **kwarg error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ContactProfile", pipeline_response) + deserialized = self._deserialize("ContactProfile", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}" - } + return deserialized # type: ignore async def _create_or_update_initial( self, resource_group_name: str, contact_profile_name: str, - location: str, - network_configuration: _models.ContactProfilesPropertiesNetworkConfiguration, - links: List[_models.ContactProfileLink], - tags: Optional[Dict[str, str]] = None, - provisioning_state: Optional[Union[str, _models.ContactProfilesPropertiesProvisioningState]] = None, - minimum_viable_contact_duration: Optional[str] = None, - minimum_elevation_degrees: Optional[float] = None, - auto_tracking_configuration: Optional[Union[str, _models.AutoTrackingConfiguration]] = None, - event_hub_uri: Optional[str] = None, - third_party_configurations: Optional[List[_models.ContactProfileThirdPartyConfiguration]] = None, + parameters: Union[_models.ContactProfile, IO[bytes]], **kwargs: Any - ) -> _models.ContactProfile: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -158,86 +312,70 @@ async def _create_or_update_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) - cls: ClsType[_models.ContactProfile] = kwargs.pop("cls", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - _parameters = _models.ContactProfile( - auto_tracking_configuration=auto_tracking_configuration, - event_hub_uri=event_hub_uri, - links=links, - location=location, - minimum_elevation_degrees=minimum_elevation_degrees, - minimum_viable_contact_duration=minimum_viable_contact_duration, - network_configuration=network_configuration, - provisioning_state=provisioning_state, - tags=tags, - third_party_configurations=third_party_configurations, - ) - _json = self._serialize.body(_parameters, "ContactProfile") + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ContactProfile") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, contact_profile_name=contact_profile_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, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("ContactProfile", pipeline_response) - if response.status_code == 201: response_headers["Azure-AsyncOperation"] = self._deserialize( "str", response.headers.get("Azure-AsyncOperation") ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - deserialized = self._deserialize("ContactProfile", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}" - } - - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, contact_profile_name: str, - location: str, - network_configuration: _models.ContactProfilesPropertiesNetworkConfiguration, - links: List[_models.ContactProfileLink], - tags: Optional[Dict[str, str]] = None, - provisioning_state: Optional[Union[str, _models.ContactProfilesPropertiesProvisioningState]] = None, - minimum_viable_contact_duration: Optional[str] = None, - minimum_elevation_degrees: Optional[float] = None, - auto_tracking_configuration: Optional[Union[str, _models.AutoTrackingConfiguration]] = None, - event_hub_uri: Optional[str] = None, - third_party_configurations: Optional[List[_models.ContactProfileThirdPartyConfiguration]] = None, + parameters: _models.ContactProfile, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.ContactProfile]: """Creates or updates a contact profile. @@ -247,246 +385,126 @@ async def begin_create_or_update( :type resource_group_name: str :param contact_profile_name: Contact Profile name. Required. :type contact_profile_name: str - :param location: The geo-location where the resource lives. Required. - :type location: str - :param network_configuration: Network configuration of customer virtual network. Required. - :type network_configuration: - ~azure.mgmt.orbital.models.ContactProfilesPropertiesNetworkConfiguration - :param links: Links of the Contact Profile. Describes RF links, modem processing, and IP - endpoints. Required. - :type links: list[~azure.mgmt.orbital.models.ContactProfileLink] - :param tags: Resource tags. Default value is None. - :type tags: dict[str, str] - :param provisioning_state: The current state of the resource's creation, deletion, or - modification. Known values are: "creating", "succeeded", "failed", "canceled", "updating", and - "deleting". Default value is None. - :type provisioning_state: str or - ~azure.mgmt.orbital.models.ContactProfilesPropertiesProvisioningState - :param minimum_viable_contact_duration: Minimum viable contact duration in ISO 8601 format. - Used for listing the available contacts with a spacecraft at a given ground station. Default - value is None. - :type minimum_viable_contact_duration: str - :param minimum_elevation_degrees: Minimum viable elevation for the contact in decimal degrees. - Used for listing the available contacts with a spacecraft at a given ground station. Default - value is None. - :type minimum_elevation_degrees: float - :param auto_tracking_configuration: Auto-tracking configuration. Known values are: "disabled", - "xBand", and "sBand". Default value is None. - :type auto_tracking_configuration: str or ~azure.mgmt.orbital.models.AutoTrackingConfiguration - :param event_hub_uri: ARM resource identifier of the Event Hub used for telemetry. Requires - granting Orbital Resource Provider the rights to send telemetry into the hub. Default value is - None. - :type event_hub_uri: str - :param third_party_configurations: Third-party mission configuration of the Contact Profile. - Describes RF links, modem processing, and IP endpoints. Default value is None. - :type third_party_configurations: - list[~azure.mgmt.orbital.models.ContactProfileThirdPartyConfiguration] - :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. + :param parameters: The parameters to provide for the created Contact Profile. Required. + :type parameters: ~azure.mgmt.orbital.models.ContactProfile + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :return: An instance of AsyncLROPoller that returns either ContactProfile or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.ContactProfile] :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) - cls: ClsType[_models.ContactProfile] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_or_update_initial( - resource_group_name=resource_group_name, - contact_profile_name=contact_profile_name, - location=location, - network_configuration=network_configuration, - links=links, - tags=tags, - provisioning_state=provisioning_state, - minimum_viable_contact_duration=minimum_viable_contact_duration, - minimum_elevation_degrees=minimum_elevation_degrees, - auto_tracking_configuration=auto_tracking_configuration, - event_hub_uri=event_hub_uri, - third_party_configurations=third_party_configurations, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ContactProfile", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), - ) - 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, - ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}" - } - - async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, contact_profile_name: str, **kwargs: Any - ) -> None: - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - cls: ClsType[None] = kwargs.pop("cls", None) - - request = build_delete_request( - resource_group_name=resource_group_name, - contact_profile_name=contact_profile_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self._delete_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - 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) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - if cls: - return cls(pipeline_response, None, response_headers) + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + contact_profile_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ContactProfile]: + """Creates or updates a contact profile. - _delete_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}" - } + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param contact_profile_name: Contact Profile name. Required. + :type contact_profile_name: str + :param parameters: The parameters to provide for the created Contact Profile. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either ContactProfile or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.ContactProfile] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async - async def begin_delete( - self, resource_group_name: str, contact_profile_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes a specified contact profile resource. + async def begin_create_or_update( + self, + resource_group_name: str, + contact_profile_name: str, + parameters: Union[_models.ContactProfile, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ContactProfile]: + """Creates or updates a contact profile. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str :param contact_profile_name: Contact Profile name. Required. :type contact_profile_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] + :param parameters: The parameters to provide for the created Contact Profile. Is either a + ContactProfile type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.orbital.models.ContactProfile or IO[bytes] + :return: An instance of AsyncLROPoller that returns either ContactProfile or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.ContactProfile] :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ContactProfile] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( # type: ignore + raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, contact_profile_name=contact_profile_name, + parameters=parameters, api_version=api_version, + content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ContactProfile", pipeline_response.http_response) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized if polling is True: polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + AsyncPollingMethod, + AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.ContactProfile].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}" - } + return AsyncLROPoller[_models.ContactProfile]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _update_tags_initial( self, resource_group_name: str, contact_profile_name: str, - parameters: Union[_models.TagsObject, IO], + parameters: Union[_models.TagsObject, IO[bytes]], **kwargs: Any - ) -> Optional[_models.ContactProfile]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -497,21 +515,19 @@ async def _update_tags_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.ContactProfile]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TagsObject") - request = build_update_tags_request( + _request = build_update_tags_request( resource_group_name=resource_group_name, contact_profile_name=contact_profile_name, subscription_id=self._config.subscription_id, @@ -519,40 +535,39 @@ async def _update_tags_initial( content_type=content_type, json=_json, content=_content, - template_url=self._update_tags_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) + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("ContactProfile", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _update_tags_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}" - } + return deserialized # type: ignore @overload async def begin_update_tags( @@ -576,14 +591,6 @@ async def begin_update_tags( :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 ContactProfile or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.ContactProfile] @@ -595,7 +602,7 @@ async def begin_update_tags( self, resource_group_name: str, contact_profile_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -608,18 +615,10 @@ async def begin_update_tags( :param contact_profile_name: Contact Profile name. Required. :type contact_profile_name: str :param parameters: Parameters supplied to update contact profile tags. Required. - :type parameters: IO + :type parameters: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ContactProfile or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.ContactProfile] @@ -631,7 +630,7 @@ async def begin_update_tags( self, resource_group_name: str, contact_profile_name: str, - parameters: Union[_models.TagsObject, IO], + parameters: Union[_models.TagsObject, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.ContactProfile]: """Updates the specified contact profile tags. @@ -642,19 +641,8 @@ async def begin_update_tags( :param contact_profile_name: Contact Profile name. Required. :type contact_profile_name: str :param parameters: Parameters supplied to update contact profile tags. Is either a TagsObject - type or a IO type. Required. - :type parameters: ~azure.mgmt.orbital.models.TagsObject or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.orbital.models.TagsObject or IO[bytes] :return: An instance of AsyncLROPoller that returns either ContactProfile or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.ContactProfile] @@ -663,9 +651,7 @@ async def begin_update_tags( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ContactProfile] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -683,12 +669,13 @@ async def begin_update_tags( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ContactProfile", pipeline_response) + deserialized = self._deserialize("ContactProfile", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -700,44 +687,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.ContactProfile].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_update_tags.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}" - } - - @distributed_trace - def list_by_subscription( - self, skiptoken: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.ContactProfile"]: - """Returns list of contact profiles by Subscription. - - :param skiptoken: An opaque string that the resource provider uses to skip over - previously-returned results. This is used when a previous list operation call returned a - partial result. If a previous response contains a nextLink element, the value of the nextLink - element will include a skiptoken parameter that specifies a starting point to use for - subsequent calls. Default value is None. - :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ContactProfile or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.orbital.models.ContactProfile] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) + return AsyncLROPoller[_models.ContactProfile]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore ) - cls: ClsType[_models.ContactProfileListResult] = kwargs.pop("cls", None) - error_map = { + async def _delete_initial( + self, resource_group_name: str, contact_profile_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -745,159 +708,104 @@ def list_by_subscription( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - request = build_list_by_subscription_request( - subscription_id=self._config.subscription_id, - skiptoken=skiptoken, - 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) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = build_delete_request( + resource_group_name=resource_group_name, + contact_profile_name=contact_profile_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) - async def extract_data(pipeline_response): - deserialized = self._deserialize("ContactProfileListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - async def get_next(next_link=None): - request = prepare_request(next_link) + response = pipeline_response.http_response - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs - ) - response = pipeline_response.http_response + if response.status_code not in [200, 202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - return pipeline_response + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return AsyncItemPaged(get_next, extract_data) + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Orbital/contactProfiles" - } + return deserialized # type: ignore - @distributed_trace - def list( - self, resource_group_name: str, skiptoken: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.ContactProfile"]: - """Returns list of contact profiles by Resource Group. + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, contact_profile_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a specified contact profile resource. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param skiptoken: An opaque string that the resource provider uses to skip over - previously-returned results. This is used when a previous list operation call returned a - partial result. If a previous response contains a nextLink element, the value of the nextLink - element will include a skiptoken parameter that specifies a starting point to use for - subsequent calls. Default value is None. - :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ContactProfile or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.orbital.models.ContactProfile] + :param contact_profile_name: Contact Profile name. Required. + :type contact_profile_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - cls: ClsType[_models.ContactProfileListResult] = kwargs.pop("cls", None) - - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - request = build_list_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - skiptoken=skiptoken, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + contact_profile_name=contact_profile_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) - async def extract_data(pipeline_response): - deserialized = self._deserialize("ContactProfileListResult", pipeline_response) - list_of_elem = deserialized.value + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) + return cls(pipeline_response, None, {}) # type: ignore - async def get_next(next_link=None): - request = prepare_request(next_link) - - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles" - } + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_contacts_operations.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_contacts_operations.py index 33e727b035a0..3c8246692860 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_contacts_operations.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_contacts_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,12 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -17,12 +18,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict @@ -30,18 +32,15 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._contacts_operations import ( build_create_request, build_delete_request, build_get_request, build_list_request, ) +from .._configuration import AzureOrbitalConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -60,10 +59,10 @@ class ContactsOperations: 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") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureOrbitalConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( @@ -82,7 +81,6 @@ def list( element will include a skiptoken parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Contact or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.orbital.models.Contact] :raises ~azure.core.exceptions.HttpResponseError: @@ -90,12 +88,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ContactListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -106,18 +102,16 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, subscription_id=self._config.subscription_id, skiptoken=skiptoken, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -129,13 +123,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ContactListResult", pipeline_response) @@ -145,10 +138,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -161,10 +155,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts" - } - @distributed_trace_async async def get( self, resource_group_name: str, spacecraft_name: str, contact_name: str, **kwargs: Any @@ -178,12 +168,11 @@ async def get( :type spacecraft_name: str :param contact_name: Contact name. Required. :type contact_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Contact or the result of cls(response) :rtype: ~azure.mgmt.orbital.models.Contact :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -194,26 +183,23 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Contact] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, contact_name=contact_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -223,26 +209,22 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Contact", pipeline_response) + deserialized = self._deserialize("Contact", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts/{contactName}" - } + return deserialized # type: ignore async def _create_initial( self, resource_group_name: str, spacecraft_name: str, contact_name: str, - parameters: Union[_models.Contact, IO], + parameters: Union[_models.Contact, IO[bytes]], **kwargs: Any - ) -> _models.Contact: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -253,21 +235,19 @@ async def _create_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Contact] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Contact") - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, contact_name=contact_name, @@ -276,44 +256,42 @@ async def _create_initial( content_type=content_type, json=_json, content=_content, - template_url=self._create_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("Contact", pipeline_response) - if response.status_code == 201: response_headers["Azure-AsyncOperation"] = self._deserialize( "str", response.headers.get("Azure-AsyncOperation") ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - deserialized = self._deserialize("Contact", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore - _create_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts/{contactName}" - } - @overload async def begin_create( self, @@ -339,14 +317,6 @@ async def begin_create( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Contact or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.Contact] @@ -359,7 +329,7 @@ async def begin_create( resource_group_name: str, spacecraft_name: str, contact_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -374,18 +344,10 @@ async def begin_create( :param contact_name: Contact name. Required. :type contact_name: str :param parameters: The parameters to provide for the created contact. Required. - :type parameters: IO + :type parameters: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Contact or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.Contact] @@ -398,7 +360,7 @@ async def begin_create( resource_group_name: str, spacecraft_name: str, contact_name: str, - parameters: Union[_models.Contact, IO], + parameters: Union[_models.Contact, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.Contact]: """Creates a contact. @@ -411,19 +373,8 @@ async def begin_create( :param contact_name: Contact name. Required. :type contact_name: str :param parameters: The parameters to provide for the created contact. Is either a Contact type - or a IO type. Required. - :type parameters: ~azure.mgmt.orbital.models.Contact 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. + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.orbital.models.Contact or IO[bytes] :return: An instance of AsyncLROPoller that returns either Contact or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.Contact] @@ -432,9 +383,7 @@ async def begin_create( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Contact] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -453,12 +402,13 @@ async def begin_create( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Contact", pipeline_response) + deserialized = self._deserialize("Contact", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -471,22 +421,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.Contact].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts/{contactName}" - } + return AsyncLROPoller[_models.Contact]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - async def _delete_initial( # pylint: disable=inconsistent-return-statements + async def _delete_initial( self, resource_group_name: str, spacecraft_name: str, contact_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -497,31 +445,33 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, contact_name=contact_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) @@ -529,13 +479,14 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _delete_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts/{contactName}" - } + return deserialized # type: ignore @distributed_trace_async async def begin_delete( @@ -550,14 +501,6 @@ async def begin_delete( :type spacecraft_name: str :param contact_name: Contact name. Required. :type contact_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -565,15 +508,13 @@ async def begin_delete( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( # type: ignore + raw_result = await self._delete_initial( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, contact_name=contact_name, @@ -583,11 +524,12 @@ async def begin_delete( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: AsyncPollingMethod = cast( @@ -598,14 +540,10 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts/{contactName}" - } + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_operations.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_operations.py index c360fdb5db22..7ed1715e0397 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_operations.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys +from collections.abc import MutableMapping from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -20,20 +20,16 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import build_list_request +from .._configuration import AzureOrbitalConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,16 +48,15 @@ class Operations: 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") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureOrbitalConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: - """Lists all of the available Orbital Rest API operations. + """List the operations for the provider. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.orbital.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: @@ -69,12 +64,10 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -85,14 +78,12 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -104,26 +95,26 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -135,5 +126,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.Orbital/operations"} diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_operations_results_operations.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_operations_results_operations.py index c19375a4b40a..81347ec64dcd 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_operations_results_operations.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_operations_results_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +5,10 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast +from collections.abc import MutableMapping +from typing import Any, Callable, Dict, Optional, TypeVar +from azure.core import AsyncPipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -18,22 +18,16 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._operations_results_operations import build_get_request +from .._configuration import AzureOrbitalConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,13 +46,24 @@ class OperationsResultsOperations: 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") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureOrbitalConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def _get_initial(self, location: str, operation_id: str, **kwargs: Any) -> Optional[_models.OperationResult]: - error_map = { + @distributed_trace_async + async def get(self, location: str, operation_id: str, **kwargs: Any) -> Optional[_models.OperationResult]: + """Returns operation results. + + :param location: The name of Azure region. Required. + :type location: str + :param operation_id: The ID of an ongoing async operation. Required. + :type operation_id: str + :return: OperationResult or None or the result of cls(response) + :rtype: ~azure.mgmt.orbital.models.OperationResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -69,25 +74,22 @@ async def _get_initial(self, location: str, operation_id: str, **kwargs: Any) -> _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[Optional[_models.OperationResult]] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( location=location, operation_id=operation_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._get_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -100,88 +102,14 @@ async def _get_initial(self, location: str, operation_id: str, **kwargs: Any) -> deserialized = None response_headers = {} if response.status_code == 200: - deserialized = self._deserialize("OperationResult", pipeline_response) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = self._deserialize("OperationResult", pipeline_response.http_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized - - _get_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Orbital/locations/{location}/operationResults/{operationId}" - } + return cls(pipeline_response, deserialized, response_headers) # type: ignore - @distributed_trace_async - async def begin_get( - self, location: str, operation_id: str, **kwargs: Any - ) -> AsyncLROPoller[_models.OperationResult]: - """Returns operation results. - - :param location: The name of Azure region. Required. - :type location: str - :param operation_id: The ID of an ongoing async operation. Required. - :type operation_id: 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 OperationResult or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.OperationResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - cls: ClsType[_models.OperationResult] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._get_initial( - location=location, - operation_id=operation_id, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("OperationResult", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_get.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Orbital/locations/{location}/operationResults/{operationId}" - } + return deserialized # type: ignore diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_spacecrafts_operations.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_spacecrafts_operations.py index 2840b6eb4553..79ccdaf5c2fb 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_spacecrafts_operations.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/aio/operations/_spacecrafts_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,11 +6,12 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime -import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -18,12 +19,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict @@ -31,7 +33,7 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._spacecrafts_operations import ( build_create_or_update_request, build_delete_request, @@ -41,11 +43,8 @@ build_list_request, build_update_tags_request, ) +from .._configuration import AzureOrbitalConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -64,10 +63,10 @@ class SpacecraftsOperations: 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") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureOrbitalConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_subscription( @@ -81,7 +80,6 @@ def list_by_subscription( element will include a skiptoken parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Spacecraft or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.orbital.models.Spacecraft] :raises ~azure.core.exceptions.HttpResponseError: @@ -89,12 +87,10 @@ def list_by_subscription( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.SpacecraftListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -105,16 +101,14 @@ def list_by_subscription( def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, skiptoken=skiptoken, 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) else: # make call to next link with the client's api-version @@ -126,13 +120,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("SpacecraftListResult", pipeline_response) @@ -142,10 +135,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -158,8 +152,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Orbital/spacecrafts"} - @distributed_trace def list( self, resource_group_name: str, skiptoken: Optional[str] = None, **kwargs: Any @@ -175,7 +167,6 @@ def list( element will include a skiptoken parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Spacecraft or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.orbital.models.Spacecraft] :raises ~azure.core.exceptions.HttpResponseError: @@ -183,12 +174,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.SpacecraftListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -199,17 +188,15 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, skiptoken=skiptoken, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -221,13 +208,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("SpacecraftListResult", pipeline_response) @@ -237,10 +223,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -253,10 +240,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts" - } - @distributed_trace_async async def get(self, resource_group_name: str, spacecraft_name: str, **kwargs: Any) -> _models.Spacecraft: """Gets the specified spacecraft in a specified resource group. @@ -266,12 +249,11 @@ async def get(self, resource_group_name: str, spacecraft_name: str, **kwargs: An :type resource_group_name: str :param spacecraft_name: Spacecraft ID. Required. :type spacecraft_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Spacecraft or the result of cls(response) :rtype: ~azure.mgmt.orbital.models.Spacecraft :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -282,25 +264,22 @@ async def get(self, resource_group_name: str, spacecraft_name: str, **kwargs: An _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Spacecraft] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -310,32 +289,21 @@ async def get(self, resource_group_name: str, spacecraft_name: str, **kwargs: An error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Spacecraft", pipeline_response) + deserialized = self._deserialize("Spacecraft", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}" - } + return deserialized # type: ignore async def _create_or_update_initial( self, resource_group_name: str, spacecraft_name: str, - location: str, - title_line: str, - tle_line1: str, - tle_line2: str, - links: List[_models.SpacecraftLink], - tags: Optional[Dict[str, str]] = None, - provisioning_state: Optional[Union[str, _models.SpacecraftsPropertiesProvisioningState]] = None, - norad_id: Optional[str] = None, + parameters: Union[_models.Spacecraft, IO[bytes]], **kwargs: Any - ) -> _models.Spacecraft: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -346,82 +314,70 @@ async def _create_or_update_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) - cls: ClsType[_models.Spacecraft] = kwargs.pop("cls", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - _parameters = _models.Spacecraft( - links=links, - location=location, - norad_id=norad_id, - provisioning_state=provisioning_state, - tags=tags, - title_line=title_line, - tle_line1=tle_line1, - tle_line2=tle_line2, - ) - _json = self._serialize.body(_parameters, "Spacecraft") + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Spacecraft") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_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, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("Spacecraft", pipeline_response) - if response.status_code == 201: response_headers["Azure-AsyncOperation"] = self._deserialize( "str", response.headers.get("Azure-AsyncOperation") ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - deserialized = self._deserialize("Spacecraft", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}" - } - - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, spacecraft_name: str, - location: str, - title_line: str, - tle_line1: str, - tle_line2: str, - links: List[_models.SpacecraftLink], - tags: Optional[Dict[str, str]] = None, - provisioning_state: Optional[Union[str, _models.SpacecraftsPropertiesProvisioningState]] = None, - norad_id: Optional[str] = None, + parameters: _models.Spacecraft, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.Spacecraft]: """Creates or updates a spacecraft resource. @@ -431,223 +387,126 @@ async def begin_create_or_update( :type resource_group_name: str :param spacecraft_name: Spacecraft ID. Required. :type spacecraft_name: str - :param location: The geo-location where the resource lives. Required. - :type location: str - :param title_line: Title line of the two-line element set (TLE). Required. - :type title_line: str - :param tle_line1: Line 1 of the two-line element set (TLE). Required. - :type tle_line1: str - :param tle_line2: Line 2 of the two-line element set (TLE). Required. - :type tle_line2: str - :param links: Immutable list of Spacecraft links. Required. - :type links: list[~azure.mgmt.orbital.models.SpacecraftLink] - :param tags: Resource tags. Default value is None. - :type tags: dict[str, str] - :param provisioning_state: The current state of the resource's creation, deletion, or - modification. Known values are: "creating", "succeeded", "failed", "canceled", "updating", and - "deleting". Default value is None. - :type provisioning_state: str or - ~azure.mgmt.orbital.models.SpacecraftsPropertiesProvisioningState - :param norad_id: NORAD ID of the spacecraft. Default value is None. - :type norad_id: 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. + :param parameters: The parameters to provide for the created spacecraft. Required. + :type parameters: ~azure.mgmt.orbital.models.Spacecraft + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :return: An instance of AsyncLROPoller that returns either Spacecraft or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.Spacecraft] :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) - cls: ClsType[_models.Spacecraft] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._create_or_update_initial( - resource_group_name=resource_group_name, - spacecraft_name=spacecraft_name, - location=location, - title_line=title_line, - tle_line1=tle_line1, - tle_line2=tle_line2, - links=links, - tags=tags, - provisioning_state=provisioning_state, - norad_id=norad_id, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Spacecraft", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), - ) - 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, - ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}" - } - - async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, spacecraft_name: str, **kwargs: Any - ) -> None: - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - cls: ClsType[None] = kwargs.pop("cls", None) - - request = build_delete_request( - resource_group_name=resource_group_name, - spacecraft_name=spacecraft_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self._delete_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - 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) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - if cls: - return cls(pipeline_response, None, response_headers) + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + spacecraft_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Spacecraft]: + """Creates or updates a spacecraft resource. - _delete_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}" - } + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param spacecraft_name: Spacecraft ID. Required. + :type spacecraft_name: str + :param parameters: The parameters to provide for the created spacecraft. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either Spacecraft or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.Spacecraft] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async - async def begin_delete(self, resource_group_name: str, spacecraft_name: str, **kwargs: Any) -> AsyncLROPoller[None]: - """Deletes a specified spacecraft resource. + async def begin_create_or_update( + self, + resource_group_name: str, + spacecraft_name: str, + parameters: Union[_models.Spacecraft, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.Spacecraft]: + """Creates or updates a spacecraft resource. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str :param spacecraft_name: Spacecraft ID. Required. :type spacecraft_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] + :param parameters: The parameters to provide for the created spacecraft. Is either a Spacecraft + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.orbital.models.Spacecraft or IO[bytes] + :return: An instance of AsyncLROPoller that returns either Spacecraft or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.Spacecraft] :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Spacecraft] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( # type: ignore + raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, + parameters=parameters, api_version=api_version, + content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Spacecraft", pipeline_response.http_response) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized if polling is True: polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + AsyncPollingMethod, + AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.Spacecraft].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}" - } + return AsyncLROPoller[_models.Spacecraft]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _update_tags_initial( - self, resource_group_name: str, spacecraft_name: str, parameters: Union[_models.TagsObject, IO], **kwargs: Any - ) -> Optional[_models.Spacecraft]: - error_map = { + self, + resource_group_name: str, + spacecraft_name: str, + parameters: Union[_models.TagsObject, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -658,21 +517,19 @@ async def _update_tags_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.Spacecraft]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TagsObject") - request = build_update_tags_request( + _request = build_update_tags_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, subscription_id=self._config.subscription_id, @@ -680,40 +537,39 @@ async def _update_tags_initial( content_type=content_type, json=_json, content=_content, - template_url=self._update_tags_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) + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("Spacecraft", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _update_tags_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}" - } + return deserialized # type: ignore @overload async def begin_update_tags( @@ -737,14 +593,6 @@ async def begin_update_tags( :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 Spacecraft or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.Spacecraft] @@ -756,7 +604,7 @@ async def begin_update_tags( self, resource_group_name: str, spacecraft_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -769,18 +617,10 @@ async def begin_update_tags( :param spacecraft_name: Spacecraft ID. Required. :type spacecraft_name: str :param parameters: Parameters supplied to update spacecraft tags. Required. - :type parameters: IO + :type parameters: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Spacecraft or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.Spacecraft] @@ -789,7 +629,11 @@ async def begin_update_tags( @distributed_trace_async async def begin_update_tags( - self, resource_group_name: str, spacecraft_name: str, parameters: Union[_models.TagsObject, IO], **kwargs: Any + self, + resource_group_name: str, + spacecraft_name: str, + parameters: Union[_models.TagsObject, IO[bytes]], + **kwargs: Any ) -> AsyncLROPoller[_models.Spacecraft]: """Updates the specified spacecraft tags. @@ -799,19 +643,8 @@ async def begin_update_tags( :param spacecraft_name: Spacecraft ID. Required. :type spacecraft_name: str :param parameters: Parameters supplied to update spacecraft tags. Is either a TagsObject type - or a IO type. Required. - :type parameters: ~azure.mgmt.orbital.models.TagsObject 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. + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.orbital.models.TagsObject or IO[bytes] :return: An instance of AsyncLROPoller that returns either Spacecraft or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.orbital.models.Spacecraft] @@ -820,9 +653,7 @@ async def begin_update_tags( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Spacecraft] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -840,12 +671,13 @@ async def begin_update_tags( params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Spacecraft", pipeline_response) + deserialized = self._deserialize("Spacecraft", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -857,29 +689,135 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.Spacecraft].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return AsyncLROPoller[_models.Spacecraft]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial( + self, resource_group_name: str, spacecraft_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + spacecraft_name=spacecraft_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete(self, resource_group_name: str, spacecraft_name: str, **kwargs: Any) -> AsyncLROPoller[None]: + """Deletes a specified spacecraft resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param spacecraft_name: Spacecraft ID. Required. + :type spacecraft_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + spacecraft_name=spacecraft_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) - begin_update_tags.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}" - } + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore async def _list_available_contacts_initial( self, resource_group_name: str, spacecraft_name: str, - contact_profile: _models.ContactParametersContactProfile, - ground_station_name: str, - start_time: datetime.datetime, - end_time: datetime.datetime, + parameters: Union[_models.ContactParameters, IO[bytes]], **kwargs: Any - ) -> Optional[_models.AvailableContactsListResult]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -890,71 +828,128 @@ async def _list_available_contacts_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) - cls: ClsType[Optional[_models.AvailableContactsListResult]] = kwargs.pop("cls", None) - - _parameters = _models.ContactParameters( - contact_profile=contact_profile, - end_time=end_time, - ground_station_name=ground_station_name, - start_time=start_time, - ) - _json = self._serialize.body(_parameters, "ContactParameters") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ContactParameters") - request = build_list_available_contacts_request( + _request = build_list_available_contacts_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._list_available_contacts_initial.metadata["url"], + content=_content, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("AvailableContactsListResult", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore - _list_available_contacts_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/listAvailableContacts" - } + @overload + async def begin_list_available_contacts( + self, + resource_group_name: str, + spacecraft_name: str, + parameters: _models.ContactParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[AsyncIterable["_models.AvailableContacts"]]: + """Returns list of available contacts. A contact is available if the spacecraft is visible from + the ground station for more than the minimum viable contact duration provided in the contact + profile. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param spacecraft_name: Spacecraft ID. Required. + :type spacecraft_name: str + :param parameters: The parameters to provide for the contacts. Required. + :type parameters: ~azure.mgmt.orbital.models.ContactParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns an iterator like instance of either + AvailableContactsListResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.orbital.models.AvailableContacts]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_list_available_contacts( + self, + resource_group_name: str, + spacecraft_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[AsyncIterable["_models.AvailableContacts"]]: + """Returns list of available contacts. A contact is available if the spacecraft is visible from + the ground station for more than the minimum viable contact duration provided in the contact + profile. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param spacecraft_name: Spacecraft ID. Required. + :type spacecraft_name: str + :param parameters: The parameters to provide for the contacts. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns an iterator like instance of either + AvailableContactsListResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.orbital.models.AvailableContacts]] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_list_available_contacts( self, resource_group_name: str, spacecraft_name: str, - contact_profile: _models.ContactParametersContactProfile, - ground_station_name: str, - start_time: datetime.datetime, - end_time: datetime.datetime, + parameters: Union[_models.ContactParameters, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[AsyncIterable["_models.AvailableContacts"]]: """Returns list of available contacts. A contact is available if the spacecraft is visible from @@ -966,22 +961,9 @@ async def begin_list_available_contacts( :type resource_group_name: str :param spacecraft_name: Spacecraft ID. Required. :type spacecraft_name: str - :param contact_profile: The reference to the contact profile resource. Required. - :type contact_profile: ~azure.mgmt.orbital.models.ContactParametersContactProfile - :param ground_station_name: Name of Azure Ground Station. Required. - :type ground_station_name: str - :param start_time: Start time of a contact (ISO 8601 UTC standard). Required. - :type start_time: ~datetime.datetime - :param end_time: End time of a contact (ISO 8601 UTC standard). Required. - :type end_time: ~datetime.datetime - :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. + :param parameters: The parameters to provide for the contacts. Is either a ContactParameters + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.orbital.models.ContactParameters or IO[bytes] :return: An instance of LROPoller that returns an iterator like instance of either AvailableContactsListResult or the result of cls(response) :rtype: @@ -992,43 +974,40 @@ async def begin_list_available_contacts( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AvailableContactsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ContactParameters") def prepare_request(next_link=None): if not next_link: - _parameters = _models.ContactParameters( - contact_profile=contact_profile, - end_time=end_time, - ground_station_name=ground_station_name, - start_time=start_time, - ) - _json = self._serialize.body(_parameters, "ContactParameters") - request = build_list_available_contacts_request( + _request = build_list_available_contacts_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.begin_list_available_contacts.metadata["url"], + content=_content, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1040,26 +1019,26 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): - deserialized = self._deserialize("AvailableContactsListResult", pipeline_response) + deserialized = self._deserialize("AvailableContactsListResult", pipeline_response.http_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1077,10 +1056,7 @@ async def get_next(next_link=None): raw_result = await self._list_available_contacts_initial( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, - contact_profile=contact_profile, - ground_station_name=ground_station_name, - start_time=start_time, - end_time=end_time, + parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, @@ -1088,6 +1064,7 @@ async def get_next(next_link=None): params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): @@ -1107,14 +1084,12 @@ async def internal_get_next(next_link=None): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[AsyncIterable["_models.AvailableContacts"]].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_list_available_contacts.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/listAvailableContacts" - } + return AsyncLROPoller[AsyncIterable["_models.AvailableContacts"]]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/models/__init__.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/models/__init__.py index dab58e5a89e6..ed186818d623 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/models/__init__.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/models/__init__.py @@ -5,97 +5,87 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._models_py3 import AuthorizedGroundstation -from ._models_py3 import AvailableContacts -from ._models_py3 import AvailableContactsListResult -from ._models_py3 import AvailableContactsProperties -from ._models_py3 import AvailableContactsSpacecraft -from ._models_py3 import AvailableGroundStation -from ._models_py3 import AvailableGroundStationListResult -from ._models_py3 import AvailableGroundStationProperties -from ._models_py3 import AvailableGroundStationPropertiesAutoGenerated -from ._models_py3 import Contact -from ._models_py3 import ContactInstanceProperties -from ._models_py3 import ContactListResult -from ._models_py3 import ContactParameters -from ._models_py3 import ContactParametersContactProfile -from ._models_py3 import ContactProfile -from ._models_py3 import ContactProfileLink -from ._models_py3 import ContactProfileLinkChannel -from ._models_py3 import ContactProfileListResult -from ._models_py3 import ContactProfileProperties -from ._models_py3 import ContactProfileThirdPartyConfiguration -from ._models_py3 import ContactProfilesProperties -from ._models_py3 import ContactProfilesPropertiesNetworkConfiguration -from ._models_py3 import ContactsPropertiesAntennaConfiguration -from ._models_py3 import ContactsPropertiesContactProfile -from ._models_py3 import EndPoint -from ._models_py3 import ErrorAdditionalInfo -from ._models_py3 import ErrorDetail -from ._models_py3 import ErrorResponse -from ._models_py3 import Operation -from ._models_py3 import OperationDisplay -from ._models_py3 import OperationListResult -from ._models_py3 import OperationResult -from ._models_py3 import OperationResultErrorProperties -from ._models_py3 import ProxyResource -from ._models_py3 import Resource -from ._models_py3 import ResourceIdListResult -from ._models_py3 import ResourceIdListResultValueItem -from ._models_py3 import ResourceReference -from ._models_py3 import Spacecraft -from ._models_py3 import SpacecraftLink -from ._models_py3 import SpacecraftListResult -from ._models_py3 import SystemData -from ._models_py3 import TagsObject -from ._models_py3 import TrackedResource +from typing import TYPE_CHECKING -from ._azure_orbital_enums import ActionType -from ._azure_orbital_enums import AutoTrackingConfiguration -from ._azure_orbital_enums import Capability -from ._azure_orbital_enums import CapabilityParameter -from ._azure_orbital_enums import ContactProfilesPropertiesProvisioningState -from ._azure_orbital_enums import ContactsPropertiesProvisioningState -from ._azure_orbital_enums import ContactsStatus -from ._azure_orbital_enums import CreatedByType -from ._azure_orbital_enums import Direction -from ._azure_orbital_enums import Origin -from ._azure_orbital_enums import Polarization -from ._azure_orbital_enums import Protocol -from ._azure_orbital_enums import ProvisioningState -from ._azure_orbital_enums import ReleaseMode -from ._azure_orbital_enums import SpacecraftsPropertiesProvisioningState -from ._azure_orbital_enums import Status +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AuthorizedGroundstation, + AvailableContacts, + AvailableContactsListResult, + AvailableGroundStation, + AvailableGroundStationListResult, + AzureResourceManagerArmResponseAvailableContactsListResult, + Contact, + ContactListResult, + ContactParameters, + ContactProfile, + ContactProfileLink, + ContactProfileLinkChannel, + ContactProfileListResult, + ContactProfileThirdPartyConfiguration, + ContactProfilesPropertiesNetworkConfiguration, + ContactsPropertiesAntennaConfiguration, + EndPoint, + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponse, + Operation, + OperationDisplay, + OperationListResult, + OperationResult, + OperationResultErrorProperties, + ProxyResource, + Resource, + ResourceReference, + Spacecraft, + SpacecraftLink, + SpacecraftListResult, + SystemData, + TagsObject, + TrackedResource, +) + +from ._azure_orbital_enums import ( # type: ignore + ActionType, + AutoTrackingConfiguration, + CapabilityParameter, + ContactsStatus, + CreatedByType, + Direction, + Origin, + Polarization, + Protocol, + ProvisioningState, + ReleaseMode, + SpacecraftsPropertiesProvisioningState, + Status, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "AuthorizedGroundstation", "AvailableContacts", "AvailableContactsListResult", - "AvailableContactsProperties", - "AvailableContactsSpacecraft", "AvailableGroundStation", "AvailableGroundStationListResult", - "AvailableGroundStationProperties", - "AvailableGroundStationPropertiesAutoGenerated", + "AzureResourceManagerArmResponseAvailableContactsListResult", "Contact", - "ContactInstanceProperties", "ContactListResult", "ContactParameters", - "ContactParametersContactProfile", "ContactProfile", "ContactProfileLink", "ContactProfileLinkChannel", "ContactProfileListResult", - "ContactProfileProperties", "ContactProfileThirdPartyConfiguration", - "ContactProfilesProperties", "ContactProfilesPropertiesNetworkConfiguration", "ContactsPropertiesAntennaConfiguration", - "ContactsPropertiesContactProfile", "EndPoint", "ErrorAdditionalInfo", "ErrorDetail", @@ -107,8 +97,6 @@ "OperationResultErrorProperties", "ProxyResource", "Resource", - "ResourceIdListResult", - "ResourceIdListResultValueItem", "ResourceReference", "Spacecraft", "SpacecraftLink", @@ -118,10 +106,7 @@ "TrackedResource", "ActionType", "AutoTrackingConfiguration", - "Capability", "CapabilityParameter", - "ContactProfilesPropertiesProvisioningState", - "ContactsPropertiesProvisioningState", "ContactsStatus", "CreatedByType", "Direction", @@ -133,5 +118,5 @@ "SpacecraftsPropertiesProvisioningState", "Status", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/models/_azure_orbital_enums.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/models/_azure_orbital_enums.py index e322f727dde2..16d1ddc925d8 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/models/_azure_orbital_enums.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/models/_azure_orbital_enums.py @@ -24,13 +24,6 @@ class AutoTrackingConfiguration(str, Enum, metaclass=CaseInsensitiveEnumMeta): S_BAND = "sBand" -class Capability(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Capability of the Ground Station.""" - - EARTH_OBSERVATION = "EarthObservation" - COMMUNICATION = "Communication" - - class CapabilityParameter(str, Enum, metaclass=CaseInsensitiveEnumMeta): """CapabilityParameter.""" @@ -38,28 +31,6 @@ class CapabilityParameter(str, Enum, metaclass=CaseInsensitiveEnumMeta): COMMUNICATION = "Communication" -class ContactProfilesPropertiesProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The current state of the resource's creation, deletion, or modification.""" - - CREATING = "creating" - SUCCEEDED = "succeeded" - FAILED = "failed" - CANCELED = "canceled" - UPDATING = "updating" - DELETING = "deleting" - - -class ContactsPropertiesProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The current state of the resource's creation, deletion, or modification.""" - - CREATING = "creating" - SUCCEEDED = "succeeded" - FAILED = "failed" - CANCELED = "canceled" - UPDATING = "updating" - DELETING = "deleting" - - class ContactsStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Status of a contact.""" diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/models/_models_py3.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/models/_models_py3.py index 39b8d3f09d6b..4c76e486d4c1 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/models/_models_py3.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/models/_models_py3.py @@ -1,5 +1,5 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # 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. @@ -8,26 +8,18 @@ # -------------------------------------------------------------------------- import datetime -import sys from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union -from .. import _serialization - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +from .._utils import serialization as _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object class AuthorizedGroundstation(_serialization.Model): """Authorized groundstation. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar ground_station: Groundstation name. Required. :vartype ground_station: str @@ -57,14 +49,14 @@ def __init__(self, *, ground_station: str, expiration_date: datetime.date, **kwa self.expiration_date = expiration_date -class AvailableContacts(_serialization.Model): # pylint: disable=too-many-instance-attributes +class AvailableContacts(_serialization.Model): """Customer retrieves list of Available Contacts for a spacecraft resource. Later, one of the available contact can be selected to create a contact. Variables are only populated by the server, and will be ignored when sending a request. :ivar spacecraft: The reference to the spacecraft resource. - :vartype spacecraft: ~azure.mgmt.orbital.models.AvailableContactsSpacecraft + :vartype spacecraft: ~azure.mgmt.orbital.models.ResourceReference :ivar ground_station_name: Name of Azure Ground Station. :vartype ground_station_name: str :ivar maximum_elevation_degrees: Maximum elevation of the antenna during the contact in decimal @@ -103,7 +95,7 @@ class AvailableContacts(_serialization.Model): # pylint: disable=too-many-insta } _attribute_map = { - "spacecraft": {"key": "spacecraft", "type": "AvailableContactsSpacecraft"}, + "spacecraft": {"key": "spacecraft", "type": "ResourceReference"}, "ground_station_name": {"key": "groundStationName", "type": "str"}, "maximum_elevation_degrees": {"key": "properties.maximumElevationDegrees", "type": "float"}, "tx_start_time": {"key": "properties.txStartTime", "type": "iso-8601"}, @@ -116,38 +108,38 @@ class AvailableContacts(_serialization.Model): # pylint: disable=too-many-insta "end_elevation_degrees": {"key": "properties.endElevationDegrees", "type": "float"}, } - def __init__(self, *, spacecraft: Optional["_models.AvailableContactsSpacecraft"] = None, **kwargs: Any) -> None: + def __init__(self, *, spacecraft: Optional["_models.ResourceReference"] = None, **kwargs: Any) -> None: """ :keyword spacecraft: The reference to the spacecraft resource. - :paramtype spacecraft: ~azure.mgmt.orbital.models.AvailableContactsSpacecraft + :paramtype spacecraft: ~azure.mgmt.orbital.models.ResourceReference """ super().__init__(**kwargs) self.spacecraft = spacecraft - self.ground_station_name = None - self.maximum_elevation_degrees = None - self.tx_start_time = None - self.tx_end_time = None - self.rx_start_time = None - self.rx_end_time = None - self.start_azimuth_degrees = None - self.end_azimuth_degrees = None - self.start_elevation_degrees = None - self.end_elevation_degrees = None + self.ground_station_name: Optional[str] = None + self.maximum_elevation_degrees: Optional[float] = None + self.tx_start_time: Optional[datetime.datetime] = None + self.tx_end_time: Optional[datetime.datetime] = None + self.rx_start_time: Optional[datetime.datetime] = None + self.rx_end_time: Optional[datetime.datetime] = None + self.start_azimuth_degrees: Optional[float] = None + self.end_azimuth_degrees: Optional[float] = None + self.start_elevation_degrees: Optional[float] = None + self.end_elevation_degrees: Optional[float] = None class AvailableContactsListResult(_serialization.Model): """Response for the ListAvailableContacts API service call. - Variables are only populated by the server, and will be ignored when sending a request. + All required parameters must be populated in order to send to server. - :ivar value: A list of available contacts. + :ivar value: The AvailableContacts items on this page. Required. :vartype value: list[~azure.mgmt.orbital.models.AvailableContacts] - :ivar next_link: The URL to get the next set of results. + :ivar next_link: The link to the next page of items. :vartype next_link: str """ _validation = { - "next_link": {"readonly": True}, + "value": {"required": True}, } _attribute_map = { @@ -155,190 +147,22 @@ class AvailableContactsListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, *, value: Optional[List["_models.AvailableContacts"]] = None, **kwargs: Any) -> None: + def __init__( + self, *, value: List["_models.AvailableContacts"], next_link: Optional[str] = None, **kwargs: Any + ) -> None: """ - :keyword value: A list of available contacts. + :keyword value: The AvailableContacts items on this page. Required. :paramtype value: list[~azure.mgmt.orbital.models.AvailableContacts] + :keyword next_link: The link to the next page of items. + :paramtype next_link: str """ super().__init__(**kwargs) self.value = value - self.next_link = None - - -class ContactInstanceProperties(_serialization.Model): - """Contact Instance Properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar maximum_elevation_degrees: Maximum elevation of the antenna during the contact in decimal - degrees. - :vartype maximum_elevation_degrees: float - :ivar tx_start_time: Time at which antenna transmit will be enabled (ISO 8601 UTC standard). - :vartype tx_start_time: ~datetime.datetime - :ivar tx_end_time: Time at which antenna transmit will be disabled (ISO 8601 UTC standard). - :vartype tx_end_time: ~datetime.datetime - :ivar rx_start_time: Earliest time to receive a signal (ISO 8601 UTC standard). - :vartype rx_start_time: ~datetime.datetime - :ivar rx_end_time: Time to lost receiving a signal (ISO 8601 UTC standard). - :vartype rx_end_time: ~datetime.datetime - :ivar start_azimuth_degrees: Azimuth of the antenna at the start of the contact in decimal - degrees. - :vartype start_azimuth_degrees: float - :ivar end_azimuth_degrees: Azimuth of the antenna at the end of the contact in decimal degrees. - :vartype end_azimuth_degrees: float - :ivar start_elevation_degrees: Spacecraft elevation above the horizon at contact start. - :vartype start_elevation_degrees: float - :ivar end_elevation_degrees: Spacecraft elevation above the horizon at contact end. - :vartype end_elevation_degrees: float - """ - - _validation = { - "maximum_elevation_degrees": {"readonly": True}, - "tx_start_time": {"readonly": True}, - "tx_end_time": {"readonly": True}, - "rx_start_time": {"readonly": True}, - "rx_end_time": {"readonly": True}, - "start_azimuth_degrees": {"readonly": True}, - "end_azimuth_degrees": {"readonly": True}, - "start_elevation_degrees": {"readonly": True}, - "end_elevation_degrees": {"readonly": True}, - } - - _attribute_map = { - "maximum_elevation_degrees": {"key": "maximumElevationDegrees", "type": "float"}, - "tx_start_time": {"key": "txStartTime", "type": "iso-8601"}, - "tx_end_time": {"key": "txEndTime", "type": "iso-8601"}, - "rx_start_time": {"key": "rxStartTime", "type": "iso-8601"}, - "rx_end_time": {"key": "rxEndTime", "type": "iso-8601"}, - "start_azimuth_degrees": {"key": "startAzimuthDegrees", "type": "float"}, - "end_azimuth_degrees": {"key": "endAzimuthDegrees", "type": "float"}, - "start_elevation_degrees": {"key": "startElevationDegrees", "type": "float"}, - "end_elevation_degrees": {"key": "endElevationDegrees", "type": "float"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.maximum_elevation_degrees = None - self.tx_start_time = None - self.tx_end_time = None - self.rx_start_time = None - self.rx_end_time = None - self.start_azimuth_degrees = None - self.end_azimuth_degrees = None - self.start_elevation_degrees = None - self.end_elevation_degrees = None - - -class AvailableContactsProperties(ContactInstanceProperties): - """Properties of Contact resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar maximum_elevation_degrees: Maximum elevation of the antenna during the contact in decimal - degrees. - :vartype maximum_elevation_degrees: float - :ivar tx_start_time: Time at which antenna transmit will be enabled (ISO 8601 UTC standard). - :vartype tx_start_time: ~datetime.datetime - :ivar tx_end_time: Time at which antenna transmit will be disabled (ISO 8601 UTC standard). - :vartype tx_end_time: ~datetime.datetime - :ivar rx_start_time: Earliest time to receive a signal (ISO 8601 UTC standard). - :vartype rx_start_time: ~datetime.datetime - :ivar rx_end_time: Time to lost receiving a signal (ISO 8601 UTC standard). - :vartype rx_end_time: ~datetime.datetime - :ivar start_azimuth_degrees: Azimuth of the antenna at the start of the contact in decimal - degrees. - :vartype start_azimuth_degrees: float - :ivar end_azimuth_degrees: Azimuth of the antenna at the end of the contact in decimal degrees. - :vartype end_azimuth_degrees: float - :ivar start_elevation_degrees: Spacecraft elevation above the horizon at contact start. - :vartype start_elevation_degrees: float - :ivar end_elevation_degrees: Spacecraft elevation above the horizon at contact end. - :vartype end_elevation_degrees: float - """ - - _validation = { - "maximum_elevation_degrees": {"readonly": True}, - "tx_start_time": {"readonly": True}, - "tx_end_time": {"readonly": True}, - "rx_start_time": {"readonly": True}, - "rx_end_time": {"readonly": True}, - "start_azimuth_degrees": {"readonly": True}, - "end_azimuth_degrees": {"readonly": True}, - "start_elevation_degrees": {"readonly": True}, - "end_elevation_degrees": {"readonly": True}, - } - - _attribute_map = { - "maximum_elevation_degrees": {"key": "maximumElevationDegrees", "type": "float"}, - "tx_start_time": {"key": "txStartTime", "type": "iso-8601"}, - "tx_end_time": {"key": "txEndTime", "type": "iso-8601"}, - "rx_start_time": {"key": "rxStartTime", "type": "iso-8601"}, - "rx_end_time": {"key": "rxEndTime", "type": "iso-8601"}, - "start_azimuth_degrees": {"key": "startAzimuthDegrees", "type": "float"}, - "end_azimuth_degrees": {"key": "endAzimuthDegrees", "type": "float"}, - "start_elevation_degrees": {"key": "startElevationDegrees", "type": "float"}, - "end_elevation_degrees": {"key": "endElevationDegrees", "type": "float"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - - -class ResourceReference(_serialization.Model): - """Resource Reference. - - All required parameters must be populated in order to send to Azure. - - :ivar id: Resource ID. Required. - :vartype id: str - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - } - - def __init__(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin - """ - :keyword id: Resource ID. Required. - :paramtype id: str - """ - super().__init__(**kwargs) - self.id = id - - -class AvailableContactsSpacecraft(ResourceReference): - """The reference to the spacecraft resource. - - All required parameters must be populated in order to send to Azure. - - :ivar id: Resource ID. Required. - :vartype id: str - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - } - - def __init__(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin - """ - :keyword id: Resource ID. Required. - :paramtype id: str - """ - super().__init__(id=id, **kwargs) + self.next_link = next_link class AvailableGroundStation(_serialization.Model): - """Ground Stations available to schedule Contacts. + """AvailableGroundStation. Variables are only populated by the server, and will be ignored when sending a request. @@ -413,10 +237,10 @@ def __init__( :paramtype release_mode: str or ~azure.mgmt.orbital.models.ReleaseMode """ super().__init__(**kwargs) - self.id = None - self.name = None + self.id: Optional[str] = None + self.name: Optional[str] = None self.location = location - self.type = None + self.type: Optional[str] = None self.city = city self.provider_name = provider_name self.longitude_degrees = longitude_degrees @@ -426,18 +250,18 @@ def __init__( class AvailableGroundStationListResult(_serialization.Model): - """Response for the AvailableGroundStations API service call. + """Ground Stations available to schedule Contacts. - Variables are only populated by the server, and will be ignored when sending a request. + All required parameters must be populated in order to send to server. - :ivar value: A list of ground station resources. + :ivar value: The AvailableGroundStation items on this page. Required. :vartype value: list[~azure.mgmt.orbital.models.AvailableGroundStation] - :ivar next_link: The URL to get the next set of results. + :ivar next_link: The link to the next page of items. :vartype next_link: str """ _validation = { - "next_link": {"readonly": True}, + "value": {"required": True}, } _attribute_map = { @@ -445,138 +269,44 @@ class AvailableGroundStationListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, *, value: Optional[List["_models.AvailableGroundStation"]] = None, **kwargs: Any) -> None: + def __init__( + self, *, value: List["_models.AvailableGroundStation"], next_link: Optional[str] = None, **kwargs: Any + ) -> None: """ - :keyword value: A list of ground station resources. + :keyword value: The AvailableGroundStation items on this page. Required. :paramtype value: list[~azure.mgmt.orbital.models.AvailableGroundStation] + :keyword next_link: The link to the next page of items. + :paramtype next_link: str """ super().__init__(**kwargs) self.value = value - self.next_link = None + self.next_link = next_link -class AvailableGroundStationPropertiesAutoGenerated(_serialization.Model): - """Properties object for Available groundstation. +class AzureResourceManagerArmResponseAvailableContactsListResult(_serialization.Model): # pylint: disable=name-too-long + """Azure operation completed successfully. - :ivar city: City of ground station. - :vartype city: str - :ivar provider_name: Ground station provider name. - :vartype provider_name: str - :ivar longitude_degrees: Longitude of the ground station in decimal degrees. - :vartype longitude_degrees: float - :ivar latitude_degrees: Latitude of the ground station in decimal degrees. - :vartype latitude_degrees: float - :ivar altitude_meters: Altitude of the ground station. - :vartype altitude_meters: float - :ivar release_mode: Release Status of a ground station. Known values are: "Preview" and "GA". - :vartype release_mode: str or ~azure.mgmt.orbital.models.ReleaseMode + All required parameters must be populated in order to send to server. + + :ivar body: The body type of the operation request or response. Required. + :vartype body: ~azure.mgmt.orbital.models.AvailableContactsListResult """ - _attribute_map = { - "city": {"key": "city", "type": "str"}, - "provider_name": {"key": "providerName", "type": "str"}, - "longitude_degrees": {"key": "longitudeDegrees", "type": "float"}, - "latitude_degrees": {"key": "latitudeDegrees", "type": "float"}, - "altitude_meters": {"key": "altitudeMeters", "type": "float"}, - "release_mode": {"key": "releaseMode", "type": "str"}, + _validation = { + "body": {"required": True}, } - def __init__( - self, - *, - city: Optional[str] = None, - provider_name: Optional[str] = None, - longitude_degrees: Optional[float] = None, - latitude_degrees: Optional[float] = None, - altitude_meters: Optional[float] = None, - release_mode: Optional[Union[str, "_models.ReleaseMode"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword city: City of ground station. - :paramtype city: str - :keyword provider_name: Ground station provider name. - :paramtype provider_name: str - :keyword longitude_degrees: Longitude of the ground station in decimal degrees. - :paramtype longitude_degrees: float - :keyword latitude_degrees: Latitude of the ground station in decimal degrees. - :paramtype latitude_degrees: float - :keyword altitude_meters: Altitude of the ground station. - :paramtype altitude_meters: float - :keyword release_mode: Release Status of a ground station. Known values are: "Preview" and - "GA". - :paramtype release_mode: str or ~azure.mgmt.orbital.models.ReleaseMode - """ - super().__init__(**kwargs) - self.city = city - self.provider_name = provider_name - self.longitude_degrees = longitude_degrees - self.latitude_degrees = latitude_degrees - self.altitude_meters = altitude_meters - self.release_mode = release_mode - - -class AvailableGroundStationProperties(AvailableGroundStationPropertiesAutoGenerated): - """The properties bag for this resource. - - :ivar city: City of ground station. - :vartype city: str - :ivar provider_name: Ground station provider name. - :vartype provider_name: str - :ivar longitude_degrees: Longitude of the ground station in decimal degrees. - :vartype longitude_degrees: float - :ivar latitude_degrees: Latitude of the ground station in decimal degrees. - :vartype latitude_degrees: float - :ivar altitude_meters: Altitude of the ground station. - :vartype altitude_meters: float - :ivar release_mode: Release Status of a ground station. Known values are: "Preview" and "GA". - :vartype release_mode: str or ~azure.mgmt.orbital.models.ReleaseMode - """ - _attribute_map = { - "city": {"key": "city", "type": "str"}, - "provider_name": {"key": "providerName", "type": "str"}, - "longitude_degrees": {"key": "longitudeDegrees", "type": "float"}, - "latitude_degrees": {"key": "latitudeDegrees", "type": "float"}, - "altitude_meters": {"key": "altitudeMeters", "type": "float"}, - "release_mode": {"key": "releaseMode", "type": "str"}, + "body": {"key": "body", "type": "AvailableContactsListResult"}, } - def __init__( - self, - *, - city: Optional[str] = None, - provider_name: Optional[str] = None, - longitude_degrees: Optional[float] = None, - latitude_degrees: Optional[float] = None, - altitude_meters: Optional[float] = None, - release_mode: Optional[Union[str, "_models.ReleaseMode"]] = None, - **kwargs: Any - ) -> None: + def __init__(self, *, body: "_models.AvailableContactsListResult", **kwargs: Any) -> None: """ - :keyword city: City of ground station. - :paramtype city: str - :keyword provider_name: Ground station provider name. - :paramtype provider_name: str - :keyword longitude_degrees: Longitude of the ground station in decimal degrees. - :paramtype longitude_degrees: float - :keyword latitude_degrees: Latitude of the ground station in decimal degrees. - :paramtype latitude_degrees: float - :keyword altitude_meters: Altitude of the ground station. - :paramtype altitude_meters: float - :keyword release_mode: Release Status of a ground station. Known values are: "Preview" and - "GA". - :paramtype release_mode: str or ~azure.mgmt.orbital.models.ReleaseMode + :keyword body: The body type of the operation request or response. Required. + :paramtype body: ~azure.mgmt.orbital.models.AvailableContactsListResult """ - super().__init__( - city=city, - provider_name=provider_name, - longitude_degrees=longitude_degrees, - latitude_degrees=latitude_degrees, - altitude_meters=altitude_meters, - release_mode=release_mode, - **kwargs - ) + super().__init__(**kwargs) + self.body = body class Resource(_serialization.Model): @@ -614,10 +344,10 @@ class Resource(_serialization.Model): def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.system_data = None + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None class ProxyResource(Resource): @@ -639,31 +369,13 @@ class ProxyResource(Resource): :vartype system_data: ~azure.mgmt.orbital.models.SystemData """ - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"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"}, - } - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - - -class Contact(ProxyResource): # pylint: disable=too-many-instance-attributes +class Contact(ProxyResource): """Customer creates a contact resource for a spacecraft resource. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. @@ -679,8 +391,7 @@ class Contact(ProxyResource): # pylint: disable=too-many-instance-attributes :ivar provisioning_state: The current state of the resource's creation, deletion, or modification. Known values are: "creating", "succeeded", "failed", "canceled", "updating", and "deleting". - :vartype provisioning_state: str or - ~azure.mgmt.orbital.models.ContactsPropertiesProvisioningState + :vartype provisioning_state: str or ~azure.mgmt.orbital.models.ProvisioningState :ivar status: Status of a contact. Known values are: "scheduled", "cancelled", "succeeded", "failed", and "providerCancelled". :vartype status: str or ~azure.mgmt.orbital.models.ContactsStatus @@ -718,7 +429,7 @@ class Contact(ProxyResource): # pylint: disable=too-many-instance-attributes :vartype antenna_configuration: ~azure.mgmt.orbital.models.ContactsPropertiesAntennaConfiguration :ivar contact_profile: The reference to the contact profile resource. Required. - :vartype contact_profile: ~azure.mgmt.orbital.models.ContactsPropertiesContactProfile + :vartype contact_profile: ~azure.mgmt.orbital.models.ResourceReference """ _validation = { @@ -768,7 +479,7 @@ class Contact(ProxyResource): # pylint: disable=too-many-instance-attributes "key": "properties.antennaConfiguration", "type": "ContactsPropertiesAntennaConfiguration", }, - "contact_profile": {"key": "properties.contactProfile", "type": "ContactsPropertiesContactProfile"}, + "contact_profile": {"key": "properties.contactProfile", "type": "ResourceReference"}, } def __init__( @@ -777,16 +488,15 @@ def __init__( reservation_start_time: datetime.datetime, reservation_end_time: datetime.datetime, ground_station_name: str, - contact_profile: "_models.ContactsPropertiesContactProfile", - provisioning_state: Optional[Union[str, "_models.ContactsPropertiesProvisioningState"]] = None, + contact_profile: "_models.ResourceReference", + provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None, **kwargs: Any ) -> None: """ :keyword provisioning_state: The current state of the resource's creation, deletion, or modification. Known values are: "creating", "succeeded", "failed", "canceled", "updating", and "deleting". - :paramtype provisioning_state: str or - ~azure.mgmt.orbital.models.ContactsPropertiesProvisioningState + :paramtype provisioning_state: str or ~azure.mgmt.orbital.models.ProvisioningState :keyword reservation_start_time: Reservation start time of a contact (ISO 8601 UTC standard). Required. :paramtype reservation_start_time: ~datetime.datetime @@ -796,41 +506,41 @@ def __init__( :keyword ground_station_name: Azure Ground Station name. Required. :paramtype ground_station_name: str :keyword contact_profile: The reference to the contact profile resource. Required. - :paramtype contact_profile: ~azure.mgmt.orbital.models.ContactsPropertiesContactProfile + :paramtype contact_profile: ~azure.mgmt.orbital.models.ResourceReference """ super().__init__(**kwargs) self.provisioning_state = provisioning_state - self.status = None + self.status: Optional[Union[str, "_models.ContactsStatus"]] = None self.reservation_start_time = reservation_start_time self.reservation_end_time = reservation_end_time - self.rx_start_time = None - self.rx_end_time = None - self.tx_start_time = None - self.tx_end_time = None - self.error_message = None - self.maximum_elevation_degrees = None - self.start_azimuth_degrees = None - self.end_azimuth_degrees = None + self.rx_start_time: Optional[datetime.datetime] = None + self.rx_end_time: Optional[datetime.datetime] = None + self.tx_start_time: Optional[datetime.datetime] = None + self.tx_end_time: Optional[datetime.datetime] = None + self.error_message: Optional[str] = None + self.maximum_elevation_degrees: Optional[float] = None + self.start_azimuth_degrees: Optional[float] = None + self.end_azimuth_degrees: Optional[float] = None self.ground_station_name = ground_station_name - self.start_elevation_degrees = None - self.end_elevation_degrees = None - self.antenna_configuration = None + self.start_elevation_degrees: Optional[float] = None + self.end_elevation_degrees: Optional[float] = None + self.antenna_configuration: Optional["_models.ContactsPropertiesAntennaConfiguration"] = None self.contact_profile = contact_profile class ContactListResult(_serialization.Model): - """Response for the ListContacts API service call. + """The response of a Contact list operation. - Variables are only populated by the server, and will be ignored when sending a request. + All required parameters must be populated in order to send to server. - :ivar value: A list of contact resources in a resource group. + :ivar value: The Contact items on this page. Required. :vartype value: list[~azure.mgmt.orbital.models.Contact] - :ivar next_link: The URL to get the next set of results. + :ivar next_link: The link to the next page of items. :vartype next_link: str """ _validation = { - "next_link": {"readonly": True}, + "value": {"required": True}, } _attribute_map = { @@ -838,23 +548,25 @@ class ContactListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, *, value: Optional[List["_models.Contact"]] = None, **kwargs: Any) -> None: + def __init__(self, *, value: List["_models.Contact"], next_link: Optional[str] = None, **kwargs: Any) -> None: """ - :keyword value: A list of contact resources in a resource group. + :keyword value: The Contact items on this page. Required. :paramtype value: list[~azure.mgmt.orbital.models.Contact] + :keyword next_link: The link to the next page of items. + :paramtype next_link: str """ super().__init__(**kwargs) self.value = value - self.next_link = None + self.next_link = next_link class ContactParameters(_serialization.Model): """Parameters that define the contact resource. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar contact_profile: The reference to the contact profile resource. Required. - :vartype contact_profile: ~azure.mgmt.orbital.models.ContactParametersContactProfile + :vartype contact_profile: ~azure.mgmt.orbital.models.ResourceReference :ivar ground_station_name: Name of Azure Ground Station. Required. :vartype ground_station_name: str :ivar start_time: Start time of a contact (ISO 8601 UTC standard). Required. @@ -871,7 +583,7 @@ class ContactParameters(_serialization.Model): } _attribute_map = { - "contact_profile": {"key": "contactProfile", "type": "ContactParametersContactProfile"}, + "contact_profile": {"key": "contactProfile", "type": "ResourceReference"}, "ground_station_name": {"key": "groundStationName", "type": "str"}, "start_time": {"key": "startTime", "type": "iso-8601"}, "end_time": {"key": "endTime", "type": "iso-8601"}, @@ -880,52 +592,27 @@ class ContactParameters(_serialization.Model): def __init__( self, *, - contact_profile: "_models.ContactParametersContactProfile", + contact_profile: "_models.ResourceReference", ground_station_name: str, start_time: datetime.datetime, - end_time: datetime.datetime, - **kwargs: Any - ) -> None: - """ - :keyword contact_profile: The reference to the contact profile resource. Required. - :paramtype contact_profile: ~azure.mgmt.orbital.models.ContactParametersContactProfile - :keyword ground_station_name: Name of Azure Ground Station. Required. - :paramtype ground_station_name: str - :keyword start_time: Start time of a contact (ISO 8601 UTC standard). Required. - :paramtype start_time: ~datetime.datetime - :keyword end_time: End time of a contact (ISO 8601 UTC standard). Required. - :paramtype end_time: ~datetime.datetime - """ - super().__init__(**kwargs) - self.contact_profile = contact_profile - self.ground_station_name = ground_station_name - self.start_time = start_time - self.end_time = end_time - - -class ContactParametersContactProfile(ResourceReference): - """The reference to the contact profile resource. - - All required parameters must be populated in order to send to Azure. - - :ivar id: Resource ID. Required. - :vartype id: str - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - } - - def __init__(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + end_time: datetime.datetime, + **kwargs: Any + ) -> None: """ - :keyword id: Resource ID. Required. - :paramtype id: str + :keyword contact_profile: The reference to the contact profile resource. Required. + :paramtype contact_profile: ~azure.mgmt.orbital.models.ResourceReference + :keyword ground_station_name: Name of Azure Ground Station. Required. + :paramtype ground_station_name: str + :keyword start_time: Start time of a contact (ISO 8601 UTC standard). Required. + :paramtype start_time: ~datetime.datetime + :keyword end_time: End time of a contact (ISO 8601 UTC standard). Required. + :paramtype end_time: ~datetime.datetime """ - super().__init__(id=id, **kwargs) + super().__init__(**kwargs) + self.contact_profile = contact_profile + self.ground_station_name = ground_station_name + self.start_time = start_time + self.end_time = end_time class TrackedResource(Resource): @@ -934,7 +621,7 @@ class TrackedResource(Resource): Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. @@ -982,13 +669,13 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.location = location -class ContactProfile(TrackedResource): # pylint: disable=too-many-instance-attributes +class ContactProfile(TrackedResource): """Customer creates a Contact Profile Resource, which will contain all of the configurations required for scheduling a contact. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. @@ -1008,8 +695,7 @@ class ContactProfile(TrackedResource): # pylint: disable=too-many-instance-attr :ivar provisioning_state: The current state of the resource's creation, deletion, or modification. Known values are: "creating", "succeeded", "failed", "canceled", "updating", and "deleting". - :vartype provisioning_state: str or - ~azure.mgmt.orbital.models.ContactProfilesPropertiesProvisioningState + :vartype provisioning_state: str or ~azure.mgmt.orbital.models.ProvisioningState :ivar minimum_viable_contact_duration: Minimum viable contact duration in ISO 8601 format. Used for listing the available contacts with a spacecraft at a given ground station. :vartype minimum_viable_contact_duration: str @@ -1075,7 +761,7 @@ def __init__( network_configuration: "_models.ContactProfilesPropertiesNetworkConfiguration", links: List["_models.ContactProfileLink"], tags: Optional[Dict[str, str]] = None, - provisioning_state: Optional[Union[str, "_models.ContactProfilesPropertiesProvisioningState"]] = None, + provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None, minimum_viable_contact_duration: Optional[str] = None, minimum_elevation_degrees: Optional[float] = None, auto_tracking_configuration: Optional[Union[str, "_models.AutoTrackingConfiguration"]] = None, @@ -1091,8 +777,7 @@ def __init__( :keyword provisioning_state: The current state of the resource's creation, deletion, or modification. Known values are: "creating", "succeeded", "failed", "canceled", "updating", and "deleting". - :paramtype provisioning_state: str or - ~azure.mgmt.orbital.models.ContactProfilesPropertiesProvisioningState + :paramtype provisioning_state: str or ~azure.mgmt.orbital.models.ProvisioningState :keyword minimum_viable_contact_duration: Minimum viable contact duration in ISO 8601 format. Used for listing the available contacts with a spacecraft at a given ground station. :paramtype minimum_viable_contact_duration: str @@ -1131,7 +816,7 @@ def __init__( class ContactProfileLink(_serialization.Model): """Contact Profile Link. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar name: Link name. Required. :vartype name: str @@ -1208,7 +893,7 @@ def __init__( class ContactProfileLinkChannel(_serialization.Model): """Contact Profile Link Channel. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar name: Channel name. Required. :vartype name: str @@ -1299,18 +984,18 @@ def __init__( class ContactProfileListResult(_serialization.Model): - """Response for the ListContactProfiles API service call. + """The response of a ContactProfile list operation. - Variables are only populated by the server, and will be ignored when sending a request. + All required parameters must be populated in order to send to server. - :ivar value: A list of contact profile resources in a resource group. + :ivar value: The ContactProfile items on this page. Required. :vartype value: list[~azure.mgmt.orbital.models.ContactProfile] - :ivar next_link: The URL to get the next set of results. + :ivar next_link: The link to the next page of items. :vartype next_link: str """ _validation = { - "next_link": {"readonly": True}, + "value": {"required": True}, } _attribute_map = { @@ -1318,244 +1003,24 @@ class ContactProfileListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, *, value: Optional[List["_models.ContactProfile"]] = None, **kwargs: Any) -> None: - """ - :keyword value: A list of contact profile resources in a resource group. - :paramtype value: list[~azure.mgmt.orbital.models.ContactProfile] - """ - super().__init__(**kwargs) - self.value = value - self.next_link = None - - -class ContactProfilesProperties(_serialization.Model): - """List of Contact Profile Resource Properties. - - All required parameters must be populated in order to send to Azure. - - :ivar provisioning_state: The current state of the resource's creation, deletion, or - modification. Known values are: "creating", "succeeded", "failed", "canceled", "updating", and - "deleting". - :vartype provisioning_state: str or - ~azure.mgmt.orbital.models.ContactProfilesPropertiesProvisioningState - :ivar minimum_viable_contact_duration: Minimum viable contact duration in ISO 8601 format. Used - for listing the available contacts with a spacecraft at a given ground station. - :vartype minimum_viable_contact_duration: str - :ivar minimum_elevation_degrees: Minimum viable elevation for the contact in decimal degrees. - Used for listing the available contacts with a spacecraft at a given ground station. - :vartype minimum_elevation_degrees: float - :ivar auto_tracking_configuration: Auto-tracking configuration. Known values are: "disabled", - "xBand", and "sBand". - :vartype auto_tracking_configuration: str or - ~azure.mgmt.orbital.models.AutoTrackingConfiguration - :ivar event_hub_uri: ARM resource identifier of the Event Hub used for telemetry. Requires - granting Orbital Resource Provider the rights to send telemetry into the hub. - :vartype event_hub_uri: str - :ivar network_configuration: Network configuration of customer virtual network. Required. - :vartype network_configuration: - ~azure.mgmt.orbital.models.ContactProfilesPropertiesNetworkConfiguration - :ivar third_party_configurations: Third-party mission configuration of the Contact Profile. - Describes RF links, modem processing, and IP endpoints. - :vartype third_party_configurations: - list[~azure.mgmt.orbital.models.ContactProfileThirdPartyConfiguration] - :ivar links: Links of the Contact Profile. Describes RF links, modem processing, and IP - endpoints. Required. - :vartype links: list[~azure.mgmt.orbital.models.ContactProfileLink] - """ - - _validation = { - "network_configuration": {"required": True}, - "links": {"required": True}, - } - - _attribute_map = { - "provisioning_state": {"key": "provisioningState", "type": "str"}, - "minimum_viable_contact_duration": {"key": "minimumViableContactDuration", "type": "str"}, - "minimum_elevation_degrees": {"key": "minimumElevationDegrees", "type": "float"}, - "auto_tracking_configuration": {"key": "autoTrackingConfiguration", "type": "str"}, - "event_hub_uri": {"key": "eventHubUri", "type": "str"}, - "network_configuration": { - "key": "networkConfiguration", - "type": "ContactProfilesPropertiesNetworkConfiguration", - }, - "third_party_configurations": { - "key": "thirdPartyConfigurations", - "type": "[ContactProfileThirdPartyConfiguration]", - }, - "links": {"key": "links", "type": "[ContactProfileLink]"}, - } - def __init__( - self, - *, - network_configuration: "_models.ContactProfilesPropertiesNetworkConfiguration", - links: List["_models.ContactProfileLink"], - provisioning_state: Optional[Union[str, "_models.ContactProfilesPropertiesProvisioningState"]] = None, - minimum_viable_contact_duration: Optional[str] = None, - minimum_elevation_degrees: Optional[float] = None, - auto_tracking_configuration: Optional[Union[str, "_models.AutoTrackingConfiguration"]] = None, - event_hub_uri: Optional[str] = None, - third_party_configurations: Optional[List["_models.ContactProfileThirdPartyConfiguration"]] = None, - **kwargs: Any + self, *, value: List["_models.ContactProfile"], next_link: Optional[str] = None, **kwargs: Any ) -> None: """ - :keyword provisioning_state: The current state of the resource's creation, deletion, or - modification. Known values are: "creating", "succeeded", "failed", "canceled", "updating", and - "deleting". - :paramtype provisioning_state: str or - ~azure.mgmt.orbital.models.ContactProfilesPropertiesProvisioningState - :keyword minimum_viable_contact_duration: Minimum viable contact duration in ISO 8601 format. - Used for listing the available contacts with a spacecraft at a given ground station. - :paramtype minimum_viable_contact_duration: str - :keyword minimum_elevation_degrees: Minimum viable elevation for the contact in decimal - degrees. Used for listing the available contacts with a spacecraft at a given ground station. - :paramtype minimum_elevation_degrees: float - :keyword auto_tracking_configuration: Auto-tracking configuration. Known values are: - "disabled", "xBand", and "sBand". - :paramtype auto_tracking_configuration: str or - ~azure.mgmt.orbital.models.AutoTrackingConfiguration - :keyword event_hub_uri: ARM resource identifier of the Event Hub used for telemetry. Requires - granting Orbital Resource Provider the rights to send telemetry into the hub. - :paramtype event_hub_uri: str - :keyword network_configuration: Network configuration of customer virtual network. Required. - :paramtype network_configuration: - ~azure.mgmt.orbital.models.ContactProfilesPropertiesNetworkConfiguration - :keyword third_party_configurations: Third-party mission configuration of the Contact Profile. - Describes RF links, modem processing, and IP endpoints. - :paramtype third_party_configurations: - list[~azure.mgmt.orbital.models.ContactProfileThirdPartyConfiguration] - :keyword links: Links of the Contact Profile. Describes RF links, modem processing, and IP - endpoints. Required. - :paramtype links: list[~azure.mgmt.orbital.models.ContactProfileLink] + :keyword value: The ContactProfile items on this page. Required. + :paramtype value: list[~azure.mgmt.orbital.models.ContactProfile] + :keyword next_link: The link to the next page of items. + :paramtype next_link: str """ super().__init__(**kwargs) - self.provisioning_state = provisioning_state - self.minimum_viable_contact_duration = minimum_viable_contact_duration - self.minimum_elevation_degrees = minimum_elevation_degrees - self.auto_tracking_configuration = auto_tracking_configuration - self.event_hub_uri = event_hub_uri - self.network_configuration = network_configuration - self.third_party_configurations = third_party_configurations - self.links = links - - -class ContactProfileProperties(ContactProfilesProperties): - """Properties of the contact profile resource. - - All required parameters must be populated in order to send to Azure. - - :ivar provisioning_state: The current state of the resource's creation, deletion, or - modification. Known values are: "creating", "succeeded", "failed", "canceled", "updating", and - "deleting". - :vartype provisioning_state: str or - ~azure.mgmt.orbital.models.ContactProfilesPropertiesProvisioningState - :ivar minimum_viable_contact_duration: Minimum viable contact duration in ISO 8601 format. Used - for listing the available contacts with a spacecraft at a given ground station. - :vartype minimum_viable_contact_duration: str - :ivar minimum_elevation_degrees: Minimum viable elevation for the contact in decimal degrees. - Used for listing the available contacts with a spacecraft at a given ground station. - :vartype minimum_elevation_degrees: float - :ivar auto_tracking_configuration: Auto-tracking configuration. Known values are: "disabled", - "xBand", and "sBand". - :vartype auto_tracking_configuration: str or - ~azure.mgmt.orbital.models.AutoTrackingConfiguration - :ivar event_hub_uri: ARM resource identifier of the Event Hub used for telemetry. Requires - granting Orbital Resource Provider the rights to send telemetry into the hub. - :vartype event_hub_uri: str - :ivar network_configuration: Network configuration of customer virtual network. Required. - :vartype network_configuration: - ~azure.mgmt.orbital.models.ContactProfilesPropertiesNetworkConfiguration - :ivar third_party_configurations: Third-party mission configuration of the Contact Profile. - Describes RF links, modem processing, and IP endpoints. - :vartype third_party_configurations: - list[~azure.mgmt.orbital.models.ContactProfileThirdPartyConfiguration] - :ivar links: Links of the Contact Profile. Describes RF links, modem processing, and IP - endpoints. Required. - :vartype links: list[~azure.mgmt.orbital.models.ContactProfileLink] - """ - - _validation = { - "network_configuration": {"required": True}, - "links": {"required": True}, - } + self.value = value + self.next_link = next_link - _attribute_map = { - "provisioning_state": {"key": "provisioningState", "type": "str"}, - "minimum_viable_contact_duration": {"key": "minimumViableContactDuration", "type": "str"}, - "minimum_elevation_degrees": {"key": "minimumElevationDegrees", "type": "float"}, - "auto_tracking_configuration": {"key": "autoTrackingConfiguration", "type": "str"}, - "event_hub_uri": {"key": "eventHubUri", "type": "str"}, - "network_configuration": { - "key": "networkConfiguration", - "type": "ContactProfilesPropertiesNetworkConfiguration", - }, - "third_party_configurations": { - "key": "thirdPartyConfigurations", - "type": "[ContactProfileThirdPartyConfiguration]", - }, - "links": {"key": "links", "type": "[ContactProfileLink]"}, - } - def __init__( - self, - *, - network_configuration: "_models.ContactProfilesPropertiesNetworkConfiguration", - links: List["_models.ContactProfileLink"], - provisioning_state: Optional[Union[str, "_models.ContactProfilesPropertiesProvisioningState"]] = None, - minimum_viable_contact_duration: Optional[str] = None, - minimum_elevation_degrees: Optional[float] = None, - auto_tracking_configuration: Optional[Union[str, "_models.AutoTrackingConfiguration"]] = None, - event_hub_uri: Optional[str] = None, - third_party_configurations: Optional[List["_models.ContactProfileThirdPartyConfiguration"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword provisioning_state: The current state of the resource's creation, deletion, or - modification. Known values are: "creating", "succeeded", "failed", "canceled", "updating", and - "deleting". - :paramtype provisioning_state: str or - ~azure.mgmt.orbital.models.ContactProfilesPropertiesProvisioningState - :keyword minimum_viable_contact_duration: Minimum viable contact duration in ISO 8601 format. - Used for listing the available contacts with a spacecraft at a given ground station. - :paramtype minimum_viable_contact_duration: str - :keyword minimum_elevation_degrees: Minimum viable elevation for the contact in decimal - degrees. Used for listing the available contacts with a spacecraft at a given ground station. - :paramtype minimum_elevation_degrees: float - :keyword auto_tracking_configuration: Auto-tracking configuration. Known values are: - "disabled", "xBand", and "sBand". - :paramtype auto_tracking_configuration: str or - ~azure.mgmt.orbital.models.AutoTrackingConfiguration - :keyword event_hub_uri: ARM resource identifier of the Event Hub used for telemetry. Requires - granting Orbital Resource Provider the rights to send telemetry into the hub. - :paramtype event_hub_uri: str - :keyword network_configuration: Network configuration of customer virtual network. Required. - :paramtype network_configuration: - ~azure.mgmt.orbital.models.ContactProfilesPropertiesNetworkConfiguration - :keyword third_party_configurations: Third-party mission configuration of the Contact Profile. - Describes RF links, modem processing, and IP endpoints. - :paramtype third_party_configurations: - list[~azure.mgmt.orbital.models.ContactProfileThirdPartyConfiguration] - :keyword links: Links of the Contact Profile. Describes RF links, modem processing, and IP - endpoints. Required. - :paramtype links: list[~azure.mgmt.orbital.models.ContactProfileLink] - """ - super().__init__( - provisioning_state=provisioning_state, - minimum_viable_contact_duration=minimum_viable_contact_duration, - minimum_elevation_degrees=minimum_elevation_degrees, - auto_tracking_configuration=auto_tracking_configuration, - event_hub_uri=event_hub_uri, - network_configuration=network_configuration, - third_party_configurations=third_party_configurations, - links=links, - **kwargs - ) - - -class ContactProfilesPropertiesNetworkConfiguration(_serialization.Model): +class ContactProfilesPropertiesNetworkConfiguration(_serialization.Model): # pylint: disable=name-too-long """Network configuration of customer virtual network. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar subnet_id: ARM resource identifier of the subnet delegated to the Microsoft.Orbital/orbitalGateways. Needs to be at least a class C subnet, and should not have @@ -1585,7 +1050,7 @@ def __init__(self, *, subnet_id: str, **kwargs: Any) -> None: class ContactProfileThirdPartyConfiguration(_serialization.Model): """Contact Profile third-party partner configuration. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar provider_name: Name of the third-party provider. Required. :vartype provider_name: str @@ -1649,35 +1114,10 @@ def __init__( self.source_ips = source_ips -class ContactsPropertiesContactProfile(ResourceReference): - """The reference to the contact profile resource. - - All required parameters must be populated in order to send to Azure. - - :ivar id: Resource ID. Required. - :vartype id: str - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - } - - def __init__(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin - """ - :keyword id: Resource ID. Required. - :paramtype id: str - """ - super().__init__(id=id, **kwargs) - - class EndPoint(_serialization.Model): """Customer end point to store and retrieve data during a contact with the spacecraft. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar ip_address: IP Address (IPv4). Required. :vartype ip_address: str @@ -1753,8 +1193,8 @@ class ErrorAdditionalInfo(_serialization.Model): def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.type = None - self.info = None + self.type: Optional[str] = None + self.info: Optional[JSON] = None class ErrorDetail(_serialization.Model): @@ -1793,11 +1233,11 @@ class ErrorDetail(_serialization.Model): def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None + self.code: Optional[str] = None + self.message: Optional[str] = None + self.target: Optional[str] = None + self.details: Optional[List["_models.ErrorDetail"]] = None + self.additional_info: Optional[List["_models.ErrorAdditionalInfo"]] = None class ErrorResponse(_serialization.Model): @@ -1864,11 +1304,11 @@ def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kw :paramtype display: ~azure.mgmt.orbital.models.OperationDisplay """ super().__init__(**kwargs) - self.name = None - self.is_data_action = None + self.name: Optional[str] = None + self.is_data_action: Optional[bool] = None self.display = display - self.origin = None - self.action_type = None + self.origin: Optional[Union[str, "_models.Origin"]] = None + self.action_type: Optional[Union[str, "_models.ActionType"]] = None class OperationDisplay(_serialization.Model): @@ -1907,10 +1347,10 @@ class OperationDisplay(_serialization.Model): def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.provider = None - self.resource = None - self.operation = None - self.description = None + self.provider: Optional[str] = None + self.resource: Optional[str] = None + self.operation: Optional[str] = None + self.description: Optional[str] = None class OperationListResult(_serialization.Model): @@ -1938,8 +1378,8 @@ class OperationListResult(_serialization.Model): def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.value = None - self.next_link = None + self.value: Optional[List["_models.Operation"]] = None + self.next_link: Optional[str] = None class OperationResult(_serialization.Model): @@ -1961,11 +1401,11 @@ class OperationResult(_serialization.Model): :ivar percent_complete: Percentage completed. :vartype percent_complete: float :ivar value: A list of results when the operation returns multiple results. - :vartype value: list[JSON] + :vartype value: list[dict[str, any]] :ivar next_link: The URL to get the next set of results. :vartype next_link: str :ivar properties: Operation result properties. - :vartype properties: JSON + :vartype properties: dict[str, any] :ivar error: Operation result error properties. :vartype error: ~azure.mgmt.orbital.models.OperationResultErrorProperties """ @@ -1988,34 +1428,34 @@ class OperationResult(_serialization.Model): "start_time": {"key": "startTime", "type": "iso-8601"}, "end_time": {"key": "endTime", "type": "iso-8601"}, "percent_complete": {"key": "percentComplete", "type": "float"}, - "value": {"key": "value", "type": "[object]"}, + "value": {"key": "value", "type": "[{object}]"}, "next_link": {"key": "nextLink", "type": "str"}, - "properties": {"key": "properties", "type": "object"}, + "properties": {"key": "properties", "type": "{object}"}, "error": {"key": "error", "type": "OperationResultErrorProperties"}, } def __init__( self, *, - properties: Optional[JSON] = None, + properties: Optional[Dict[str, Any]] = None, error: Optional["_models.OperationResultErrorProperties"] = None, **kwargs: Any ) -> None: """ :keyword properties: Operation result properties. - :paramtype properties: JSON + :paramtype properties: dict[str, any] :keyword error: Operation result error properties. :paramtype error: ~azure.mgmt.orbital.models.OperationResultErrorProperties """ super().__init__(**kwargs) - self.id = None - self.name = None - self.status = None - self.start_time = None - self.end_time = None - self.percent_complete = None - self.value = None - self.next_link = None + self.id: Optional[str] = None + self.name: Optional[str] = None + self.status: Optional[Union[str, "_models.Status"]] = None + self.start_time: Optional[datetime.datetime] = None + self.end_time: Optional[datetime.datetime] = None + self.percent_complete: Optional[float] = None + self.value: Optional[List[Dict[str, Any]]] = None + self.next_link: Optional[str] = None self.properties = properties self.error = error @@ -2044,67 +1484,42 @@ class OperationResultErrorProperties(_serialization.Model): def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.code = None - self.message = None + self.code: Optional[str] = None + self.message: Optional[str] = None -class ResourceIdListResult(_serialization.Model): - """Response for an API service call that lists the resource IDs of resources associated with - another resource. +class ResourceReference(_serialization.Model): + """Resource Reference. - Variables are only populated by the server, and will be ignored when sending a request. + All required parameters must be populated in order to send to server. - :ivar value: A list of Azure Resource IDs. - :vartype value: list[~azure.mgmt.orbital.models.ResourceIdListResultValueItem] - :ivar next_link: The URL to get the next set of results. - :vartype next_link: str + :ivar id: Resource ID. Required. + :vartype id: str """ _validation = { - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[ResourceIdListResultValueItem]"}, - "next_link": {"key": "nextLink", "type": "str"}, + "id": {"required": True}, } - def __init__(self, *, value: Optional[List["_models.ResourceIdListResultValueItem"]] = None, **kwargs: Any) -> None: - """ - :keyword value: A list of Azure Resource IDs. - :paramtype value: list[~azure.mgmt.orbital.models.ResourceIdListResultValueItem] - """ - super().__init__(**kwargs) - self.value = value - self.next_link = None - - -class ResourceIdListResultValueItem(_serialization.Model): - """ResourceIdListResultValueItem. - - :ivar id: The Azure Resource ID. - :vartype id: str - """ - _attribute_map = { "id": {"key": "id", "type": "str"}, } - def __init__(self, *, id: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + def __init__(self, *, id: str, **kwargs: Any) -> None: # pylint: disable=redefined-builtin """ - :keyword id: The Azure Resource ID. + :keyword id: Resource ID. Required. :paramtype id: str """ super().__init__(**kwargs) self.id = id -class Spacecraft(TrackedResource): # pylint: disable=too-many-instance-attributes +class Spacecraft(TrackedResource): """Customer creates a spacecraft resource to schedule a contact. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. @@ -2214,7 +1629,7 @@ class SpacecraftLink(_serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar name: Link name. Required. :vartype name: str @@ -2280,22 +1695,22 @@ def __init__( self.bandwidth_m_hz = bandwidth_m_hz self.direction = direction self.polarization = polarization - self.authorizations = None + self.authorizations: Optional[List["_models.AuthorizedGroundstation"]] = None class SpacecraftListResult(_serialization.Model): - """Response for the ListSpacecrafts API service call. + """The response of a Spacecraft list operation. - Variables are only populated by the server, and will be ignored when sending a request. + All required parameters must be populated in order to send to server. - :ivar value: A list of spacecraft resources in a resource group. + :ivar value: The Spacecraft items on this page. Required. :vartype value: list[~azure.mgmt.orbital.models.Spacecraft] - :ivar next_link: The URL to get the next set of results. + :ivar next_link: The link to the next page of items. :vartype next_link: str """ _validation = { - "next_link": {"readonly": True}, + "value": {"required": True}, } _attribute_map = { @@ -2303,14 +1718,16 @@ class SpacecraftListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, *, value: Optional[List["_models.Spacecraft"]] = None, **kwargs: Any) -> None: + def __init__(self, *, value: List["_models.Spacecraft"], next_link: Optional[str] = None, **kwargs: Any) -> None: """ - :keyword value: A list of spacecraft resources in a resource group. + :keyword value: The Spacecraft items on this page. Required. :paramtype value: list[~azure.mgmt.orbital.models.Spacecraft] + :keyword next_link: The link to the next page of items. + :paramtype next_link: str """ super().__init__(**kwargs) self.value = value - self.next_link = None + self.next_link = next_link class SystemData(_serialization.Model): diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/__init__.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/__init__.py index d97b0cb1b651..0ce0e44f988f 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/__init__.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/__init__.py @@ -5,25 +5,31 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import Operations -from ._spacecrafts_operations import SpacecraftsOperations -from ._contacts_operations import ContactsOperations -from ._contact_profiles_operations import ContactProfilesOperations -from ._available_ground_stations_operations import AvailableGroundStationsOperations -from ._operations_results_operations import OperationsResultsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._available_ground_stations_operations import AvailableGroundStationsOperations # type: ignore +from ._contact_profiles_operations import ContactProfilesOperations # type: ignore +from ._operations_results_operations import OperationsResultsOperations # type: ignore +from ._spacecrafts_operations import SpacecraftsOperations # type: ignore +from ._contacts_operations import ContactsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "Operations", - "SpacecraftsOperations", - "ContactsOperations", - "ContactProfilesOperations", "AvailableGroundStationsOperations", + "ContactProfilesOperations", "OperationsResultsOperations", + "SpacecraftsOperations", + "ContactsOperations", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_available_ground_stations_operations.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_available_ground_stations_operations.py index 8ae531013f35..8cd619541d25 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_available_ground_stations_operations.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_available_ground_stations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys +from collections.abc import MutableMapping from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -20,20 +20,15 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +from .._configuration import AzureOrbitalConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -47,7 +42,7 @@ def build_list_by_capability_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -58,7 +53,7 @@ def build_list_by_capability_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -84,10 +79,10 @@ class AvailableGroundStationsOperations: 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") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureOrbitalConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_capability( @@ -98,7 +93,6 @@ def list_by_capability( :param capability: Ground Station Capability. Known values are: "EarthObservation" and "Communication". Required. :type capability: str or ~azure.mgmt.orbital.models.CapabilityParameter - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AvailableGroundStation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.orbital.models.AvailableGroundStation] @@ -107,12 +101,10 @@ def list_by_capability( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.AvailableGroundStationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -123,16 +115,14 @@ def list_by_capability( def prepare_request(next_link=None): if not next_link: - request = build_list_by_capability_request( + _request = build_list_by_capability_request( subscription_id=self._config.subscription_id, capability=capability, api_version=api_version, - template_url=self.list_by_capability.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -144,13 +134,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AvailableGroundStationListResult", pipeline_response) @@ -160,10 +149,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -175,7 +165,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_capability.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Orbital/availableGroundStations" - } diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_contact_profiles_operations.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_contact_profiles_operations.py index a2add8163b7a..752fe97834bb 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_contact_profiles_operations.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_contact_profiles_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,36 +6,35 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, IO, Iterable, List, Optional, TypeVar, Union, cast, overload +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +from .._configuration import AzureOrbitalConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -43,32 +42,27 @@ _SERIALIZER.client_side_validation = False -def build_get_request( - resource_group_name: str, contact_profile_name: str, subscription_id: str, **kwargs: Any +def build_list_by_subscription_request( + subscription_id: str, *, skiptoken: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}", - ) # pylint: disable=line-too-long + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Orbital/contactProfiles") path_format_arguments = { - "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), - "contactProfileName": _SERIALIZER.url("contact_profile_name", contact_profile_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skiptoken is not None: + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -76,65 +70,63 @@ def build_get_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_create_or_update_request( - resource_group_name: str, contact_profile_name: str, subscription_id: str, **kwargs: Any +def build_list_request( + resource_group_name: str, subscription_id: str, *, skiptoken: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles", + ) 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), - "contactProfileName": _SERIALIZER.url("contact_profile_name", contact_profile_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skiptoken is not None: + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_request( +def build_get_request( resource_group_name: str, contact_profile_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: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}", - ) # 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), "contactProfileName": _SERIALIZER.url("contact_profile_name", contact_profile_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -142,16 +134,16 @@ def build_delete_request( # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_update_tags_request( +def build_create_or_update_request( resource_group_name: str, contact_profile_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: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -159,16 +151,16 @@ def build_update_tags_request( _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}", - ) # 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), "contactProfileName": _SERIALIZER.url("contact_profile_name", contact_profile_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -178,69 +170,76 @@ def build_update_tags_request( _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) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_by_subscription_request( - subscription_id: str, *, skiptoken: Optional[str] = None, **kwargs: Any +def build_update_tags_request( + resource_group_name: str, contact_profile_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: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Orbital/contactProfiles") + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}", + ) 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 + ), + "contactProfileName": _SERIALIZER.url("contact_profile_name", contact_profile_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if skiptoken is not None: - _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_request( - resource_group_name: str, subscription_id: str, *, skiptoken: Optional[str] = None, **kwargs: Any +def build_delete_request( + resource_group_name: str, contact_profile_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: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}", + ) 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), + "contactProfileName": _SERIALIZER.url("contact_profile_name", contact_profile_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if skiptoken is not None: - _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) class ContactProfilesOperations: @@ -257,10 +256,182 @@ class ContactProfilesOperations: 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") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureOrbitalConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_subscription( + self, skiptoken: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.ContactProfile"]: + """Returns list of contact profiles by Subscription. + + :param skiptoken: An opaque string that the resource provider uses to skip over + previously-returned results. This is used when a previous list operation call returned a + partial result. If a previous response contains a nextLink element, the value of the nextLink + element will include a skiptoken parameter that specifies a starting point to use for + subsequent calls. Default value is None. + :type skiptoken: str + :return: An iterator like instance of either ContactProfile or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.orbital.models.ContactProfile] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ContactProfileListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_subscription_request( + subscription_id=self._config.subscription_id, + skiptoken=skiptoken, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ContactProfileListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list( + self, resource_group_name: str, skiptoken: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.ContactProfile"]: + """Returns list of contact profiles by Resource Group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param skiptoken: An opaque string that the resource provider uses to skip over + previously-returned results. This is used when a previous list operation call returned a + partial result. If a previous response contains a nextLink element, the value of the nextLink + element will include a skiptoken parameter that specifies a starting point to use for + subsequent calls. Default value is None. + :type skiptoken: str + :return: An iterator like instance of either ContactProfile or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.orbital.models.ContactProfile] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ContactProfileListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + skiptoken=skiptoken, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ContactProfileListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) @distributed_trace def get(self, resource_group_name: str, contact_profile_name: str, **kwargs: Any) -> _models.ContactProfile: @@ -271,12 +442,11 @@ def get(self, resource_group_name: str, contact_profile_name: str, **kwargs: Any :type resource_group_name: str :param contact_profile_name: Contact Profile name. Required. :type contact_profile_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ContactProfile or the result of cls(response) :rtype: ~azure.mgmt.orbital.models.ContactProfile :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -287,25 +457,22 @@ def get(self, resource_group_name: str, contact_profile_name: str, **kwargs: Any _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ContactProfile] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, contact_profile_name=contact_profile_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -315,34 +482,21 @@ def get(self, resource_group_name: str, contact_profile_name: str, **kwargs: Any error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ContactProfile", pipeline_response) + deserialized = self._deserialize("ContactProfile", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}" - } + return deserialized # type: ignore def _create_or_update_initial( self, resource_group_name: str, contact_profile_name: str, - location: str, - network_configuration: _models.ContactProfilesPropertiesNetworkConfiguration, - links: List[_models.ContactProfileLink], - tags: Optional[Dict[str, str]] = None, - provisioning_state: Optional[Union[str, _models.ContactProfilesPropertiesProvisioningState]] = None, - minimum_viable_contact_duration: Optional[str] = None, - minimum_elevation_degrees: Optional[float] = None, - auto_tracking_configuration: Optional[Union[str, _models.AutoTrackingConfiguration]] = None, - event_hub_uri: Optional[str] = None, - third_party_configurations: Optional[List[_models.ContactProfileThirdPartyConfiguration]] = None, + parameters: Union[_models.ContactProfile, IO[bytes]], **kwargs: Any - ) -> _models.ContactProfile: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -353,86 +507,70 @@ def _create_or_update_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) - cls: ClsType[_models.ContactProfile] = kwargs.pop("cls", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - _parameters = _models.ContactProfile( - auto_tracking_configuration=auto_tracking_configuration, - event_hub_uri=event_hub_uri, - links=links, - location=location, - minimum_elevation_degrees=minimum_elevation_degrees, - minimum_viable_contact_duration=minimum_viable_contact_duration, - network_configuration=network_configuration, - provisioning_state=provisioning_state, - tags=tags, - third_party_configurations=third_party_configurations, - ) - _json = self._serialize.body(_parameters, "ContactProfile") + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ContactProfile") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, contact_profile_name=contact_profile_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, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("ContactProfile", pipeline_response) - if response.status_code == 201: response_headers["Azure-AsyncOperation"] = self._deserialize( "str", response.headers.get("Azure-AsyncOperation") ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - deserialized = self._deserialize("ContactProfile", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}" - } - - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, contact_profile_name: str, - location: str, - network_configuration: _models.ContactProfilesPropertiesNetworkConfiguration, - links: List[_models.ContactProfileLink], - tags: Optional[Dict[str, str]] = None, - provisioning_state: Optional[Union[str, _models.ContactProfilesPropertiesProvisioningState]] = None, - minimum_viable_contact_duration: Optional[str] = None, - minimum_elevation_degrees: Optional[float] = None, - auto_tracking_configuration: Optional[Union[str, _models.AutoTrackingConfiguration]] = None, - event_hub_uri: Optional[str] = None, - third_party_configurations: Optional[List[_models.ContactProfileThirdPartyConfiguration]] = None, + parameters: _models.ContactProfile, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.ContactProfile]: """Creates or updates a contact profile. @@ -442,243 +580,125 @@ def begin_create_or_update( :type resource_group_name: str :param contact_profile_name: Contact Profile name. Required. :type contact_profile_name: str - :param location: The geo-location where the resource lives. Required. - :type location: str - :param network_configuration: Network configuration of customer virtual network. Required. - :type network_configuration: - ~azure.mgmt.orbital.models.ContactProfilesPropertiesNetworkConfiguration - :param links: Links of the Contact Profile. Describes RF links, modem processing, and IP - endpoints. Required. - :type links: list[~azure.mgmt.orbital.models.ContactProfileLink] - :param tags: Resource tags. Default value is None. - :type tags: dict[str, str] - :param provisioning_state: The current state of the resource's creation, deletion, or - modification. Known values are: "creating", "succeeded", "failed", "canceled", "updating", and - "deleting". Default value is None. - :type provisioning_state: str or - ~azure.mgmt.orbital.models.ContactProfilesPropertiesProvisioningState - :param minimum_viable_contact_duration: Minimum viable contact duration in ISO 8601 format. - Used for listing the available contacts with a spacecraft at a given ground station. Default - value is None. - :type minimum_viable_contact_duration: str - :param minimum_elevation_degrees: Minimum viable elevation for the contact in decimal degrees. - Used for listing the available contacts with a spacecraft at a given ground station. Default - value is None. - :type minimum_elevation_degrees: float - :param auto_tracking_configuration: Auto-tracking configuration. Known values are: "disabled", - "xBand", and "sBand". Default value is None. - :type auto_tracking_configuration: str or ~azure.mgmt.orbital.models.AutoTrackingConfiguration - :param event_hub_uri: ARM resource identifier of the Event Hub used for telemetry. Requires - granting Orbital Resource Provider the rights to send telemetry into the hub. Default value is - None. - :type event_hub_uri: str - :param third_party_configurations: Third-party mission configuration of the Contact Profile. - Describes RF links, modem processing, and IP endpoints. Default value is None. - :type third_party_configurations: - list[~azure.mgmt.orbital.models.ContactProfileThirdPartyConfiguration] - :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. + :param parameters: The parameters to provide for the created Contact Profile. Required. + :type parameters: ~azure.mgmt.orbital.models.ContactProfile + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :return: An instance of LROPoller that returns either ContactProfile or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.ContactProfile] :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) - cls: ClsType[_models.ContactProfile] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_or_update_initial( - resource_group_name=resource_group_name, - contact_profile_name=contact_profile_name, - location=location, - network_configuration=network_configuration, - links=links, - tags=tags, - provisioning_state=provisioning_state, - minimum_viable_contact_duration=minimum_viable_contact_duration, - minimum_elevation_degrees=minimum_elevation_degrees, - auto_tracking_configuration=auto_tracking_configuration, - event_hub_uri=event_hub_uri, - third_party_configurations=third_party_configurations, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ContactProfile", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) - ) - 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, - ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}" - } - - def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, contact_profile_name: str, **kwargs: Any - ) -> None: - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - cls: ClsType[None] = kwargs.pop("cls", None) - - request = build_delete_request( - resource_group_name=resource_group_name, - contact_profile_name=contact_profile_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self._delete_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - 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) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - if cls: - return cls(pipeline_response, None, response_headers) + @overload + def begin_create_or_update( + self, + resource_group_name: str, + contact_profile_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ContactProfile]: + """Creates or updates a contact profile. - _delete_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}" - } + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param contact_profile_name: Contact Profile name. Required. + :type contact_profile_name: str + :param parameters: The parameters to provide for the created Contact Profile. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either ContactProfile or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.ContactProfile] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def begin_delete(self, resource_group_name: str, contact_profile_name: str, **kwargs: Any) -> LROPoller[None]: - """Deletes a specified contact profile resource. + def begin_create_or_update( + self, + resource_group_name: str, + contact_profile_name: str, + parameters: Union[_models.ContactProfile, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ContactProfile]: + """Creates or updates a contact profile. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str :param contact_profile_name: Contact Profile name. Required. :type contact_profile_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] + :param parameters: The parameters to provide for the created Contact Profile. Is either a + ContactProfile type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.orbital.models.ContactProfile or IO[bytes] + :return: An instance of LROPoller that returns either ContactProfile or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.ContactProfile] :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ContactProfile] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( # type: ignore + raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, contact_profile_name=contact_profile_name, + parameters=parameters, api_version=api_version, + content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ContactProfile", pipeline_response.http_response) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized if polling is True: polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.ContactProfile].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}" - } + return LROPoller[_models.ContactProfile]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _update_tags_initial( self, resource_group_name: str, contact_profile_name: str, - parameters: Union[_models.TagsObject, IO], + parameters: Union[_models.TagsObject, IO[bytes]], **kwargs: Any - ) -> Optional[_models.ContactProfile]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -689,21 +709,19 @@ def _update_tags_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.ContactProfile]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TagsObject") - request = build_update_tags_request( + _request = build_update_tags_request( resource_group_name=resource_group_name, contact_profile_name=contact_profile_name, subscription_id=self._config.subscription_id, @@ -711,40 +729,39 @@ def _update_tags_initial( content_type=content_type, json=_json, content=_content, - template_url=self._update_tags_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) + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("ContactProfile", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _update_tags_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}" - } + return deserialized # type: ignore @overload def begin_update_tags( @@ -768,14 +785,6 @@ def begin_update_tags( :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 ContactProfile or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.ContactProfile] @@ -787,7 +796,7 @@ def begin_update_tags( self, resource_group_name: str, contact_profile_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -800,18 +809,10 @@ def begin_update_tags( :param contact_profile_name: Contact Profile name. Required. :type contact_profile_name: str :param parameters: Parameters supplied to update contact profile tags. Required. - :type parameters: IO + :type parameters: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either ContactProfile or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.ContactProfile] @@ -823,7 +824,7 @@ def begin_update_tags( self, resource_group_name: str, contact_profile_name: str, - parameters: Union[_models.TagsObject, IO], + parameters: Union[_models.TagsObject, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.ContactProfile]: """Updates the specified contact profile tags. @@ -834,19 +835,8 @@ def begin_update_tags( :param contact_profile_name: Contact Profile name. Required. :type contact_profile_name: str :param parameters: Parameters supplied to update contact profile tags. Is either a TagsObject - type or a IO type. Required. - :type parameters: ~azure.mgmt.orbital.models.TagsObject or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.orbital.models.TagsObject or IO[bytes] :return: An instance of LROPoller that returns either ContactProfile or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.ContactProfile] @@ -855,9 +845,7 @@ def begin_update_tags( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ContactProfile] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -875,12 +863,13 @@ def begin_update_tags( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ContactProfile", pipeline_response) + deserialized = self._deserialize("ContactProfile", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -892,44 +881,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.ContactProfile].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_update_tags.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles/{contactProfileName}" - } - - @distributed_trace - def list_by_subscription( - self, skiptoken: Optional[str] = None, **kwargs: Any - ) -> Iterable["_models.ContactProfile"]: - """Returns list of contact profiles by Subscription. - - :param skiptoken: An opaque string that the resource provider uses to skip over - previously-returned results. This is used when a previous list operation call returned a - partial result. If a previous response contains a nextLink element, the value of the nextLink - element will include a skiptoken parameter that specifies a starting point to use for - subsequent calls. Default value is None. - :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ContactProfile or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.orbital.models.ContactProfile] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) + return LROPoller[_models.ContactProfile]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore ) - cls: ClsType[_models.ContactProfileListResult] = kwargs.pop("cls", None) - error_map = { + def _delete_initial(self, resource_group_name: str, contact_profile_name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -937,159 +900,102 @@ def list_by_subscription( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - request = build_list_by_subscription_request( - subscription_id=self._config.subscription_id, - skiptoken=skiptoken, - 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) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = build_delete_request( + resource_group_name=resource_group_name, + contact_profile_name=contact_profile_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) - def extract_data(pipeline_response): - deserialized = self._deserialize("ContactProfileListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - def get_next(next_link=None): - request = prepare_request(next_link) + response = pipeline_response.http_response - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs - ) - response = pipeline_response.http_response + if response.status_code not in [200, 202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - return pipeline_response + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return ItemPaged(get_next, extract_data) + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Orbital/contactProfiles" - } + return deserialized # type: ignore @distributed_trace - def list( - self, resource_group_name: str, skiptoken: Optional[str] = None, **kwargs: Any - ) -> Iterable["_models.ContactProfile"]: - """Returns list of contact profiles by Resource Group. + def begin_delete(self, resource_group_name: str, contact_profile_name: str, **kwargs: Any) -> LROPoller[None]: + """Deletes a specified contact profile resource. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param skiptoken: An opaque string that the resource provider uses to skip over - previously-returned results. This is used when a previous list operation call returned a - partial result. If a previous response contains a nextLink element, the value of the nextLink - element will include a skiptoken parameter that specifies a starting point to use for - subsequent calls. Default value is None. - :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ContactProfile or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.orbital.models.ContactProfile] + :param contact_profile_name: Contact Profile name. Required. + :type contact_profile_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - cls: ClsType[_models.ContactProfileListResult] = kwargs.pop("cls", None) - - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - request = build_list_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - skiptoken=skiptoken, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + contact_profile_name=contact_profile_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) - def extract_data(pipeline_response): - deserialized = self._deserialize("ContactProfileListResult", pipeline_response) - list_of_elem = deserialized.value + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - request = prepare_request(next_link) + return cls(pipeline_response, None, {}) # type: ignore - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/contactProfiles" - } + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_contacts_operations.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_contacts_operations.py index 63ef65e83a99..0747b8be505c 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_contacts_operations.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_contacts_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,36 +6,35 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +from .._configuration import AzureOrbitalConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -54,23 +53,23 @@ def build_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts", - ) # 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), "spacecraftName": _SERIALIZER.url("spacecraft_name", spacecraft_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -89,24 +88,24 @@ def build_get_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts/{contactName}", - ) # 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), "spacecraftName": _SERIALIZER.url("spacecraft_name", spacecraft_name, "str"), "contactName": _SERIALIZER.url("contact_name", contact_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -123,7 +122,7 @@ def build_create_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -131,17 +130,17 @@ def build_create_request( _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts/{contactName}", - ) # 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), "spacecraftName": _SERIALIZER.url("spacecraft_name", spacecraft_name, "str"), "contactName": _SERIALIZER.url("contact_name", contact_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -160,24 +159,24 @@ def build_delete_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts/{contactName}", - ) # 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), "spacecraftName": _SERIALIZER.url("spacecraft_name", spacecraft_name, "str"), "contactName": _SERIALIZER.url("contact_name", contact_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -202,10 +201,10 @@ class ContactsOperations: 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") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureOrbitalConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( @@ -224,7 +223,6 @@ def list( element will include a skiptoken parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Contact or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.orbital.models.Contact] :raises ~azure.core.exceptions.HttpResponseError: @@ -232,12 +230,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.ContactListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -248,18 +244,16 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, subscription_id=self._config.subscription_id, skiptoken=skiptoken, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -271,13 +265,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ContactListResult", pipeline_response) @@ -287,10 +280,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -303,10 +297,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts" - } - @distributed_trace def get(self, resource_group_name: str, spacecraft_name: str, contact_name: str, **kwargs: Any) -> _models.Contact: """Gets the specified contact in a specified resource group. @@ -318,12 +308,11 @@ def get(self, resource_group_name: str, spacecraft_name: str, contact_name: str, :type spacecraft_name: str :param contact_name: Contact name. Required. :type contact_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Contact or the result of cls(response) :rtype: ~azure.mgmt.orbital.models.Contact :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -334,26 +323,23 @@ def get(self, resource_group_name: str, spacecraft_name: str, contact_name: str, _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Contact] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, contact_name=contact_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -363,26 +349,22 @@ def get(self, resource_group_name: str, spacecraft_name: str, contact_name: str, error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Contact", pipeline_response) + deserialized = self._deserialize("Contact", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts/{contactName}" - } + return deserialized # type: ignore def _create_initial( self, resource_group_name: str, spacecraft_name: str, contact_name: str, - parameters: Union[_models.Contact, IO], + parameters: Union[_models.Contact, IO[bytes]], **kwargs: Any - ) -> _models.Contact: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -393,21 +375,19 @@ def _create_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Contact] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "Contact") - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, contact_name=contact_name, @@ -416,44 +396,42 @@ def _create_initial( content_type=content_type, json=_json, content=_content, - template_url=self._create_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("Contact", pipeline_response) - if response.status_code == 201: response_headers["Azure-AsyncOperation"] = self._deserialize( "str", response.headers.get("Azure-AsyncOperation") ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - deserialized = self._deserialize("Contact", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore - _create_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts/{contactName}" - } - @overload def begin_create( self, @@ -479,14 +457,6 @@ def begin_create( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either Contact or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.Contact] :raises ~azure.core.exceptions.HttpResponseError: @@ -498,7 +468,7 @@ def begin_create( resource_group_name: str, spacecraft_name: str, contact_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -513,18 +483,10 @@ def begin_create( :param contact_name: Contact name. Required. :type contact_name: str :param parameters: The parameters to provide for the created contact. Required. - :type parameters: IO + :type parameters: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either Contact or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.Contact] :raises ~azure.core.exceptions.HttpResponseError: @@ -536,7 +498,7 @@ def begin_create( resource_group_name: str, spacecraft_name: str, contact_name: str, - parameters: Union[_models.Contact, IO], + parameters: Union[_models.Contact, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.Contact]: """Creates a contact. @@ -549,19 +511,8 @@ def begin_create( :param contact_name: Contact name. Required. :type contact_name: str :param parameters: The parameters to provide for the created contact. Is either a Contact type - or a IO type. Required. - :type parameters: ~azure.mgmt.orbital.models.Contact 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. + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.orbital.models.Contact or IO[bytes] :return: An instance of LROPoller that returns either Contact or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.Contact] :raises ~azure.core.exceptions.HttpResponseError: @@ -569,9 +520,7 @@ def begin_create( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Contact] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -590,12 +539,13 @@ def begin_create( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Contact", pipeline_response) + deserialized = self._deserialize("Contact", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -607,22 +557,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.Contact].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts/{contactName}" - } + return LROPoller[_models.Contact]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - def _delete_initial( # pylint: disable=inconsistent-return-statements + def _delete_initial( self, resource_group_name: str, spacecraft_name: str, contact_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -633,31 +581,33 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, contact_name=contact_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) @@ -665,13 +615,14 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements response_headers = {} if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _delete_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts/{contactName}" - } + return deserialized # type: ignore @distributed_trace def begin_delete( @@ -686,14 +637,6 @@ def begin_delete( :type spacecraft_name: str :param contact_name: Contact name. Required. :type contact_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -701,15 +644,13 @@ def begin_delete( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( # type: ignore + raw_result = self._delete_initial( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, contact_name=contact_name, @@ -719,11 +660,12 @@ def begin_delete( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: PollingMethod = cast( @@ -734,14 +676,10 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/contacts/{contactName}" - } + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_operations.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_operations.py index 67d358fb2f19..abca6b89f0d3 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_operations.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys +from collections.abc import MutableMapping from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -20,20 +20,15 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request +from .._configuration import AzureOrbitalConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -45,7 +40,7 @@ def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -74,16 +69,15 @@ class Operations: 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") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureOrbitalConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: - """Lists all of the available Orbital Rest API operations. + """List the operations for the provider. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.orbital.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: @@ -91,12 +85,10 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -107,14 +99,12 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -126,26 +116,26 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -157,5 +147,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.Orbital/operations"} diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_operations_results_operations.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_operations_results_operations.py index 38d188c3e9ff..49e096cc1e63 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_operations_results_operations.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_operations_results_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +6,10 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast +from collections.abc import MutableMapping +from typing import Any, Callable, Dict, Optional, TypeVar +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -18,22 +19,15 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +from .._configuration import AzureOrbitalConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -45,21 +39,21 @@ def build_get_request(location: str, operation_id: str, subscription_id: str, ** _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Orbital/locations/{location}/operationResults/{operationId}", - ) # 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", min_length=1), "operationId": _SERIALIZER.url("operation_id", operation_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -84,13 +78,24 @@ class OperationsResultsOperations: 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") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureOrbitalConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def _get_initial(self, location: str, operation_id: str, **kwargs: Any) -> Optional[_models.OperationResult]: - error_map = { + @distributed_trace + def get(self, location: str, operation_id: str, **kwargs: Any) -> Optional[_models.OperationResult]: + """Returns operation results. + + :param location: The name of Azure region. Required. + :type location: str + :param operation_id: The ID of an ongoing async operation. Required. + :type operation_id: str + :return: OperationResult or None or the result of cls(response) + :rtype: ~azure.mgmt.orbital.models.OperationResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -101,25 +106,22 @@ def _get_initial(self, location: str, operation_id: str, **kwargs: Any) -> Optio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[Optional[_models.OperationResult]] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( location=location, operation_id=operation_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._get_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -132,86 +134,14 @@ def _get_initial(self, location: str, operation_id: str, **kwargs: Any) -> Optio deserialized = None response_headers = {} if response.status_code == 200: - deserialized = self._deserialize("OperationResult", pipeline_response) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = self._deserialize("OperationResult", pipeline_response.http_response) if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized - - _get_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Orbital/locations/{location}/operationResults/{operationId}" - } + return cls(pipeline_response, deserialized, response_headers) # type: ignore - @distributed_trace - def begin_get(self, location: str, operation_id: str, **kwargs: Any) -> LROPoller[_models.OperationResult]: - """Returns operation results. - - :param location: The name of Azure region. Required. - :type location: str - :param operation_id: The ID of an ongoing async operation. Required. - :type operation_id: 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 OperationResult or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.OperationResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - cls: ClsType[_models.OperationResult] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._get_initial( - location=location, - operation_id=operation_id, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("OperationResult", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_get.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Orbital/locations/{location}/operationResults/{operationId}" - } + return deserialized # type: ignore diff --git a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_spacecrafts_operations.py b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_spacecrafts_operations.py index 1cb7f59a70e4..6ca8230111d7 100644 --- a/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_spacecrafts_operations.py +++ b/sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/operations/_spacecrafts_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,37 +6,35 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime -import sys -from typing import Any, Callable, Dict, IO, Iterable, List, Optional, TypeVar, Union, cast, overload +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +from .._configuration import AzureOrbitalConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -50,7 +48,7 @@ def build_list_by_subscription_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -59,7 +57,7 @@ def build_list_by_subscription_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -78,22 +76,22 @@ def build_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts", - ) # 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), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -112,23 +110,23 @@ def build_get_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}", - ) # 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), "spacecraftName": _SERIALIZER.url("spacecraft_name", spacecraft_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -145,7 +143,7 @@ def build_create_or_update_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -153,16 +151,16 @@ def build_create_or_update_request( _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}", - ) # 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), "spacecraftName": _SERIALIZER.url("spacecraft_name", spacecraft_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -175,73 +173,73 @@ def build_create_or_update_request( return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_request( +def build_update_tags_request( resource_group_name: str, spacecraft_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: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}", - ) # 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), "spacecraftName": _SERIALIZER.url("spacecraft_name", spacecraft_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_update_tags_request( +def build_delete_request( resource_group_name: str, spacecraft_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: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}", - ) # 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), "spacecraftName": _SERIALIZER.url("spacecraft_name", spacecraft_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_list_available_contacts_request( @@ -250,7 +248,7 @@ def build_list_available_contacts_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -258,16 +256,16 @@ def build_list_available_contacts_request( _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/listAvailableContacts", - ) # 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), "spacecraftName": _SERIALIZER.url("spacecraft_name", spacecraft_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -294,10 +292,10 @@ class SpacecraftsOperations: 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") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AzureOrbitalConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_subscription(self, skiptoken: Optional[str] = None, **kwargs: Any) -> Iterable["_models.Spacecraft"]: @@ -309,7 +307,6 @@ def list_by_subscription(self, skiptoken: Optional[str] = None, **kwargs: Any) - element will include a skiptoken parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Spacecraft or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.orbital.models.Spacecraft] :raises ~azure.core.exceptions.HttpResponseError: @@ -317,12 +314,10 @@ def list_by_subscription(self, skiptoken: Optional[str] = None, **kwargs: Any) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.SpacecraftListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -333,16 +328,14 @@ def list_by_subscription(self, skiptoken: Optional[str] = None, **kwargs: Any) - def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, skiptoken=skiptoken, 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) else: # make call to next link with the client's api-version @@ -354,13 +347,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("SpacecraftListResult", pipeline_response) @@ -370,10 +362,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -386,8 +379,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Orbital/spacecrafts"} - @distributed_trace def list( self, resource_group_name: str, skiptoken: Optional[str] = None, **kwargs: Any @@ -403,7 +394,6 @@ def list( element will include a skiptoken parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Spacecraft or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.orbital.models.Spacecraft] :raises ~azure.core.exceptions.HttpResponseError: @@ -411,12 +401,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.SpacecraftListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -427,17 +415,15 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, skiptoken=skiptoken, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -449,13 +435,12 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("SpacecraftListResult", pipeline_response) @@ -465,10 +450,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -481,10 +467,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts" - } - @distributed_trace def get(self, resource_group_name: str, spacecraft_name: str, **kwargs: Any) -> _models.Spacecraft: """Gets the specified spacecraft in a specified resource group. @@ -494,12 +476,11 @@ def get(self, resource_group_name: str, spacecraft_name: str, **kwargs: Any) -> :type resource_group_name: str :param spacecraft_name: Spacecraft ID. Required. :type spacecraft_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Spacecraft or the result of cls(response) :rtype: ~azure.mgmt.orbital.models.Spacecraft :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -510,25 +491,22 @@ def get(self, resource_group_name: str, spacecraft_name: str, **kwargs: Any) -> _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) cls: ClsType[_models.Spacecraft] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -538,32 +516,21 @@ def get(self, resource_group_name: str, spacecraft_name: str, **kwargs: Any) -> error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Spacecraft", pipeline_response) + deserialized = self._deserialize("Spacecraft", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}" - } + return deserialized # type: ignore def _create_or_update_initial( self, resource_group_name: str, spacecraft_name: str, - location: str, - title_line: str, - tle_line1: str, - tle_line2: str, - links: List[_models.SpacecraftLink], - tags: Optional[Dict[str, str]] = None, - provisioning_state: Optional[Union[str, _models.SpacecraftsPropertiesProvisioningState]] = None, - norad_id: Optional[str] = None, + parameters: Union[_models.Spacecraft, IO[bytes]], **kwargs: Any - ) -> _models.Spacecraft: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -574,82 +541,70 @@ def _create_or_update_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) - cls: ClsType[_models.Spacecraft] = kwargs.pop("cls", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - _parameters = _models.Spacecraft( - links=links, - location=location, - norad_id=norad_id, - provisioning_state=provisioning_state, - tags=tags, - title_line=title_line, - tle_line1=tle_line1, - tle_line2=tle_line2, - ) - _json = self._serialize.body(_parameters, "Spacecraft") + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Spacecraft") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_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, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("Spacecraft", pipeline_response) - if response.status_code == 201: response_headers["Azure-AsyncOperation"] = self._deserialize( "str", response.headers.get("Azure-AsyncOperation") ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - deserialized = self._deserialize("Spacecraft", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}" - } - - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, spacecraft_name: str, - location: str, - title_line: str, - tle_line1: str, - tle_line2: str, - links: List[_models.SpacecraftLink], - tags: Optional[Dict[str, str]] = None, - provisioning_state: Optional[Union[str, _models.SpacecraftsPropertiesProvisioningState]] = None, - norad_id: Optional[str] = None, + parameters: _models.Spacecraft, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.Spacecraft]: """Creates or updates a spacecraft resource. @@ -659,221 +614,122 @@ def begin_create_or_update( :type resource_group_name: str :param spacecraft_name: Spacecraft ID. Required. :type spacecraft_name: str - :param location: The geo-location where the resource lives. Required. - :type location: str - :param title_line: Title line of the two-line element set (TLE). Required. - :type title_line: str - :param tle_line1: Line 1 of the two-line element set (TLE). Required. - :type tle_line1: str - :param tle_line2: Line 2 of the two-line element set (TLE). Required. - :type tle_line2: str - :param links: Immutable list of Spacecraft links. Required. - :type links: list[~azure.mgmt.orbital.models.SpacecraftLink] - :param tags: Resource tags. Default value is None. - :type tags: dict[str, str] - :param provisioning_state: The current state of the resource's creation, deletion, or - modification. Known values are: "creating", "succeeded", "failed", "canceled", "updating", and - "deleting". Default value is None. - :type provisioning_state: str or - ~azure.mgmt.orbital.models.SpacecraftsPropertiesProvisioningState - :param norad_id: NORAD ID of the spacecraft. Default value is None. - :type norad_id: 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. + :param parameters: The parameters to provide for the created spacecraft. Required. + :type parameters: ~azure.mgmt.orbital.models.Spacecraft + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :return: An instance of LROPoller that returns either Spacecraft or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.Spacecraft] :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) - cls: ClsType[_models.Spacecraft] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._create_or_update_initial( - resource_group_name=resource_group_name, - spacecraft_name=spacecraft_name, - location=location, - title_line=title_line, - tle_line1=tle_line1, - tle_line2=tle_line2, - links=links, - tags=tags, - provisioning_state=provisioning_state, - norad_id=norad_id, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Spacecraft", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) - ) - 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, - ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}" - } - - def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, spacecraft_name: str, **kwargs: Any - ) -> None: - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - cls: ClsType[None] = kwargs.pop("cls", None) - - request = build_delete_request( - resource_group_name=resource_group_name, - spacecraft_name=spacecraft_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self._delete_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - 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) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - if cls: - return cls(pipeline_response, None, response_headers) + @overload + def begin_create_or_update( + self, + resource_group_name: str, + spacecraft_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Spacecraft]: + """Creates or updates a spacecraft resource. - _delete_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}" - } + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param spacecraft_name: Spacecraft ID. Required. + :type spacecraft_name: str + :param parameters: The parameters to provide for the created spacecraft. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either Spacecraft or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.Spacecraft] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def begin_delete(self, resource_group_name: str, spacecraft_name: str, **kwargs: Any) -> LROPoller[None]: - """Deletes a specified spacecraft resource. + def begin_create_or_update( + self, + resource_group_name: str, + spacecraft_name: str, + parameters: Union[_models.Spacecraft, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.Spacecraft]: + """Creates or updates a spacecraft resource. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str :param spacecraft_name: Spacecraft ID. Required. :type spacecraft_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] + :param parameters: The parameters to provide for the created spacecraft. Is either a Spacecraft + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.orbital.models.Spacecraft or IO[bytes] + :return: An instance of LROPoller that returns either Spacecraft or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.Spacecraft] :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Spacecraft] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( # type: ignore + raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, + parameters=parameters, api_version=api_version, + content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Spacecraft", pipeline_response.http_response) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized if polling is True: polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.Spacecraft].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}" - } + return LROPoller[_models.Spacecraft]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _update_tags_initial( - self, resource_group_name: str, spacecraft_name: str, parameters: Union[_models.TagsObject, IO], **kwargs: Any - ) -> Optional[_models.Spacecraft]: - error_map = { + self, + resource_group_name: str, + spacecraft_name: str, + parameters: Union[_models.TagsObject, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -884,21 +740,19 @@ def _update_tags_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.Spacecraft]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "TagsObject") - request = build_update_tags_request( + _request = build_update_tags_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, subscription_id=self._config.subscription_id, @@ -906,40 +760,39 @@ def _update_tags_initial( content_type=content_type, json=_json, content=_content, - template_url=self._update_tags_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) + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("Spacecraft", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _update_tags_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}" - } + return deserialized # type: ignore @overload def begin_update_tags( @@ -963,14 +816,6 @@ def begin_update_tags( :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 Spacecraft or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.Spacecraft] :raises ~azure.core.exceptions.HttpResponseError: @@ -981,7 +826,7 @@ def begin_update_tags( self, resource_group_name: str, spacecraft_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -994,18 +839,10 @@ def begin_update_tags( :param spacecraft_name: Spacecraft ID. Required. :type spacecraft_name: str :param parameters: Parameters supplied to update spacecraft tags. Required. - :type parameters: IO + :type parameters: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either Spacecraft or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.Spacecraft] :raises ~azure.core.exceptions.HttpResponseError: @@ -1013,7 +850,11 @@ def begin_update_tags( @distributed_trace def begin_update_tags( - self, resource_group_name: str, spacecraft_name: str, parameters: Union[_models.TagsObject, IO], **kwargs: Any + self, + resource_group_name: str, + spacecraft_name: str, + parameters: Union[_models.TagsObject, IO[bytes]], + **kwargs: Any ) -> LROPoller[_models.Spacecraft]: """Updates the specified spacecraft tags. @@ -1023,19 +864,8 @@ def begin_update_tags( :param spacecraft_name: Spacecraft ID. Required. :type spacecraft_name: str :param parameters: Parameters supplied to update spacecraft tags. Is either a TagsObject type - or a IO type. Required. - :type parameters: ~azure.mgmt.orbital.models.TagsObject 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. + or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.orbital.models.TagsObject or IO[bytes] :return: An instance of LROPoller that returns either Spacecraft or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.orbital.models.Spacecraft] :raises ~azure.core.exceptions.HttpResponseError: @@ -1043,9 +873,7 @@ def begin_update_tags( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Spacecraft] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -1063,12 +891,13 @@ def begin_update_tags( params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("Spacecraft", pipeline_response) + deserialized = self._deserialize("Spacecraft", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -1080,29 +909,133 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.Spacecraft].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return LROPoller[_models.Spacecraft]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - begin_update_tags.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}" - } + def _delete_initial(self, resource_group_name: str, spacecraft_name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + spacecraft_name=spacecraft_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_delete(self, resource_group_name: str, spacecraft_name: str, **kwargs: Any) -> LROPoller[None]: + """Deletes a specified spacecraft resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param spacecraft_name: Spacecraft ID. Required. + :type spacecraft_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + spacecraft_name=spacecraft_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore def _list_available_contacts_initial( self, resource_group_name: str, spacecraft_name: str, - contact_profile: _models.ContactParametersContactProfile, - ground_station_name: str, - start_time: datetime.datetime, - end_time: datetime.datetime, + parameters: Union[_models.ContactParameters, IO[bytes]], **kwargs: Any - ) -> Optional[_models.AvailableContactsListResult]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1113,71 +1046,128 @@ def _list_available_contacts_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) - cls: ClsType[Optional[_models.AvailableContactsListResult]] = kwargs.pop("cls", None) - - _parameters = _models.ContactParameters( - contact_profile=contact_profile, - end_time=end_time, - ground_station_name=ground_station_name, - start_time=start_time, - ) - _json = self._serialize.body(_parameters, "ContactParameters") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ContactParameters") - request = build_list_available_contacts_request( + _request = build_list_available_contacts_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._list_available_contacts_initial.metadata["url"], + content=_content, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("AvailableContactsListResult", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore - _list_available_contacts_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/listAvailableContacts" - } + @overload + def begin_list_available_contacts( + self, + resource_group_name: str, + spacecraft_name: str, + parameters: _models.ContactParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[Iterable["_models.AvailableContacts"]]: + """Returns list of available contacts. A contact is available if the spacecraft is visible from + the ground station for more than the minimum viable contact duration provided in the contact + profile. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param spacecraft_name: Spacecraft ID. Required. + :type spacecraft_name: str + :param parameters: The parameters to provide for the contacts. Required. + :type parameters: ~azure.mgmt.orbital.models.ContactParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns an iterator like instance of either + AvailableContactsListResult or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.core.paging.ItemPaged[~azure.mgmt.orbital.models.AvailableContacts]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_list_available_contacts( + self, + resource_group_name: str, + spacecraft_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[Iterable["_models.AvailableContacts"]]: + """Returns list of available contacts. A contact is available if the spacecraft is visible from + the ground station for more than the minimum viable contact duration provided in the contact + profile. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param spacecraft_name: Spacecraft ID. Required. + :type spacecraft_name: str + :param parameters: The parameters to provide for the contacts. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns an iterator like instance of either + AvailableContactsListResult or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.core.paging.ItemPaged[~azure.mgmt.orbital.models.AvailableContacts]] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_list_available_contacts( self, resource_group_name: str, spacecraft_name: str, - contact_profile: _models.ContactParametersContactProfile, - ground_station_name: str, - start_time: datetime.datetime, - end_time: datetime.datetime, + parameters: Union[_models.ContactParameters, IO[bytes]], **kwargs: Any ) -> LROPoller[Iterable["_models.AvailableContacts"]]: """Returns list of available contacts. A contact is available if the spacecraft is visible from @@ -1189,22 +1179,9 @@ def begin_list_available_contacts( :type resource_group_name: str :param spacecraft_name: Spacecraft ID. Required. :type spacecraft_name: str - :param contact_profile: The reference to the contact profile resource. Required. - :type contact_profile: ~azure.mgmt.orbital.models.ContactParametersContactProfile - :param ground_station_name: Name of Azure Ground Station. Required. - :type ground_station_name: str - :param start_time: Start time of a contact (ISO 8601 UTC standard). Required. - :type start_time: ~datetime.datetime - :param end_time: End time of a contact (ISO 8601 UTC standard). Required. - :type end_time: ~datetime.datetime - :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. + :param parameters: The parameters to provide for the contacts. Is either a ContactParameters + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.orbital.models.ContactParameters or IO[bytes] :return: An instance of LROPoller that returns an iterator like instance of either AvailableContactsListResult or the result of cls(response) :rtype: @@ -1215,43 +1192,40 @@ def begin_list_available_contacts( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-11-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AvailableContactsListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ContactParameters") def prepare_request(next_link=None): if not next_link: - _parameters = _models.ContactParameters( - contact_profile=contact_profile, - end_time=end_time, - ground_station_name=ground_station_name, - start_time=start_time, - ) - _json = self._serialize.body(_parameters, "ContactParameters") - request = build_list_available_contacts_request( + _request = build_list_available_contacts_request( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.begin_list_available_contacts.metadata["url"], + content=_content, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1263,26 +1237,26 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): - deserialized = self._deserialize("AvailableContactsListResult", pipeline_response) + deserialized = self._deserialize("AvailableContactsListResult", pipeline_response.http_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1300,10 +1274,7 @@ def get_next(next_link=None): raw_result = self._list_available_contacts_initial( resource_group_name=resource_group_name, spacecraft_name=spacecraft_name, - contact_profile=contact_profile, - ground_station_name=ground_station_name, - start_time=start_time, - end_time=end_time, + parameters=parameters, api_version=api_version, content_type=content_type, cls=lambda x, y, z: x, @@ -1311,6 +1282,7 @@ def get_next(next_link=None): params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): @@ -1330,14 +1302,12 @@ def internal_get_next(next_link=None): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[Iterable["_models.AvailableContacts"]].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_list_available_contacts.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Orbital/spacecrafts/{spacecraftName}/listAvailableContacts" - } + return LROPoller[Iterable["_models.AvailableContacts"]]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/available_contacts_list.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/available_contacts_list.py new file mode 100644 index 000000000000..5d8700e15a9a --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/available_contacts_list.py @@ -0,0 +1,52 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.orbital import AzureOrbital + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-orbital +# USAGE + python available_contacts_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AzureOrbital( + credential=DefaultAzureCredential(), + subscription_id="c1be1141-a7c9-4aac-9608-3c2e2f1152c3", + ) + + response = client.spacecrafts.begin_list_available_contacts( + resource_group_name="contoso-Rgp", + spacecraft_name="CONTOSO_SAT", + parameters={ + "contactProfile": { + "id": "/subscriptions/c1be1141-a7c9-4aac-9608-3c2e2f1152c3/resourceGroups/contoso-Rgp/providers/Microsoft.Orbital/contactProfiles/CONTOSO-CP" + }, + "endTime": "2022-11-02T11:30:00Z", + "groundStationName": "EASTUS2_0", + "startTime": "2022-11-01T11:30:00Z", + }, + ).result() + for item in response: + print(item) + + +# x-ms-original-file: specification/orbital/resource-manager/Microsoft.Orbital/stable/2022-11-01/examples/AvailableContactsList.json +if __name__ == "__main__": + main() diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/available_ground_stations_by_capability_list.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/available_ground_stations_by_capability_list.py index 7acb538a9b8c..efbfdefd1673 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/available_ground_stations_by_capability_list.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/available_ground_stations_by_capability_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_create.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_create.py index 2f3b97fe5886..277f13f13248 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_create.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_create.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_delete.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_delete.py index 3b8c83573179..aaa1874b32a5 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_delete.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_delete.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ @@ -29,12 +31,11 @@ def main(): subscription_id="c1be1141-a7c9-4aac-9608-3c2e2f1152c3", ) - response = client.contacts.begin_delete( + client.contacts.begin_delete( resource_group_name="contoso-Rgp", spacecraft_name="CONTOSO_SAT", contact_name="contact1", ).result() - print(response) # x-ms-original-file: specification/orbital/resource-manager/Microsoft.Orbital/stable/2022-11-01/examples/ContactDelete.json diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_get.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_get.py index 9dedfd6c0fb5..e70d78e37191 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_get.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profile_create.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profile_create.py new file mode 100644 index 000000000000..5f91bb3eabc3 --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profile_create.py @@ -0,0 +1,101 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.orbital import AzureOrbital + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-orbital +# USAGE + python contact_profile_create.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AzureOrbital( + credential=DefaultAzureCredential(), + subscription_id="c1be1141-a7c9-4aac-9608-3c2e2f1152c3", + ) + + response = client.contact_profiles.begin_create_or_update( + resource_group_name="contoso-Rgp", + contact_profile_name="CONTOSO-CP", + parameters={ + "location": "eastus2", + "properties": { + "autoTrackingConfiguration": "disabled", + "eventHubUri": "/subscriptions/c1be1141-a7c9-4aac-9608-3c2e2f1152c3/resourceGroups/contoso-Rgp/providers/Microsoft.EventHub/namespaces/contosoHub/eventhubs/contosoHub", + "links": [ + { + "channels": [ + { + "bandwidthMHz": 2, + "centerFrequencyMHz": 2250, + "endPoint": { + "endPointName": "ContosoTest_Uplink", + "ipAddress": "10.1.0.4", + "port": "50000", + "protocol": "TCP", + }, + "name": "contoso-uplink-channel", + } + ], + "direction": "Uplink", + "eirpdBW": 45, + "gainOverTemperature": 0, + "name": "contoso-uplink", + "polarization": "LHCP", + }, + { + "channels": [ + { + "bandwidthMHz": 15, + "centerFrequencyMHz": 8160, + "endPoint": { + "endPointName": "ContosoTest_Downlink", + "ipAddress": "10.1.0.5", + "port": "50001", + "protocol": "UDP", + }, + "name": "contoso-downlink-channel", + } + ], + "direction": "Downlink", + "eirpdBW": 0, + "gainOverTemperature": 25, + "name": "contoso-downlink", + "polarization": "RHCP", + }, + ], + "minimumElevationDegrees": 5, + "minimumViableContactDuration": "PT1M", + "networkConfiguration": { + "subnetId": "/subscriptions/c1be1141-a7c9-4aac-9608-3c2e2f1152c3/resourceGroups/contoso-Rgp/providers/Microsoft.Network/virtualNetworks/contoso-vnet/subnets/orbital-delegated-subnet" + }, + "thirdPartyConfigurations": [ + {"missionConfiguration": "Ksat_MissionConfiguration", "providerName": "KSAT"}, + {"missionConfiguration": "Viasat_Configuration", "providerName": "VIASAT"}, + ], + }, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/orbital/resource-manager/Microsoft.Orbital/stable/2022-11-01/examples/ContactProfileCreate.json +if __name__ == "__main__": + main() diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profile_delete.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profile_delete.py index f3e2a8e4277b..09b679cbf600 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profile_delete.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profile_delete.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ @@ -29,11 +31,10 @@ def main(): subscription_id="c1be1141-a7c9-4aac-9608-3c2e2f1152c3", ) - response = client.contact_profiles.begin_delete( + client.contact_profiles.begin_delete( resource_group_name="contoso-Rgp", contact_profile_name="CONTOSO-CP", ).result() - print(response) # x-ms-original-file: specification/orbital/resource-manager/Microsoft.Orbital/stable/2022-11-01/examples/ContactProfileDelete.json diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profile_get.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profile_get.py index b64764fc0bd1..ca2b36ca65cd 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profile_get.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profile_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profile_update_tag.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profile_update_tag.py index 145b18d29dfe..be8501738ac2 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profile_update_tag.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profile_update_tag.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profiles_by_resource_group_list.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profiles_by_resource_group_list.py index a09a6967a021..4f38a691cac5 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profiles_by_resource_group_list.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profiles_by_resource_group_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profiles_by_subscription_list.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profiles_by_subscription_list.py index 1e5feb408255..f7012abb856b 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profiles_by_subscription_list.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/contact_profiles_by_subscription_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/contacts_by_spacecraft_name_list.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/contacts_by_spacecraft_name_list.py index c77ba1a48a5c..b487d2a74ddc 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/contacts_by_spacecraft_name_list.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/contacts_by_spacecraft_name_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/operation_results_get.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/operation_results_get.py index b61f310cc4ed..cc5f9d4e3f91 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/operation_results_get.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/operation_results_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ @@ -29,10 +31,10 @@ def main(): subscription_id="12345678-1234-1234-1234-123456789098", ) - response = client.operations_results.begin_get( + response = client.operations_results.get( location="eastus2", operation_id="30972f1b-b61d-4fd8-bd34-3dcfa24670f3", - ).result() + ) print(response) diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/operations_list.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/operations_list.py index ea6d1f32382d..96315178afae 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/operations_list.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/operations_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecraft_create.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecraft_create.py new file mode 100644 index 000000000000..0e79a1e65278 --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecraft_create.py @@ -0,0 +1,68 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.orbital import AzureOrbital + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-orbital +# USAGE + python spacecraft_create.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AzureOrbital( + credential=DefaultAzureCredential(), + subscription_id="c1be1141-a7c9-4aac-9608-3c2e2f1152c3", + ) + + response = client.spacecrafts.begin_create_or_update( + resource_group_name="contoso-Rgp", + spacecraft_name="CONTOSO_SAT", + parameters={ + "location": "eastus2", + "properties": { + "links": [ + { + "bandwidthMHz": 2, + "centerFrequencyMHz": 2250, + "direction": "Uplink", + "name": "uplink_lhcp1", + "polarization": "LHCP", + }, + { + "bandwidthMHz": 15, + "centerFrequencyMHz": 8160, + "direction": "Downlink", + "name": "downlink_rhcp1", + "polarization": "RHCP", + }, + ], + "noradId": "36411", + "titleLine": "CONTOSO_SAT", + "tleLine1": "1 27424U 02022A 22167.05119303 .00000638 00000+0 15103-3 0 9994", + "tleLine2": "2 27424 98.2477 108.9546 0000928 92.9194 327.0802 14.57300770 69982", + }, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/orbital/resource-manager/Microsoft.Orbital/stable/2022-11-01/examples/SpacecraftCreate.json +if __name__ == "__main__": + main() diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecraft_delete.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecraft_delete.py index 7d3383ef0774..3d25dc147e4d 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecraft_delete.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecraft_delete.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ @@ -29,11 +31,10 @@ def main(): subscription_id="c1be1141-a7c9-4aac-9608-3c2e2f1152c3", ) - response = client.spacecrafts.begin_delete( + client.spacecrafts.begin_delete( resource_group_name="contoso-Rgp", spacecraft_name="CONTOSO_SAT", ).result() - print(response) # x-ms-original-file: specification/orbital/resource-manager/Microsoft.Orbital/stable/2022-11-01/examples/SpacecraftDelete.json diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecraft_get.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecraft_get.py index 68416ed4676c..b1765183cf90 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecraft_get.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecraft_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecraft_update_tags.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecraft_update_tags.py index ca8dfe3d4808..8cc0cca21126 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecraft_update_tags.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecraft_update_tags.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecrafts_by_resource_group_list.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecrafts_by_resource_group_list.py index 91c1f8409ca8..cc4ad193c2c5 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecrafts_by_resource_group_list.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecrafts_by_resource_group_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ diff --git a/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecrafts_by_subscription_list.py b/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecrafts_by_subscription_list.py index 11e740ba737c..366b229ca068 100644 --- a/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecrafts_by_subscription_list.py +++ b/sdk/orbital/azure-mgmt-orbital/generated_samples/spacecrafts_by_subscription_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.orbital import AzureOrbital """ diff --git a/sdk/orbital/azure-mgmt-orbital/generated_tests/conftest.py b/sdk/orbital/azure-mgmt-orbital/generated_tests/conftest.py new file mode 100644 index 000000000000..f038b32102ea --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + azureorbital_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + azureorbital_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + azureorbital_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + azureorbital_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=azureorbital_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=azureorbital_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=azureorbital_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=azureorbital_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_available_ground_stations_operations.py b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_available_ground_stations_operations.py new file mode 100644 index 000000000000..27d706fe666d --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_available_ground_stations_operations.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.orbital import AzureOrbital + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureOrbitalAvailableGroundStationsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureOrbital) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_available_ground_stations_list_by_capability(self, resource_group): + response = self.client.available_ground_stations.list_by_capability( + capability="str", + api_version="2022-11-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_available_ground_stations_operations_async.py b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_available_ground_stations_operations_async.py new file mode 100644 index 000000000000..a6d3a5bf10e3 --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_available_ground_stations_operations_async.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.orbital.aio import AzureOrbital + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureOrbitalAvailableGroundStationsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureOrbital, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_available_ground_stations_list_by_capability(self, resource_group): + response = self.client.available_ground_stations.list_by_capability( + capability="str", + api_version="2022-11-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_contact_profiles_operations.py b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_contact_profiles_operations.py new file mode 100644 index 000000000000..2e88e4e93079 --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_contact_profiles_operations.py @@ -0,0 +1,137 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.orbital import AzureOrbital + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureOrbitalContactProfilesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureOrbital) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_contact_profiles_list_by_subscription(self, resource_group): + response = self.client.contact_profiles.list_by_subscription( + api_version="2022-11-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_contact_profiles_list(self, resource_group): + response = self.client.contact_profiles.list( + resource_group_name=resource_group.name, + api_version="2022-11-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_contact_profiles_get(self, resource_group): + response = self.client.contact_profiles.get( + resource_group_name=resource_group.name, + contact_profile_name="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_contact_profiles_begin_create_or_update(self, resource_group): + response = self.client.contact_profiles.begin_create_or_update( + resource_group_name=resource_group.name, + contact_profile_name="str", + parameters={ + "links": [ + { + "channels": [ + { + "bandwidthMHz": 0.0, + "centerFrequencyMHz": 0.0, + "endPoint": { + "endPointName": "str", + "ipAddress": "str", + "port": "str", + "protocol": "str", + }, + "name": "str", + "decodingConfiguration": "str", + "demodulationConfiguration": "str", + "encodingConfiguration": "str", + "modulationConfiguration": "str", + } + ], + "direction": "str", + "name": "str", + "polarization": "str", + "eirpdBW": 0.0, + "gainOverTemperature": 0.0, + } + ], + "location": "str", + "networkConfiguration": {"subnetId": "str"}, + "autoTrackingConfiguration": "str", + "eventHubUri": "str", + "id": "str", + "minimumElevationDegrees": 0.0, + "minimumViableContactDuration": "str", + "name": "str", + "provisioningState": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "thirdPartyConfigurations": [{"missionConfiguration": "str", "providerName": "str"}], + "type": "str", + }, + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_contact_profiles_begin_update_tags(self, resource_group): + response = self.client.contact_profiles.begin_update_tags( + resource_group_name=resource_group.name, + contact_profile_name="str", + parameters={"tags": {"str": "str"}}, + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_contact_profiles_begin_delete(self, resource_group): + response = self.client.contact_profiles.begin_delete( + resource_group_name=resource_group.name, + contact_profile_name="str", + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_contact_profiles_operations_async.py b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_contact_profiles_operations_async.py new file mode 100644 index 000000000000..51d9074acd5f --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_contact_profiles_operations_async.py @@ -0,0 +1,144 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.orbital.aio import AzureOrbital + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureOrbitalContactProfilesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureOrbital, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_contact_profiles_list_by_subscription(self, resource_group): + response = self.client.contact_profiles.list_by_subscription( + api_version="2022-11-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_contact_profiles_list(self, resource_group): + response = self.client.contact_profiles.list( + resource_group_name=resource_group.name, + api_version="2022-11-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_contact_profiles_get(self, resource_group): + response = await self.client.contact_profiles.get( + resource_group_name=resource_group.name, + contact_profile_name="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_contact_profiles_begin_create_or_update(self, resource_group): + response = await ( + await self.client.contact_profiles.begin_create_or_update( + resource_group_name=resource_group.name, + contact_profile_name="str", + parameters={ + "links": [ + { + "channels": [ + { + "bandwidthMHz": 0.0, + "centerFrequencyMHz": 0.0, + "endPoint": { + "endPointName": "str", + "ipAddress": "str", + "port": "str", + "protocol": "str", + }, + "name": "str", + "decodingConfiguration": "str", + "demodulationConfiguration": "str", + "encodingConfiguration": "str", + "modulationConfiguration": "str", + } + ], + "direction": "str", + "name": "str", + "polarization": "str", + "eirpdBW": 0.0, + "gainOverTemperature": 0.0, + } + ], + "location": "str", + "networkConfiguration": {"subnetId": "str"}, + "autoTrackingConfiguration": "str", + "eventHubUri": "str", + "id": "str", + "minimumElevationDegrees": 0.0, + "minimumViableContactDuration": "str", + "name": "str", + "provisioningState": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "thirdPartyConfigurations": [{"missionConfiguration": "str", "providerName": "str"}], + "type": "str", + }, + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_contact_profiles_begin_update_tags(self, resource_group): + response = await ( + await self.client.contact_profiles.begin_update_tags( + resource_group_name=resource_group.name, + contact_profile_name="str", + parameters={"tags": {"str": "str"}}, + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_contact_profiles_begin_delete(self, resource_group): + response = await ( + await self.client.contact_profiles.begin_delete( + resource_group_name=resource_group.name, + contact_profile_name="str", + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_contacts_operations.py b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_contacts_operations.py new file mode 100644 index 000000000000..3d777559e7e9 --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_contacts_operations.py @@ -0,0 +1,100 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.orbital import AzureOrbital + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureOrbitalContactsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureOrbital) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_contacts_list(self, resource_group): + response = self.client.contacts.list( + resource_group_name=resource_group.name, + spacecraft_name="str", + api_version="2022-11-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_contacts_get(self, resource_group): + response = self.client.contacts.get( + resource_group_name=resource_group.name, + spacecraft_name="str", + contact_name="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_contacts_begin_create(self, resource_group): + response = self.client.contacts.begin_create( + resource_group_name=resource_group.name, + spacecraft_name="str", + contact_name="str", + parameters={ + "contactProfile": {"id": "str"}, + "groundStationName": "str", + "reservationEndTime": "2020-02-20 00:00:00", + "reservationStartTime": "2020-02-20 00:00:00", + "antennaConfiguration": {"destinationIp": "str", "sourceIps": ["str"]}, + "endAzimuthDegrees": 0.0, + "endElevationDegrees": 0.0, + "errorMessage": "str", + "id": "str", + "maximumElevationDegrees": 0.0, + "name": "str", + "provisioningState": "str", + "rxEndTime": "2020-02-20 00:00:00", + "rxStartTime": "2020-02-20 00:00:00", + "startAzimuthDegrees": 0.0, + "startElevationDegrees": 0.0, + "status": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "txEndTime": "2020-02-20 00:00:00", + "txStartTime": "2020-02-20 00:00:00", + "type": "str", + }, + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_contacts_begin_delete(self, resource_group): + response = self.client.contacts.begin_delete( + resource_group_name=resource_group.name, + spacecraft_name="str", + contact_name="str", + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_contacts_operations_async.py b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_contacts_operations_async.py new file mode 100644 index 000000000000..95600c2dd148 --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_contacts_operations_async.py @@ -0,0 +1,105 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.orbital.aio import AzureOrbital + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureOrbitalContactsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureOrbital, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_contacts_list(self, resource_group): + response = self.client.contacts.list( + resource_group_name=resource_group.name, + spacecraft_name="str", + api_version="2022-11-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_contacts_get(self, resource_group): + response = await self.client.contacts.get( + resource_group_name=resource_group.name, + spacecraft_name="str", + contact_name="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_contacts_begin_create(self, resource_group): + response = await ( + await self.client.contacts.begin_create( + resource_group_name=resource_group.name, + spacecraft_name="str", + contact_name="str", + parameters={ + "contactProfile": {"id": "str"}, + "groundStationName": "str", + "reservationEndTime": "2020-02-20 00:00:00", + "reservationStartTime": "2020-02-20 00:00:00", + "antennaConfiguration": {"destinationIp": "str", "sourceIps": ["str"]}, + "endAzimuthDegrees": 0.0, + "endElevationDegrees": 0.0, + "errorMessage": "str", + "id": "str", + "maximumElevationDegrees": 0.0, + "name": "str", + "provisioningState": "str", + "rxEndTime": "2020-02-20 00:00:00", + "rxStartTime": "2020-02-20 00:00:00", + "startAzimuthDegrees": 0.0, + "startElevationDegrees": 0.0, + "status": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "txEndTime": "2020-02-20 00:00:00", + "txStartTime": "2020-02-20 00:00:00", + "type": "str", + }, + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_contacts_begin_delete(self, resource_group): + response = await ( + await self.client.contacts.begin_delete( + resource_group_name=resource_group.name, + spacecraft_name="str", + contact_name="str", + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_operations.py b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_operations.py new file mode 100644 index 000000000000..3fa5c3023bca --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_operations.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.orbital import AzureOrbital + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureOrbitalOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureOrbital) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operations_list(self, resource_group): + response = self.client.operations.list( + api_version="2022-11-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_operations_async.py b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_operations_async.py new file mode 100644 index 000000000000..3caafc5f8b4a --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_operations_async.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.orbital.aio import AzureOrbital + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureOrbitalOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureOrbital, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_operations_list(self, resource_group): + response = self.client.operations.list( + api_version="2022-11-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_operations_results_operations.py b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_operations_results_operations.py new file mode 100644 index 000000000000..2a2645e986c4 --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_operations_results_operations.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.orbital import AzureOrbital + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureOrbitalOperationsResultsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureOrbital) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operations_results_get(self, resource_group): + response = self.client.operations_results.get( + location="str", + operation_id="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_operations_results_operations_async.py b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_operations_results_operations_async.py new file mode 100644 index 000000000000..ec4c7db4579b --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_operations_results_operations_async.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.orbital.aio import AzureOrbital + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureOrbitalOperationsResultsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureOrbital, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_operations_results_get(self, resource_group): + response = await self.client.operations_results.get( + location="str", + operation_id="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_spacecrafts_operations.py b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_spacecrafts_operations.py new file mode 100644 index 000000000000..93ab389b3cce --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_spacecrafts_operations.py @@ -0,0 +1,137 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.orbital import AzureOrbital + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureOrbitalSpacecraftsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureOrbital) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_spacecrafts_list_by_subscription(self, resource_group): + response = self.client.spacecrafts.list_by_subscription( + api_version="2022-11-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_spacecrafts_list(self, resource_group): + response = self.client.spacecrafts.list( + resource_group_name=resource_group.name, + api_version="2022-11-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_spacecrafts_get(self, resource_group): + response = self.client.spacecrafts.get( + resource_group_name=resource_group.name, + spacecraft_name="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_spacecrafts_begin_create_or_update(self, resource_group): + response = self.client.spacecrafts.begin_create_or_update( + resource_group_name=resource_group.name, + spacecraft_name="str", + parameters={ + "links": [ + { + "bandwidthMHz": 0.0, + "centerFrequencyMHz": 0.0, + "direction": "str", + "name": "str", + "polarization": "str", + "authorizations": [{"expirationDate": "2020-02-20", "groundStation": "str"}], + } + ], + "location": "str", + "titleLine": "str", + "tleLine1": "str", + "tleLine2": "str", + "id": "str", + "name": "str", + "noradId": "str", + "provisioningState": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_spacecrafts_begin_update_tags(self, resource_group): + response = self.client.spacecrafts.begin_update_tags( + resource_group_name=resource_group.name, + spacecraft_name="str", + parameters={"tags": {"str": "str"}}, + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_spacecrafts_begin_delete(self, resource_group): + response = self.client.spacecrafts.begin_delete( + resource_group_name=resource_group.name, + spacecraft_name="str", + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_spacecrafts_begin_list_available_contacts(self, resource_group): + response = self.client.spacecrafts.begin_list_available_contacts( + resource_group_name=resource_group.name, + spacecraft_name="str", + parameters={ + "contactProfile": {"id": "str"}, + "endTime": "2020-02-20 00:00:00", + "groundStationName": "str", + "startTime": "2020-02-20 00:00:00", + }, + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_spacecrafts_operations_async.py b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_spacecrafts_operations_async.py new file mode 100644 index 000000000000..0e6b8602d613 --- /dev/null +++ b/sdk/orbital/azure-mgmt-orbital/generated_tests/test_azure_orbital_spacecrafts_operations_async.py @@ -0,0 +1,146 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.orbital.aio import AzureOrbital + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAzureOrbitalSpacecraftsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AzureOrbital, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_spacecrafts_list_by_subscription(self, resource_group): + response = self.client.spacecrafts.list_by_subscription( + api_version="2022-11-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_spacecrafts_list(self, resource_group): + response = self.client.spacecrafts.list( + resource_group_name=resource_group.name, + api_version="2022-11-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_spacecrafts_get(self, resource_group): + response = await self.client.spacecrafts.get( + resource_group_name=resource_group.name, + spacecraft_name="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_spacecrafts_begin_create_or_update(self, resource_group): + response = await ( + await self.client.spacecrafts.begin_create_or_update( + resource_group_name=resource_group.name, + spacecraft_name="str", + parameters={ + "links": [ + { + "bandwidthMHz": 0.0, + "centerFrequencyMHz": 0.0, + "direction": "str", + "name": "str", + "polarization": "str", + "authorizations": [{"expirationDate": "2020-02-20", "groundStation": "str"}], + } + ], + "location": "str", + "titleLine": "str", + "tleLine1": "str", + "tleLine2": "str", + "id": "str", + "name": "str", + "noradId": "str", + "provisioningState": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_spacecrafts_begin_update_tags(self, resource_group): + response = await ( + await self.client.spacecrafts.begin_update_tags( + resource_group_name=resource_group.name, + spacecraft_name="str", + parameters={"tags": {"str": "str"}}, + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_spacecrafts_begin_delete(self, resource_group): + response = await ( + await self.client.spacecrafts.begin_delete( + resource_group_name=resource_group.name, + spacecraft_name="str", + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_spacecrafts_begin_list_available_contacts(self, resource_group): + response = await ( + await self.client.spacecrafts.begin_list_available_contacts( + resource_group_name=resource_group.name, + spacecraft_name="str", + parameters={ + "contactProfile": {"id": "str"}, + "endTime": "2020-02-20 00:00:00", + "groundStationName": "str", + "startTime": "2020-02-20 00:00:00", + }, + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/orbital/azure-mgmt-orbital/sdk_packaging.toml b/sdk/orbital/azure-mgmt-orbital/sdk_packaging.toml index 87c7b8168e5e..9397a8b6d316 100644 --- a/sdk/orbital/azure-mgmt-orbital/sdk_packaging.toml +++ b/sdk/orbital/azure-mgmt-orbital/sdk_packaging.toml @@ -3,7 +3,7 @@ package_name = "azure-mgmt-orbital" package_nspkg = "azure-mgmt-nspkg" package_pprint_name = "Orbital Management" package_doc_id = "" -is_stable = false +is_stable = true is_arm = true need_msrestazure = false need_azuremgmtcore = true diff --git a/sdk/orbital/azure-mgmt-orbital/setup.py b/sdk/orbital/azure-mgmt-orbital/setup.py index f2bba6a81634..4fc661590d2a 100644 --- a/sdk/orbital/azure-mgmt-orbital/setup.py +++ b/sdk/orbital/azure-mgmt-orbital/setup.py @@ -1,10 +1,10 @@ #!/usr/bin/env python -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- import re import os.path @@ -16,64 +16,67 @@ PACKAGE_PPRINT_NAME = "Orbital Management" # a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace('-', '/') +package_folder_path = PACKAGE_NAME.replace("-", "/") # a-b-c => a.b.c -namespace_name = PACKAGE_NAME.replace('-', '.') +namespace_name = PACKAGE_NAME.replace("-", ".") # Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, 'version.py') - if os.path.exists(os.path.join(package_folder_path, 'version.py')) - else os.path.join(package_folder_path, '_version.py'), 'r') as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', - fd.read(), re.MULTILINE).group(1) +with open( + os.path.join(package_folder_path, "version.py") + if os.path.exists(os.path.join(package_folder_path, "version.py")) + else os.path.join(package_folder_path, "_version.py"), + "r", +) as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: - raise RuntimeError('Cannot find version information') + raise RuntimeError("Cannot find version information") -with open('README.md', encoding='utf-8') as f: +with open("README.md", encoding="utf-8") as f: readme = f.read() -with open('CHANGELOG.md', encoding='utf-8') as f: +with open("CHANGELOG.md", encoding="utf-8") as f: changelog = f.read() setup( name=PACKAGE_NAME, version=version, - description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), - long_description=readme + '\n\n' + changelog, - long_description_content_type='text/markdown', - license='MIT License', - author='Microsoft Corporation', - author_email='azpysdkhelp@microsoft.com', - url='https://github.com/Azure/azure-sdk-for-python', + description="Microsoft Azure {} Client Library for Python".format(PACKAGE_PPRINT_NAME), + long_description=readme + "\n\n" + changelog, + long_description_content_type="text/markdown", + license="MIT License", + author="Microsoft Corporation", + author_email="azpysdkhelp@microsoft.com", + url="https://github.com/Azure/azure-sdk-for-python", keywords="azure, azure sdk", # update with search keywords relevant to the azure service / product classifiers=[ - 'Development Status :: 4 - Beta', - 'Programming Language :: Python', - 'Programming Language :: Python :: 3 :: Only', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'License :: OSI Approved :: MIT License', + "Development Status :: 5 - Production/Stable", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: MIT License", ], zip_safe=False, - packages=find_packages(exclude=[ - 'tests', - # Exclude packages that will be covered by PEP420 or nspkg - 'azure', - 'azure.mgmt', - ]), + packages=find_packages( + exclude=[ + "tests", + # Exclude packages that will be covered by PEP420 or nspkg + "azure", + "azure.mgmt", + ] + ), include_package_data=True, package_data={ - 'pytyped': ['py.typed'], + "pytyped": ["py.typed"], }, install_requires=[ - "msrest>=0.7.1", - "azure-common~=1.1", - "azure-mgmt-core>=1.3.2,<2.0.0", - "typing-extensions>=4.3.0; python_version<'3.8.0'", + "isodate>=0.6.1", + "typing-extensions>=4.6.0", + "azure-common>=1.1", + "azure-mgmt-core>=1.5.0", ], - python_requires=">=3.7" + python_requires=">=3.9", )