diff --git a/.vscode/cspell.json b/.vscode/cspell.json index e57c1b8c4feb..44ab178d7682 100644 --- a/.vscode/cspell.json +++ b/.vscode/cspell.json @@ -1897,6 +1897,16 @@ "words": [ "stringized" ] + }, + { + "filename": "sdk/maps/azure-maps-route/**", + "words": [ + "uturn", + "Einsteinweg", + "Hundredkm", + "TPEG", + "Hundredkm" + ] } ], "allowCompoundWords": true diff --git a/sdk/maps/azure-maps-route/assets.json b/sdk/maps/azure-maps-route/assets.json index 584b647e89f7..4473e0cfec8e 100644 --- a/sdk/maps/azure-maps-route/assets.json +++ b/sdk/maps/azure-maps-route/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/maps/azure-maps-route", - "Tag": "python/maps/azure-maps-route_543cdfb1f8" + "Tag": "python/maps/azure-maps-route_fe9d365729" } diff --git a/sdk/maps/azure-maps-route/azure/maps/route/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/__init__.py index 596ea9c88588..8a3c08dfb6f2 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/__init__.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/__init__.py @@ -6,10 +6,16 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._version import VERSION -from ._route_client import MapsRouteClient +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'MapsRouteClient' + "MapsRouteClient", ] -__version__ = VERSION +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_client.py b/sdk/maps/azure-maps-route/azure/maps/route/_client.py similarity index 67% rename from sdk/maps/azure-maps-route/azure/maps/route/_generated/_client.py rename to sdk/maps/azure-maps-route/azure/maps/route/_client.py index 7d3d332a4801..903dfdd53eb2 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_client.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/_client.py @@ -8,11 +8,13 @@ from copy import deepcopy from typing import Any, Optional, TYPE_CHECKING +from typing_extensions import Self from azure.core import PipelineClient +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse -from . import models +from . import models as _models from ._configuration import MapsRouteClientConfiguration from ._serialization import Deserializer, Serializer from .operations import RouteOperations @@ -22,13 +24,13 @@ from azure.core.credentials import TokenCredential -class MapsRouteClient: # pylint: disable=client-accepts-api-version-keyword +class MapsRouteClient(RouteOperations): """Azure Maps Route REST APIs. :ivar route: RouteOperations operations :vartype route: azure.maps.route.operations.RouteOperations :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential + :type credential: ~azure.core.credentials.AzureKeyCredential :param client_id: Specifies which account is intended for usage in conjunction with the Azure AD security model. It represents a unique ID for the Azure Maps account and can be retrieved from the Azure Maps management plane Account API. To use Azure AD security in Azure Maps see @@ -52,15 +54,37 @@ def __init__( **kwargs: Any ) -> None: self._config = MapsRouteClientConfiguration(credential=credential, client_id=client_id, **kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + _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), + 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: PipelineClient = PipelineClient(base_url=endpoint, policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False - self.route = RouteOperations(self._client, self._config, self._serialize, self._deserialize) - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + super().__init__( + client=self._client, + config=self._config, + serializer=self._serialize, + deserializer=self._deserialize + ) + + 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 @@ -80,17 +104,14 @@ 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): - # type: () -> None + def close(self) -> None: self._client.close() - def __enter__(self): - # type: () -> MapsRouteClient + def __enter__(self) -> Self: self._client.__enter__() return self - def __exit__(self, *exc_details): - # type: (Any) -> None + def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_configuration.py b/sdk/maps/azure-maps-route/azure/maps/route/_configuration.py similarity index 67% rename from sdk/maps/azure-maps-route/azure/maps/route/_generated/_configuration.py rename to sdk/maps/azure-maps-route/azure/maps/route/_configuration.py index e92a332e50b4..3513b659ff62 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_configuration.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/_configuration.py @@ -8,17 +8,16 @@ from typing import Any, Optional, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies -from ._version import VERSION - if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential +VERSION = "1.0.0b2" + -class MapsRouteClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MapsRouteClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for MapsRouteClient. Note that all parameters used to create this instance are saved as instance @@ -26,42 +25,52 @@ class MapsRouteClientConfiguration(Configuration): # pylint: disable=too-many-i :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param client_id: Specifies which account is intended for usage in conjunction with the Azure - AD security model. It represents a unique ID for the Azure Maps account and can be retrieved - from the Azure Maps management plane Account API. To use Azure AD security in Azure Maps see - the following `articles `_ for guidance. Default value is None. + :param accept: The Accept header field can be used to specify preferences regarding response + media types. Allowed media types include image/jpeg and image/png. Return image in image/png if + Accept header is not specified. Known values are: "image/png" and "image/jpeg". Default value + is None. + :type accept: str + :param client_id: Specifies which account is intended for usage in conjunction with the + Microsoft Entra ID security model. It represents a unique ID for the Azure Maps account and + can be retrieved from the Azure Maps management plane Account API. To use Microsoft Entra ID + security in Azure Maps see the following `articles `_ for + guidance. Default value is None. :type client_id: str - :keyword api_version: Api Version. Default value is "1.0". Note that overriding this default - value may result in unsupported behavior. + :keyword api_version: Api Version. Default value is "1.0". Note that overriding this + default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, credential: "TokenCredential", client_id: Optional[str] = None, **kwargs: Any) -> None: - super(MapsRouteClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "1.0") # type: str + def __init__( + self, + credential: "TokenCredential", + accept: Optional[str] = None, + client_id: Optional[str] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "1.0") if credential is None: raise ValueError("Parameter 'credential' must not be None.") self.credential = credential + self.accept = accept self.client_id = client_id self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://atlas.microsoft.com/.default"]) kwargs.setdefault("sdk_moniker", "maps-route/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> None + def _configure(self, **kwargs: Any) -> None: self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**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 = policies.BearerTokenCredentialPolicy( diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/__init__.py deleted file mode 100644 index 3a3ceaee1f06..000000000000 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import MapsRouteClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["MapsRouteClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_vendor.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/_vendor.py deleted file mode 100644 index 54f238858ed8..000000000000 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_vendor.py +++ /dev/null @@ -1,17 +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. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_version.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/_version.py deleted file mode 100644 index b9995fb385b0..000000000000 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "1.0-preview" diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/__init__.py deleted file mode 100644 index 8fb07df07c83..000000000000 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import MapsRouteClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["MapsRouteClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_patch.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_patch.py deleted file mode 100644 index f7dd32510333..000000000000 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/_patch.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/_patch.py deleted file mode 100644 index f7dd32510333..000000000000 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/__init__.py deleted file mode 100644 index ad96766b2ce1..000000000000 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/__init__.py +++ /dev/null @@ -1,173 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._models import BatchRequest -from ._models import BatchRequestItem -from ._models import BatchResult -from ._models import BatchResultItem -from ._models import BatchResultSummary -from ._models import EffectiveSetting -from ._models import ErrorAdditionalInfo -from ._models import ErrorDetail -from ._models import ErrorResponse -from ._models import GeoJsonFeature -from ._models import GeoJsonFeatureCollection -from ._models import GeoJsonFeatureCollectionData -from ._models import GeoJsonFeatureData -from ._models import GeoJsonGeometry -from ._models import GeoJsonGeometryCollection -from ._models import GeoJsonGeometryCollectionData -from ._models import GeoJsonLineString -from ._models import GeoJsonLineStringData -from ._models import GeoJsonMultiLineString -from ._models import GeoJsonMultiLineStringData -from ._models import GeoJsonMultiPoint -from ._models import GeoJsonMultiPointData -from ._models import GeoJsonMultiPolygon -from ._models import GeoJsonMultiPolygonData -from ._models import GeoJsonObject -from ._models import GeoJsonPoint -from ._models import GeoJsonPointData -from ._models import GeoJsonPolygon -from ._models import GeoJsonPolygonData -from ._models import LatLongPair -from ._models import Route -from ._models import RouteDirectionParameters -from ._models import RouteDirections -from ._models import RouteDirectionsBatchItem -from ._models import RouteDirectionsBatchItemResponse -from ._models import RouteDirectionsBatchResult -from ._models import RouteGuidance -from ._models import RouteInstruction -from ._models import RouteInstructionGroup -from ._models import RouteLeg -from ._models import RouteLegSummary -from ._models import RouteMatrix -from ._models import RouteMatrixQuery -from ._models import RouteMatrixResult -from ._models import RouteMatrixResultResponse -from ._models import RouteMatrixSummary -from ._models import RouteOptimizedWaypoint -from ._models import RouteRange -from ._models import RouteRangeResult -from ._models import RouteReport -from ._models import RouteSection -from ._models import RouteSectionTec -from ._models import RouteSectionTecCause -from ._models import RouteSummary - -from ._enums import AlternativeRouteType -from ._enums import ComputeTravelTime -from ._enums import DelayMagnitude -from ._enums import DrivingSide -from ._enums import GeoJsonObjectType -from ._enums import GuidanceInstructionType -from ._enums import GuidanceManeuver -from ._enums import InclineLevel -from ._enums import JsonFormat -from ._enums import JunctionType -from ._enums import Report -from ._enums import ResponseFormat -from ._enums import ResponseSectionType -from ._enums import ResponseTravelMode -from ._enums import RouteAvoidType -from ._enums import RouteInstructionsType -from ._enums import RouteRepresentationForBestOrder -from ._enums import RouteType -from ._enums import SectionType -from ._enums import SimpleCategory -from ._enums import TravelMode -from ._enums import VehicleEngineType -from ._enums import VehicleLoadType -from ._enums import WindingnessLevel -from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "BatchRequest", - "BatchRequestItem", - "BatchResult", - "BatchResultItem", - "BatchResultSummary", - "EffectiveSetting", - "ErrorAdditionalInfo", - "ErrorDetail", - "ErrorResponse", - "GeoJsonFeature", - "GeoJsonFeatureCollection", - "GeoJsonFeatureCollectionData", - "GeoJsonFeatureData", - "GeoJsonGeometry", - "GeoJsonGeometryCollection", - "GeoJsonGeometryCollectionData", - "GeoJsonLineString", - "GeoJsonLineStringData", - "GeoJsonMultiLineString", - "GeoJsonMultiLineStringData", - "GeoJsonMultiPoint", - "GeoJsonMultiPointData", - "GeoJsonMultiPolygon", - "GeoJsonMultiPolygonData", - "GeoJsonObject", - "GeoJsonPoint", - "GeoJsonPointData", - "GeoJsonPolygon", - "GeoJsonPolygonData", - "LatLongPair", - "Route", - "RouteDirectionParameters", - "RouteDirections", - "RouteDirectionsBatchItem", - "RouteDirectionsBatchItemResponse", - "RouteDirectionsBatchResult", - "RouteGuidance", - "RouteInstruction", - "RouteInstructionGroup", - "RouteLeg", - "RouteLegSummary", - "RouteMatrix", - "RouteMatrixQuery", - "RouteMatrixResult", - "RouteMatrixResultResponse", - "RouteMatrixSummary", - "RouteOptimizedWaypoint", - "RouteRange", - "RouteRangeResult", - "RouteReport", - "RouteSection", - "RouteSectionTec", - "RouteSectionTecCause", - "RouteSummary", - "AlternativeRouteType", - "ComputeTravelTime", - "DelayMagnitude", - "DrivingSide", - "GeoJsonObjectType", - "GuidanceInstructionType", - "GuidanceManeuver", - "InclineLevel", - "JsonFormat", - "JunctionType", - "Report", - "ResponseFormat", - "ResponseSectionType", - "ResponseTravelMode", - "RouteAvoidType", - "RouteInstructionsType", - "RouteRepresentationForBestOrder", - "RouteType", - "SectionType", - "SimpleCategory", - "TravelMode", - "VehicleEngineType", - "VehicleLoadType", - "WindingnessLevel", -] -__all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_models.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_models.py deleted file mode 100644 index 1d12b83e5710..000000000000 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_models.py +++ /dev/null @@ -1,2146 +0,0 @@ -# coding=utf-8 -# pylint: disable=too-many-lines -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -import sys -from typing import Any, List, Optional, TYPE_CHECKING, Union - -from .. import _serialization - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from .. import models as _models -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - - -class BatchRequest(_serialization.Model): - """This type represents the request body for the Batch service. - - :ivar batch_items: The list of queries to process. - :vartype batch_items: list[~azure.maps.route.models.BatchRequestItem] - """ - - _attribute_map = { - "batch_items": {"key": "batchItems", "type": "[BatchRequestItem]"}, - } - - def __init__(self, *, batch_items: Optional[List["_models.BatchRequestItem"]] = None, **kwargs): - """ - :keyword batch_items: The list of queries to process. - :paramtype batch_items: list[~azure.maps.route.models.BatchRequestItem] - """ - super().__init__(**kwargs) - self.batch_items = batch_items - - -class BatchRequestItem(_serialization.Model): - """Batch request object. - - :ivar query: This parameter contains a query string used to perform an unstructured geocoding - operation. The query string will be passed verbatim to the search API for processing. - :vartype query: str - """ - - _attribute_map = { - "query": {"key": "query", "type": "str"}, - } - - def __init__(self, *, query: Optional[str] = None, **kwargs): - """ - :keyword query: This parameter contains a query string used to perform an unstructured - geocoding operation. The query string will be passed verbatim to the search API for processing. - :paramtype query: str - """ - super().__init__(**kwargs) - self.query = query - - -class BatchResult(_serialization.Model): - """This object is returned from a successful Batch service call. Extend with 'batchItems' property. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar batch_summary: Summary of the results for the batch request. - :vartype batch_summary: ~azure.maps.route.models.BatchResultSummary - """ - - _validation = { - "batch_summary": {"readonly": True}, - } - - _attribute_map = { - "batch_summary": {"key": "summary", "type": "BatchResultSummary"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.batch_summary = None - - -class BatchResultItem(_serialization.Model): - """An item returned from Batch API. Extend with 'response' property. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar status_code: HTTP request status code. - :vartype status_code: int - """ - - _validation = { - "status_code": {"readonly": True}, - } - - _attribute_map = { - "status_code": {"key": "statusCode", "type": "int"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.status_code = None - - -class BatchResultSummary(_serialization.Model): - """Summary of the results for the batch request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar successful_requests: Number of successful requests in the batch. - :vartype successful_requests: int - :ivar total_requests: Total number of requests in the batch. - :vartype total_requests: int - """ - - _validation = { - "successful_requests": {"readonly": True}, - "total_requests": {"readonly": True}, - } - - _attribute_map = { - "successful_requests": {"key": "successfulRequests", "type": "int"}, - "total_requests": {"key": "totalRequests", "type": "int"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.successful_requests = None - self.total_requests = None - - -class EffectiveSetting(_serialization.Model): - """Effective parameter or data used when calling this Route API. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar key: Name of the parameter used. - :vartype key: str - :ivar value: Value of the parameter used. - :vartype value: str - """ - - _validation = { - "key": {"readonly": True}, - "value": {"readonly": True}, - } - - _attribute_map = { - "key": {"key": "key", "type": "str"}, - "value": {"key": "value", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.key = None - self.value = None - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.type = None - self.info = None - - -class ErrorDetail(_serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.maps.route.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.maps.route.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDetail]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None - - -class ErrorResponse(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - - :ivar error: The error object. - :vartype error: ~azure.maps.route.models.ErrorDetail - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): - """ - :keyword error: The error object. - :paramtype error: ~azure.maps.route.models.ErrorDetail - """ - super().__init__(**kwargs) - self.error = error - - -class GeoJsonFeatureData(_serialization.Model): - """GeoJsonFeatureData. - - All required parameters must be populated in order to send to Azure. - - :ivar geometry: A valid ``GeoJSON`` geometry object. The type must be one of the seven valid - GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon - and GeometryCollection. Please refer to `RFC 7946 - `_ for details. Required. - :vartype geometry: ~azure.maps.route.models.GeoJsonGeometry - :ivar properties: Properties can contain any additional metadata about the ``Feature``. Value - can be any JSON object or a JSON null value. - :vartype properties: JSON - :ivar id: Identifier for the feature. - :vartype id: str - :ivar feature_type: The type of the feature. The value depends on the data model the current - feature is part of. Some data models may have an empty value. - :vartype feature_type: str - """ - - _validation = { - "geometry": {"required": True}, - } - - _attribute_map = { - "geometry": {"key": "geometry", "type": "GeoJsonGeometry"}, - "properties": {"key": "properties", "type": "object"}, - "id": {"key": "id", "type": "str"}, - "feature_type": {"key": "featureType", "type": "str"}, - } - - def __init__( - self, - *, - geometry: "_models.GeoJsonGeometry", - properties: Optional[JSON] = None, - id: Optional[str] = None, # pylint: disable=redefined-builtin - feature_type: Optional[str] = None, - **kwargs - ): - """ - :keyword geometry: A valid ``GeoJSON`` geometry object. The type must be one of the seven valid - GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon - and GeometryCollection. Please refer to `RFC 7946 - `_ for details. Required. - :paramtype geometry: ~azure.maps.route.models.GeoJsonGeometry - :keyword properties: Properties can contain any additional metadata about the ``Feature``. - Value can be any JSON object or a JSON null value. - :paramtype properties: JSON - :keyword id: Identifier for the feature. - :paramtype id: str - :keyword feature_type: The type of the feature. The value depends on the data model the current - feature is part of. Some data models may have an empty value. - :paramtype feature_type: str - """ - super().__init__(**kwargs) - self.geometry = geometry - self.properties = properties - self.id = id - self.feature_type = feature_type - - -class GeoJsonObject(_serialization.Model): - """A valid ``GeoJSON`` object. Please refer to `RFC 7946 `_ for details. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - GeoJsonFeature, GeoJsonFeatureCollection, GeoJsonGeometry - - All required parameters must be populated in order to send to Azure. - - :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, - Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", - "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and - "FeatureCollection". - :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType - """ - - _validation = { - "type": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - } - - _subtype_map = { - "type": { - "Feature": "GeoJsonFeature", - "FeatureCollection": "GeoJsonFeatureCollection", - "GeoJsonGeometry": "GeoJsonGeometry", - } - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.type = None # type: Optional[str] - - -class GeoJsonFeature(GeoJsonObject, GeoJsonFeatureData): - """A valid ``GeoJSON Feature`` object type. Please refer to `RFC 7946 `_ for details. - - All required parameters must be populated in order to send to Azure. - - :ivar geometry: A valid ``GeoJSON`` geometry object. The type must be one of the seven valid - GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon - and GeometryCollection. Please refer to `RFC 7946 - `_ for details. Required. - :vartype geometry: ~azure.maps.route.models.GeoJsonGeometry - :ivar properties: Properties can contain any additional metadata about the ``Feature``. Value - can be any JSON object or a JSON null value. - :vartype properties: JSON - :ivar id: Identifier for the feature. - :vartype id: str - :ivar feature_type: The type of the feature. The value depends on the data model the current - feature is part of. Some data models may have an empty value. - :vartype feature_type: str - :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, - Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", - "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and - "FeatureCollection". - :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType - """ - - _validation = { - "geometry": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "geometry": {"key": "geometry", "type": "GeoJsonGeometry"}, - "properties": {"key": "properties", "type": "object"}, - "id": {"key": "id", "type": "str"}, - "feature_type": {"key": "featureType", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__( - self, - *, - geometry: "_models.GeoJsonGeometry", - properties: Optional[JSON] = None, - id: Optional[str] = None, # pylint: disable=redefined-builtin - feature_type: Optional[str] = None, - **kwargs - ): - """ - :keyword geometry: A valid ``GeoJSON`` geometry object. The type must be one of the seven valid - GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon - and GeometryCollection. Please refer to `RFC 7946 - `_ for details. Required. - :paramtype geometry: ~azure.maps.route.models.GeoJsonGeometry - :keyword properties: Properties can contain any additional metadata about the ``Feature``. - Value can be any JSON object or a JSON null value. - :paramtype properties: JSON - :keyword id: Identifier for the feature. - :paramtype id: str - :keyword feature_type: The type of the feature. The value depends on the data model the current - feature is part of. Some data models may have an empty value. - :paramtype feature_type: str - """ - super().__init__(geometry=geometry, properties=properties, id=id, feature_type=feature_type, **kwargs) - self.geometry = geometry - self.properties = properties - self.id = id - self.feature_type = feature_type - self.type = "Feature" # type: str - - -class GeoJsonFeatureCollectionData(_serialization.Model): - """GeoJsonFeatureCollectionData. - - All required parameters must be populated in order to send to Azure. - - :ivar features: Contains a list of valid ``GeoJSON Feature`` objects. Required. - :vartype features: list[~azure.maps.route.models.GeoJsonFeature] - """ - - _validation = { - "features": {"required": True}, - } - - _attribute_map = { - "features": {"key": "features", "type": "[GeoJsonFeature]"}, - } - - def __init__(self, *, features: List["_models.GeoJsonFeature"], **kwargs): - """ - :keyword features: Contains a list of valid ``GeoJSON Feature`` objects. Required. - :paramtype features: list[~azure.maps.route.models.GeoJsonFeature] - """ - super().__init__(**kwargs) - self.features = features - - -class GeoJsonFeatureCollection(GeoJsonObject, GeoJsonFeatureCollectionData): - """A valid ``GeoJSON FeatureCollection`` object type. Please refer to `RFC 7946 `_ for details. - - All required parameters must be populated in order to send to Azure. - - :ivar features: Contains a list of valid ``GeoJSON Feature`` objects. Required. - :vartype features: list[~azure.maps.route.models.GeoJsonFeature] - :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, - Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", - "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and - "FeatureCollection". - :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType - """ - - _validation = { - "features": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "features": {"key": "features", "type": "[GeoJsonFeature]"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, *, features: List["_models.GeoJsonFeature"], **kwargs): - """ - :keyword features: Contains a list of valid ``GeoJSON Feature`` objects. Required. - :paramtype features: list[~azure.maps.route.models.GeoJsonFeature] - """ - super().__init__(features=features, **kwargs) - self.features = features - self.type = "FeatureCollection" # type: str - - -class GeoJsonGeometry(GeoJsonObject): - """A valid ``GeoJSON`` geometry object. The type must be one of the seven valid GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon and GeometryCollection. Please refer to `RFC 7946 `_ for details. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - GeoJsonGeometryCollection, GeoJsonLineString, GeoJsonMultiLineString, GeoJsonMultiPoint, - GeoJsonMultiPolygon, GeoJsonPoint, GeoJsonPolygon - - All required parameters must be populated in order to send to Azure. - - :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, - Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", - "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and - "FeatureCollection". - :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType - """ - - _validation = { - "type": {"required": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - } - - _subtype_map = { - "type": { - "GeometryCollection": "GeoJsonGeometryCollection", - "LineString": "GeoJsonLineString", - "MultiLineString": "GeoJsonMultiLineString", - "MultiPoint": "GeoJsonMultiPoint", - "MultiPolygon": "GeoJsonMultiPolygon", - "Point": "GeoJsonPoint", - "Polygon": "GeoJsonPolygon", - } - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.type = "GeoJsonGeometry" # type: str - - -class GeoJsonGeometryCollectionData(_serialization.Model): - """GeoJsonGeometryCollectionData. - - All required parameters must be populated in order to send to Azure. - - :ivar geometries: Contains a list of valid ``GeoJSON`` geometry objects. **Note** that - coordinates in GeoJSON are in x, y order (longitude, latitude). Required. - :vartype geometries: list[~azure.maps.route.models.GeoJsonGeometry] - """ - - _validation = { - "geometries": {"required": True}, - } - - _attribute_map = { - "geometries": {"key": "geometries", "type": "[GeoJsonGeometry]"}, - } - - def __init__(self, *, geometries: List["_models.GeoJsonGeometry"], **kwargs): - """ - :keyword geometries: Contains a list of valid ``GeoJSON`` geometry objects. **Note** that - coordinates in GeoJSON are in x, y order (longitude, latitude). Required. - :paramtype geometries: list[~azure.maps.route.models.GeoJsonGeometry] - """ - super().__init__(**kwargs) - self.geometries = geometries - - -class GeoJsonGeometryCollection(GeoJsonGeometry, GeoJsonGeometryCollectionData): - """A valid ``GeoJSON GeometryCollection`` object type. Please refer to `RFC 7946 `_ for details. - - All required parameters must be populated in order to send to Azure. - - :ivar geometries: Contains a list of valid ``GeoJSON`` geometry objects. **Note** that - coordinates in GeoJSON are in x, y order (longitude, latitude). Required. - :vartype geometries: list[~azure.maps.route.models.GeoJsonGeometry] - :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, - Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", - "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and - "FeatureCollection". - :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType - """ - - _validation = { - "geometries": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "geometries": {"key": "geometries", "type": "[GeoJsonGeometry]"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, *, geometries: List["_models.GeoJsonGeometry"], **kwargs): - """ - :keyword geometries: Contains a list of valid ``GeoJSON`` geometry objects. **Note** that - coordinates in GeoJSON are in x, y order (longitude, latitude). Required. - :paramtype geometries: list[~azure.maps.route.models.GeoJsonGeometry] - """ - super().__init__(geometries=geometries, **kwargs) - self.geometries = geometries - self.type = "GeometryCollection" # type: str - - -class GeoJsonLineStringData(_serialization.Model): - """GeoJsonLineStringData. - - All required parameters must be populated in order to send to Azure. - - :ivar coordinates: Coordinates for the ``GeoJson LineString`` geometry. Required. - :vartype coordinates: list[list[float]] - """ - - _validation = { - "coordinates": {"required": True}, - } - - _attribute_map = { - "coordinates": {"key": "coordinates", "type": "[[float]]"}, - } - - def __init__(self, *, coordinates: List[List[float]], **kwargs): - """ - :keyword coordinates: Coordinates for the ``GeoJson LineString`` geometry. Required. - :paramtype coordinates: list[list[float]] - """ - super().__init__(**kwargs) - self.coordinates = coordinates - - -class GeoJsonLineString(GeoJsonGeometry, GeoJsonLineStringData): - """A valid ``GeoJSON LineString`` geometry type. Please refer to `RFC 7946 `_ for details. - - All required parameters must be populated in order to send to Azure. - - :ivar coordinates: Coordinates for the ``GeoJson LineString`` geometry. Required. - :vartype coordinates: list[list[float]] - :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, - Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", - "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and - "FeatureCollection". - :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType - """ - - _validation = { - "coordinates": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "coordinates": {"key": "coordinates", "type": "[[float]]"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, *, coordinates: List[List[float]], **kwargs): - """ - :keyword coordinates: Coordinates for the ``GeoJson LineString`` geometry. Required. - :paramtype coordinates: list[list[float]] - """ - super().__init__(coordinates=coordinates, **kwargs) - self.coordinates = coordinates - self.type = "LineString" # type: str - - -class GeoJsonMultiLineStringData(_serialization.Model): - """GeoJsonMultiLineStringData. - - All required parameters must be populated in order to send to Azure. - - :ivar coordinates: Coordinates for the ``GeoJson MultiLineString`` geometry. Required. - :vartype coordinates: list[list[list[float]]] - """ - - _validation = { - "coordinates": {"required": True}, - } - - _attribute_map = { - "coordinates": {"key": "coordinates", "type": "[[[float]]]"}, - } - - def __init__(self, *, coordinates: List[List[List[float]]], **kwargs): - """ - :keyword coordinates: Coordinates for the ``GeoJson MultiLineString`` geometry. Required. - :paramtype coordinates: list[list[list[float]]] - """ - super().__init__(**kwargs) - self.coordinates = coordinates - - -class GeoJsonMultiLineString(GeoJsonGeometry, GeoJsonMultiLineStringData): - """A valid ``GeoJSON MultiLineString`` geometry type. Please refer to `RFC 7946 `_ for details. - - All required parameters must be populated in order to send to Azure. - - :ivar coordinates: Coordinates for the ``GeoJson MultiLineString`` geometry. Required. - :vartype coordinates: list[list[list[float]]] - :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, - Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", - "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and - "FeatureCollection". - :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType - """ - - _validation = { - "coordinates": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "coordinates": {"key": "coordinates", "type": "[[[float]]]"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, *, coordinates: List[List[List[float]]], **kwargs): - """ - :keyword coordinates: Coordinates for the ``GeoJson MultiLineString`` geometry. Required. - :paramtype coordinates: list[list[list[float]]] - """ - super().__init__(coordinates=coordinates, **kwargs) - self.coordinates = coordinates - self.type = "MultiLineString" # type: str - - -class GeoJsonMultiPointData(_serialization.Model): - """Data contained by a ``GeoJson MultiPoint``. - - All required parameters must be populated in order to send to Azure. - - :ivar coordinates: Coordinates for the ``GeoJson MultiPoint`` geometry. Required. - :vartype coordinates: list[list[float]] - """ - - _validation = { - "coordinates": {"required": True}, - } - - _attribute_map = { - "coordinates": {"key": "coordinates", "type": "[[float]]"}, - } - - def __init__(self, *, coordinates: List[List[float]], **kwargs): - """ - :keyword coordinates: Coordinates for the ``GeoJson MultiPoint`` geometry. Required. - :paramtype coordinates: list[list[float]] - """ - super().__init__(**kwargs) - self.coordinates = coordinates - - -class GeoJsonMultiPoint(GeoJsonGeometry, GeoJsonMultiPointData): - """A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 `_ for details. - - All required parameters must be populated in order to send to Azure. - - :ivar coordinates: Coordinates for the ``GeoJson MultiPoint`` geometry. Required. - :vartype coordinates: list[list[float]] - :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, - Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", - "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and - "FeatureCollection". - :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType - """ - - _validation = { - "coordinates": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "coordinates": {"key": "coordinates", "type": "[[float]]"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, *, coordinates: List[List[float]], **kwargs): - """ - :keyword coordinates: Coordinates for the ``GeoJson MultiPoint`` geometry. Required. - :paramtype coordinates: list[list[float]] - """ - super().__init__(coordinates=coordinates, **kwargs) - self.coordinates = coordinates - self.type = "MultiPoint" # type: str - - -class GeoJsonMultiPolygonData(_serialization.Model): - """GeoJsonMultiPolygonData. - - All required parameters must be populated in order to send to Azure. - - :ivar coordinates: Contains a list of valid ``GeoJSON Polygon`` objects. **Note** that - coordinates in GeoJSON are in x, y order (longitude, latitude). Required. - :vartype coordinates: list[list[list[list[float]]]] - """ - - _validation = { - "coordinates": {"required": True}, - } - - _attribute_map = { - "coordinates": {"key": "coordinates", "type": "[[[[float]]]]"}, - } - - def __init__(self, *, coordinates: List[List[List[List[float]]]], **kwargs): - """ - :keyword coordinates: Contains a list of valid ``GeoJSON Polygon`` objects. **Note** that - coordinates in GeoJSON are in x, y order (longitude, latitude). Required. - :paramtype coordinates: list[list[list[list[float]]]] - """ - super().__init__(**kwargs) - self.coordinates = coordinates - - -class GeoJsonMultiPolygon(GeoJsonGeometry, GeoJsonMultiPolygonData): - """A valid ``GeoJSON MultiPolygon`` object type. Please refer to `RFC 7946 `_ for details. - - All required parameters must be populated in order to send to Azure. - - :ivar coordinates: Contains a list of valid ``GeoJSON Polygon`` objects. **Note** that - coordinates in GeoJSON are in x, y order (longitude, latitude). Required. - :vartype coordinates: list[list[list[list[float]]]] - :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, - Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", - "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and - "FeatureCollection". - :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType - """ - - _validation = { - "coordinates": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "coordinates": {"key": "coordinates", "type": "[[[[float]]]]"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, *, coordinates: List[List[List[List[float]]]], **kwargs): - """ - :keyword coordinates: Contains a list of valid ``GeoJSON Polygon`` objects. **Note** that - coordinates in GeoJSON are in x, y order (longitude, latitude). Required. - :paramtype coordinates: list[list[list[list[float]]]] - """ - super().__init__(coordinates=coordinates, **kwargs) - self.coordinates = coordinates - self.type = "MultiPolygon" # type: str - - -class GeoJsonPointData(_serialization.Model): - """Data contained by a ``GeoJson Point``. - - All required parameters must be populated in order to send to Azure. - - :ivar coordinates: A ``Position`` is an array of numbers with two or more elements. The first - two elements are *longitude* and *latitude*\ , precisely in that order. *Altitude/Elevation* is - an optional third element. Please refer to `RFC 7946 - `_ for details. Required. - :vartype coordinates: list[float] - """ - - _validation = { - "coordinates": {"required": True}, - } - - _attribute_map = { - "coordinates": {"key": "coordinates", "type": "[float]"}, - } - - def __init__(self, *, coordinates: List[float], **kwargs): - """ - :keyword coordinates: A ``Position`` is an array of numbers with two or more elements. The - first two elements are *longitude* and *latitude*\ , precisely in that order. - *Altitude/Elevation* is an optional third element. Please refer to `RFC 7946 - `_ for details. Required. - :paramtype coordinates: list[float] - """ - super().__init__(**kwargs) - self.coordinates = coordinates - - -class GeoJsonPoint(GeoJsonGeometry, GeoJsonPointData): - """A valid ``GeoJSON Point`` geometry type. Please refer to `RFC 7946 `_ for details. - - All required parameters must be populated in order to send to Azure. - - :ivar coordinates: A ``Position`` is an array of numbers with two or more elements. The first - two elements are *longitude* and *latitude*\ , precisely in that order. *Altitude/Elevation* is - an optional third element. Please refer to `RFC 7946 - `_ for details. Required. - :vartype coordinates: list[float] - :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, - Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", - "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and - "FeatureCollection". - :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType - """ - - _validation = { - "coordinates": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "coordinates": {"key": "coordinates", "type": "[float]"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, *, coordinates: List[float], **kwargs): - """ - :keyword coordinates: A ``Position`` is an array of numbers with two or more elements. The - first two elements are *longitude* and *latitude*\ , precisely in that order. - *Altitude/Elevation* is an optional third element. Please refer to `RFC 7946 - `_ for details. Required. - :paramtype coordinates: list[float] - """ - super().__init__(coordinates=coordinates, **kwargs) - self.coordinates = coordinates - self.type = "Point" # type: str - - -class GeoJsonPolygonData(_serialization.Model): - """GeoJsonPolygonData. - - All required parameters must be populated in order to send to Azure. - - :ivar coordinates: Coordinates for the ``GeoJson Polygon`` geometry type. Required. - :vartype coordinates: list[list[list[float]]] - """ - - _validation = { - "coordinates": {"required": True}, - } - - _attribute_map = { - "coordinates": {"key": "coordinates", "type": "[[[float]]]"}, - } - - def __init__(self, *, coordinates: List[List[List[float]]], **kwargs): - """ - :keyword coordinates: Coordinates for the ``GeoJson Polygon`` geometry type. Required. - :paramtype coordinates: list[list[list[float]]] - """ - super().__init__(**kwargs) - self.coordinates = coordinates - - -class GeoJsonPolygon(GeoJsonGeometry, GeoJsonPolygonData): - """A valid ``GeoJSON Polygon`` geometry type. Please refer to `RFC 7946 `_ for details. - - All required parameters must be populated in order to send to Azure. - - :ivar coordinates: Coordinates for the ``GeoJson Polygon`` geometry type. Required. - :vartype coordinates: list[list[list[float]]] - :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, - Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", - "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and - "FeatureCollection". - :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType - """ - - _validation = { - "coordinates": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "coordinates": {"key": "coordinates", "type": "[[[float]]]"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, *, coordinates: List[List[List[float]]], **kwargs): - """ - :keyword coordinates: Coordinates for the ``GeoJson Polygon`` geometry type. Required. - :paramtype coordinates: list[list[list[float]]] - """ - super().__init__(coordinates=coordinates, **kwargs) - self.coordinates = coordinates - self.type = "Polygon" # type: str - - -class LatLongPair(_serialization.Model): - """A location represented as a latitude and longitude. - - :ivar latitude: Latitude property. - :vartype latitude: float - :ivar longitude: Longitude property. - :vartype longitude: float - """ - - _attribute_map = { - "latitude": {"key": "latitude", "type": "float"}, - "longitude": {"key": "longitude", "type": "float"}, - } - - def __init__(self, *, latitude: Optional[float] = None, longitude: Optional[float] = None, **kwargs): - """ - :keyword latitude: Latitude property. - :paramtype latitude: float - :keyword longitude: Longitude property. - :paramtype longitude: float - """ - super().__init__(**kwargs) - self.latitude = latitude - self.longitude = longitude - - -class Route(_serialization.Model): - """Route. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar summary: Summary object. - :vartype summary: ~azure.maps.route.models.RouteSummary - :ivar legs: Legs array. - :vartype legs: list[~azure.maps.route.models.RouteLeg] - :ivar sections: Sections array. - :vartype sections: list[~azure.maps.route.models.RouteSection] - :ivar guidance: Contains guidance related elements. This field is present only when guidance - was requested and is available. - :vartype guidance: ~azure.maps.route.models.RouteGuidance - """ - - _validation = { - "summary": {"readonly": True}, - "legs": {"readonly": True}, - "sections": {"readonly": True}, - "guidance": {"readonly": True}, - } - - _attribute_map = { - "summary": {"key": "summary", "type": "RouteSummary"}, - "legs": {"key": "legs", "type": "[RouteLeg]"}, - "sections": {"key": "sections", "type": "[RouteSection]"}, - "guidance": {"key": "guidance", "type": "RouteGuidance"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.summary = None - self.legs = None - self.sections = None - self.guidance = None - - -class RouteDirectionParameters(_serialization.Model): - """Post body parameters for Route directions. - - :ivar supporting_points: A GeoJSON Geometry collection representing sequence of coordinates - used as input for route reconstruction and for calculating zero or more alternative routes to - this reference route. - - - * The provided sequence of supporting points is used as input for route reconstruction. - * The alternative routes are calculated between the origin and destination points specified in - the base path parameter locations. - * If both *minDeviationDistance* and *minDeviationTime* are set to zero, then these origin and - destination points are - expected to be at (or very near) the beginning and end of the reference route, respectively. - * Intermediate locations (\ *waypoints*\ ) are not supported when using - :code:`<_supportingPoints_>`. - * The reference route may contain traffic incidents of type _ROAD\ *CLOSURE*\ , which are - ignored for the calculation of the reference route's travel time and traffic delay. - Please refer to `Supporting Points - `_ - for details. - :vartype supporting_points: ~azure.maps.route.models.GeoJsonGeometryCollection - :ivar avoid_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of - countries in which all toll roads with vignettes are to be avoided, e.g. "AUS,CHE". Toll roads - with vignettes in countries not in the list are unaffected. Note: It is an error to specify - both **avoidVignette** and **allowVignette**. - :vartype avoid_vignette: list[str] - :ivar allow_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of - countries in which toll roads with vignettes are allowed, e.g. "AUS,CHE". Specifying - **allowVignette** with some countries X is equivalent to specifying **avoidVignette** with all - countries but X. Specifying **allowVignette** with an empty list is the same as avoiding all - toll roads with vignettes. Note: It is an error to specify both **avoidVignette** and - **allowVignette**. - :vartype allow_vignette: list[str] - :ivar avoid_areas: A GeoJSON MultiPolygon representing list of areas to avoid. Only rectangle - polygons are supported. The maximum size of a rectangle is about 160x160 km. Maximum number of - avoided areas is **10**. It cannot cross the 180th meridian. It must be between -80 and +80 - degrees of latitude. - :vartype avoid_areas: ~azure.maps.route.models.GeoJsonMultiPolygon - """ - - _attribute_map = { - "supporting_points": {"key": "supportingPoints", "type": "GeoJsonGeometryCollection"}, - "avoid_vignette": {"key": "avoidVignette", "type": "[str]"}, - "allow_vignette": {"key": "allowVignette", "type": "[str]"}, - "avoid_areas": {"key": "avoidAreas", "type": "GeoJsonMultiPolygon"}, - } - - def __init__( - self, - *, - supporting_points: Optional["_models.GeoJsonGeometryCollection"] = None, - avoid_vignette: Optional[List[str]] = None, - allow_vignette: Optional[List[str]] = None, - avoid_areas: Optional["_models.GeoJsonMultiPolygon"] = None, - **kwargs - ): - """ - :keyword supporting_points: A GeoJSON Geometry collection representing sequence of coordinates - used as input for route reconstruction and for calculating zero or more alternative routes to - this reference route. - - - * The provided sequence of supporting points is used as input for route reconstruction. - * The alternative routes are calculated between the origin and destination points specified in - the base path parameter locations. - * If both *minDeviationDistance* and *minDeviationTime* are set to zero, then these origin and - destination points are - expected to be at (or very near) the beginning and end of the reference route, respectively. - * Intermediate locations (\ *waypoints*\ ) are not supported when using - :code:`<_supportingPoints_>`. - * The reference route may contain traffic incidents of type _ROAD\ *CLOSURE*\ , which are - ignored for the calculation of the reference route's travel time and traffic delay. - Please refer to `Supporting Points - `_ - for details. - :paramtype supporting_points: ~azure.maps.route.models.GeoJsonGeometryCollection - :keyword avoid_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of - countries in which all toll roads with vignettes are to be avoided, e.g. "AUS,CHE". Toll roads - with vignettes in countries not in the list are unaffected. Note: It is an error to specify - both **avoidVignette** and **allowVignette**. - :paramtype avoid_vignette: list[str] - :keyword allow_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of - countries in which toll roads with vignettes are allowed, e.g. "AUS,CHE". Specifying - **allowVignette** with some countries X is equivalent to specifying **avoidVignette** with all - countries but X. Specifying **allowVignette** with an empty list is the same as avoiding all - toll roads with vignettes. Note: It is an error to specify both **avoidVignette** and - **allowVignette**. - :paramtype allow_vignette: list[str] - :keyword avoid_areas: A GeoJSON MultiPolygon representing list of areas to avoid. Only - rectangle polygons are supported. The maximum size of a rectangle is about 160x160 km. Maximum - number of avoided areas is **10**. It cannot cross the 180th meridian. It must be between -80 - and +80 degrees of latitude. - :paramtype avoid_areas: ~azure.maps.route.models.GeoJsonMultiPolygon - """ - super().__init__(**kwargs) - self.supporting_points = supporting_points - self.avoid_vignette = avoid_vignette - self.allow_vignette = allow_vignette - self.avoid_areas = avoid_areas - - -class RouteDirections(_serialization.Model): - """This object is returned from a successful Route Directions call. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar format_version: Format Version property. - :vartype format_version: str - :ivar routes: Routes array. - :vartype routes: list[~azure.maps.route.models.Route] - :ivar optimized_waypoints: Optimized sequence of waypoints. It shows the index from the user - provided waypoint sequence for the original and optimized list. For instance, a response: - - .. code-block:: - - - - - - - - means that the original sequence is [0, 1, 2] and optimized sequence is [1, 2, 0]. Since the - index starts by 0 the original is "first, second, third" while the optimized is "second, third, - first". - :vartype optimized_waypoints: list[~azure.maps.route.models.RouteOptimizedWaypoint] - :ivar report: Reports the effective settings used in the current call. - :vartype report: ~azure.maps.route.models.RouteReport - """ - - _validation = { - "format_version": {"readonly": True}, - "routes": {"readonly": True}, - "optimized_waypoints": {"readonly": True}, - } - - _attribute_map = { - "format_version": {"key": "formatVersion", "type": "str"}, - "routes": {"key": "routes", "type": "[Route]"}, - "optimized_waypoints": {"key": "optimizedWaypoints", "type": "[RouteOptimizedWaypoint]"}, - "report": {"key": "report", "type": "RouteReport"}, - } - - def __init__(self, *, report: Optional["_models.RouteReport"] = None, **kwargs): - """ - :keyword report: Reports the effective settings used in the current call. - :paramtype report: ~azure.maps.route.models.RouteReport - """ - super().__init__(**kwargs) - self.format_version = None - self.routes = None - self.optimized_waypoints = None - self.report = report - - -class RouteDirectionsBatchItem(BatchResultItem): - """An item returned from Route Directions Batch service call. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar status_code: HTTP request status code. - :vartype status_code: int - :ivar response: The result of the query. RouteDirections if the query completed successfully, - ErrorResponse otherwise. - :vartype response: ~azure.maps.route.models.RouteDirectionsBatchItemResponse - """ - - _validation = { - "status_code": {"readonly": True}, - "response": {"readonly": True}, - } - - _attribute_map = { - "status_code": {"key": "statusCode", "type": "int"}, - "response": {"key": "response", "type": "RouteDirectionsBatchItemResponse"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.response = None - - -class RouteDirectionsBatchItemResponse(RouteDirections, ErrorResponse): - """The result of the query. RouteDirections if the query completed successfully, ErrorResponse otherwise. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar error: The error object. - :vartype error: ~azure.maps.route.models.ErrorDetail - :ivar format_version: Format Version property. - :vartype format_version: str - :ivar routes: Routes array. - :vartype routes: list[~azure.maps.route.models.Route] - :ivar optimized_waypoints: Optimized sequence of waypoints. It shows the index from the user - provided waypoint sequence for the original and optimized list. For instance, a response: - - .. code-block:: - - - - - - - - means that the original sequence is [0, 1, 2] and optimized sequence is [1, 2, 0]. Since the - index starts by 0 the original is "first, second, third" while the optimized is "second, third, - first". - :vartype optimized_waypoints: list[~azure.maps.route.models.RouteOptimizedWaypoint] - :ivar report: Reports the effective settings used in the current call. - :vartype report: ~azure.maps.route.models.RouteReport - """ - - _validation = { - "format_version": {"readonly": True}, - "routes": {"readonly": True}, - "optimized_waypoints": {"readonly": True}, - } - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, - "format_version": {"key": "formatVersion", "type": "str"}, - "routes": {"key": "routes", "type": "[Route]"}, - "optimized_waypoints": {"key": "optimizedWaypoints", "type": "[RouteOptimizedWaypoint]"}, - "report": {"key": "report", "type": "RouteReport"}, - } - - def __init__( - self, *, error: Optional["_models.ErrorDetail"] = None, report: Optional["_models.RouteReport"] = None, **kwargs - ): - """ - :keyword error: The error object. - :paramtype error: ~azure.maps.route.models.ErrorDetail - :keyword report: Reports the effective settings used in the current call. - :paramtype report: ~azure.maps.route.models.RouteReport - """ - super().__init__(report=report, error=error, **kwargs) - self.error = error - self.format_version = None - self.routes = None - self.optimized_waypoints = None - self.report = report - - -class RouteDirectionsBatchResult(BatchResult): - """This object is returned from a successful Route Directions Batch service call. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar batch_summary: Summary of the results for the batch request. - :vartype batch_summary: ~azure.maps.route.models.BatchResultSummary - :ivar batch_items: Array containing the batch results. - :vartype batch_items: list[~azure.maps.route.models.RouteDirectionsBatchItem] - """ - - _validation = { - "batch_summary": {"readonly": True}, - "batch_items": {"readonly": True}, - } - - _attribute_map = { - "batch_summary": {"key": "summary", "type": "BatchResultSummary"}, - "batch_items": {"key": "batchItems", "type": "[RouteDirectionsBatchItem]"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.batch_items = None - - -class RouteGuidance(_serialization.Model): - """Contains guidance related elements. This field is present only when guidance was requested and is available. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar instructions: A list of instructions describing maneuvers. - :vartype instructions: list[~azure.maps.route.models.RouteInstruction] - :ivar instruction_groups: Groups a sequence of instruction elements which are related to each - other. - :vartype instruction_groups: list[~azure.maps.route.models.RouteInstructionGroup] - """ - - _validation = { - "instructions": {"readonly": True}, - "instruction_groups": {"readonly": True}, - } - - _attribute_map = { - "instructions": {"key": "instructions", "type": "[RouteInstruction]"}, - "instruction_groups": {"key": "instructionGroups", "type": "[RouteInstructionGroup]"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.instructions = None - self.instruction_groups = None - - -class RouteInstruction(_serialization.Model): # pylint: disable=too-many-instance-attributes - """A set of attributes describing a maneuver, e.g. 'Turn right', 'Keep left', 'Take the ferry', 'Take the motorway', 'Arrive'. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar route_offset_in_meters: Distance from the start of the route to the point of the - instruction. - :vartype route_offset_in_meters: int - :ivar travel_time_in_seconds: Estimated travel time up to the point corresponding to - routeOffsetInMeters. - :vartype travel_time_in_seconds: int - :ivar point: A location represented as a latitude and longitude. - :vartype point: ~azure.maps.route.models.LatLongPair - :ivar point_index: The index of the point in the list of polyline "points" corresponding to the - point of the instruction. - :vartype point_index: int - :ivar instruction_type: Type of the instruction, e.g., turn or change of road form. Known - values are: "TURN", "ROAD_CHANGE", "LOCATION_DEPARTURE", "LOCATION_ARRIVAL", "DIRECTION_INFO", - and "LOCATION_WAYPOINT". - :vartype instruction_type: str or ~azure.maps.route.models.GuidanceInstructionType - :ivar road_numbers: The road number(s) of the next significant road segment(s) after the - maneuver, or of the road(s) to be followed. Example: ["E34", "N205"]. - :vartype road_numbers: list[str] - :ivar exit_number: The number(s) of a highway exit taken by the current maneuver. If an exit - has multiple exit numbers, they will be separated by "," and possibly aggregated by "-", e.g., - "10, 13-15". - :vartype exit_number: str - :ivar street: Street name of the next significant road segment after the maneuver, or of the - street that should be followed. - :vartype street: str - :ivar signpost_text: The text on a signpost which is most relevant to the maneuver, or to the - direction that should be followed. - :vartype signpost_text: str - :ivar country_code: 3-character `ISO 3166-1 `_ - alpha-3 country code. E.g. USA. - :vartype country_code: str - :ivar state_code: A subdivision (e.g., state) of the country, represented by the second part of - an `ISO 3166-2 `_ code. This is only available for - some countries like the US, Canada, and Mexico. - :vartype state_code: str - :ivar junction_type: The type of the junction where the maneuver takes place. For larger - roundabouts, two separate instructions are generated for entering and leaving the roundabout. - Known values are: "REGULAR", "ROUNDABOUT", and "BIFURCATION". - :vartype junction_type: str or ~azure.maps.route.models.JunctionType - :ivar turn_angle_in_degrees: Indicates the direction of an instruction. If junctionType - indicates a turn instruction: - - - * 180 = U-turn - * [-179, -1] = Left turn - * 0 = Straight on (a '0 degree' turn) - * [1, 179] = Right turn - - If junctionType indicates a bifurcation instruction: - - - * <0 - keep left - * >0 - keep right. - :vartype turn_angle_in_degrees: int - :ivar roundabout_exit_number: This indicates which exit to take at a roundabout. - :vartype roundabout_exit_number: str - :ivar possible_combine_with_next: It is possible to optionally combine the instruction with the - next one. This can be used to build messages like "Turn left and then turn right". - :vartype possible_combine_with_next: bool - :ivar driving_side: Indicates left-hand vs. right-hand side driving at the point of the - maneuver. Known values are: "LEFT" and "RIGHT". - :vartype driving_side: str or ~azure.maps.route.models.DrivingSide - :ivar maneuver: A code identifying the maneuver. Known values are: "ARRIVE", "ARRIVE_LEFT", - "ARRIVE_RIGHT", "DEPART", "STRAIGHT", "KEEP_RIGHT", "BEAR_RIGHT", "TURN_RIGHT", "SHARP_RIGHT", - "KEEP_LEFT", "BEAR_LEFT", "TURN_LEFT", "SHARP_LEFT", "MAKE_UTURN", "ENTER_MOTORWAY", - "ENTER_FREEWAY", "ENTER_HIGHWAY", "TAKE_EXIT", "MOTORWAY_EXIT_LEFT", "MOTORWAY_EXIT_RIGHT", - "TAKE_FERRY", "ROUNDABOUT_CROSS", "ROUNDABOUT_RIGHT", "ROUNDABOUT_LEFT", "ROUNDABOUT_BACK", - "TRY_MAKE_UTURN", "FOLLOW", "SWITCH_PARALLEL_ROAD", "SWITCH_MAIN_ROAD", "ENTRANCE_RAMP", - "WAYPOINT_LEFT", "WAYPOINT_RIGHT", and "WAYPOINT_REACHED". - :vartype maneuver: str or ~azure.maps.route.models.GuidanceManeuver - :ivar message: A human-readable message for the maneuver. - :vartype message: str - :ivar combined_message: A human-readable message for the maneuver combined with the message - from the next instruction. Sometimes it is possible to combine two successive instructions into - a single instruction making it easier to follow. When this is the case the - possibleCombineWithNext flag will be true. For example: - - .. code-block:: - - 10. Turn left onto Einsteinweg/A10/E22 towards Ring Amsterdam - 11. Follow Einsteinweg/A10/E22 towards Ring Amsterdam - - The possibleCombineWithNext flag on instruction 10 is true. This indicates to the clients of - coded guidance that it can be combined with instruction 11. The instructions will be combined - automatically for clients requesting human-readable guidance. The combinedMessage field - contains the combined message: - - .. code-block:: - - Turn left onto Einsteinweg/A10/E22 towards Ring Amsterdam - then follow Einsteinweg/A10/E22 towards Ring Amsterdam. - :vartype combined_message: str - """ - - _validation = { - "route_offset_in_meters": {"readonly": True}, - "travel_time_in_seconds": {"readonly": True}, - "point_index": {"readonly": True}, - "road_numbers": {"readonly": True}, - "exit_number": {"readonly": True}, - "street": {"readonly": True}, - "signpost_text": {"readonly": True}, - "country_code": {"readonly": True}, - "state_code": {"readonly": True}, - "junction_type": {"readonly": True}, - "turn_angle_in_degrees": {"readonly": True}, - "roundabout_exit_number": {"readonly": True}, - "possible_combine_with_next": {"readonly": True}, - "driving_side": {"readonly": True}, - "maneuver": {"readonly": True}, - "message": {"readonly": True}, - "combined_message": {"readonly": True}, - } - - _attribute_map = { - "route_offset_in_meters": {"key": "routeOffsetInMeters", "type": "int"}, - "travel_time_in_seconds": {"key": "travelTimeInSeconds", "type": "int"}, - "point": {"key": "point", "type": "LatLongPair"}, - "point_index": {"key": "pointIndex", "type": "int"}, - "instruction_type": {"key": "instructionType", "type": "str"}, - "road_numbers": {"key": "roadNumbers", "type": "[str]"}, - "exit_number": {"key": "exitNumber", "type": "str"}, - "street": {"key": "street", "type": "str"}, - "signpost_text": {"key": "signpostText", "type": "str"}, - "country_code": {"key": "countryCode", "type": "str"}, - "state_code": {"key": "stateCode", "type": "str"}, - "junction_type": {"key": "junctionType", "type": "str"}, - "turn_angle_in_degrees": {"key": "turnAngleInDecimalDegrees", "type": "int"}, - "roundabout_exit_number": {"key": "roundaboutExitNumber", "type": "str"}, - "possible_combine_with_next": {"key": "possibleCombineWithNext", "type": "bool"}, - "driving_side": {"key": "drivingSide", "type": "str"}, - "maneuver": {"key": "maneuver", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "combined_message": {"key": "combinedMessage", "type": "str"}, - } - - def __init__( - self, - *, - point: Optional["_models.LatLongPair"] = None, - instruction_type: Optional[Union[str, "_models.GuidanceInstructionType"]] = None, - **kwargs - ): - """ - :keyword point: A location represented as a latitude and longitude. - :paramtype point: ~azure.maps.route.models.LatLongPair - :keyword instruction_type: Type of the instruction, e.g., turn or change of road form. Known - values are: "TURN", "ROAD_CHANGE", "LOCATION_DEPARTURE", "LOCATION_ARRIVAL", "DIRECTION_INFO", - and "LOCATION_WAYPOINT". - :paramtype instruction_type: str or ~azure.maps.route.models.GuidanceInstructionType - """ - super().__init__(**kwargs) - self.route_offset_in_meters = None - self.travel_time_in_seconds = None - self.point = point - self.point_index = None - self.instruction_type = instruction_type - self.road_numbers = None - self.exit_number = None - self.street = None - self.signpost_text = None - self.country_code = None - self.state_code = None - self.junction_type = None - self.turn_angle_in_degrees = None - self.roundabout_exit_number = None - self.possible_combine_with_next = None - self.driving_side = None - self.maneuver = None - self.message = None - self.combined_message = None - - -class RouteInstructionGroup(_serialization.Model): - """Groups a sequence of instruction elements which are related to each other. The sequence range is constrained with firstInstructionIndex and lastInstructionIndex. When human-readable text messages are requested for guidance (instructionType=text or tagged), then the instructionGroup has a summary message returned when available. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar first_instruction_index: Index of the first instruction in the instructions and belonging - to this group. - :vartype first_instruction_index: int - :ivar last_instruction_index: Index of the last instruction in the instructions and belonging - to this group. - :vartype last_instruction_index: int - :ivar group_length_in_meters: Length of the group. - :vartype group_length_in_meters: int - :ivar group_message: Summary message when human-readable text messages are requested for - guidance (instructionType=text or tagged). - :vartype group_message: str - """ - - _validation = { - "first_instruction_index": {"readonly": True}, - "last_instruction_index": {"readonly": True}, - "group_length_in_meters": {"readonly": True}, - "group_message": {"readonly": True}, - } - - _attribute_map = { - "first_instruction_index": {"key": "firstInstructionIndex", "type": "int"}, - "last_instruction_index": {"key": "lastInstructionIndex", "type": "int"}, - "group_length_in_meters": {"key": "groupLengthInMeters", "type": "int"}, - "group_message": {"key": "groupMessage", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.first_instruction_index = None - self.last_instruction_index = None - self.group_length_in_meters = None - self.group_message = None - - -class RouteLeg(_serialization.Model): - """A description of a part of a route, comprised of a list of points. Each additional waypoint provided in the request will result in an additional leg in the returned route. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar summary: Summary object for route section. - :vartype summary: ~azure.maps.route.models.RouteLegSummary - :ivar points: Points array. - :vartype points: list[~azure.maps.route.models.LatLongPair] - """ - - _validation = { - "summary": {"readonly": True}, - "points": {"readonly": True}, - } - - _attribute_map = { - "summary": {"key": "summary", "type": "RouteLegSummary"}, - "points": {"key": "points", "type": "[LatLongPair]"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.summary = None - self.points = None - - -class RouteLegSummary(_serialization.Model): - """Summary object for route section. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar length_in_meters: Length In Meters property. - :vartype length_in_meters: int - :ivar travel_time_in_seconds: Estimated travel time in seconds property that includes the delay - due to real-time traffic. Note that even when traffic=false travelTimeInSeconds still includes - the delay due to traffic. If DepartAt is in the future, travel time is calculated using - time-dependent historic traffic data. - :vartype travel_time_in_seconds: int - :ivar traffic_delay_in_seconds: Estimated delay in seconds caused by the real-time incident(s) - according to traffic information. For routes planned with departure time in the future, delays - is always 0. To return additional travel times using different types of traffic information, - parameter computeTravelTimeFor=all needs to be added. - :vartype traffic_delay_in_seconds: int - :ivar departure_time: The estimated departure time for the route or leg. - :vartype departure_time: ~datetime.datetime - :ivar arrival_time: The estimated arrival time for the route or leg. - :vartype arrival_time: ~datetime.datetime - :ivar no_traffic_travel_time_in_seconds: Estimated travel time calculated as if there are no - delays on the route due to traffic conditions (e.g. congestion). Included only if - computeTravelTimeFor = all is used in the query. - :vartype no_traffic_travel_time_in_seconds: int - :ivar historic_traffic_travel_time_in_seconds: Estimated travel time calculated using - time-dependent historic traffic data. Included only if computeTravelTimeFor = all is used in - the query. - :vartype historic_traffic_travel_time_in_seconds: int - :ivar live_traffic_incidents_travel_time_in_seconds: Estimated travel time calculated using - real-time speed data. Included only if computeTravelTimeFor = all is used in the query. - :vartype live_traffic_incidents_travel_time_in_seconds: int - :ivar fuel_consumption_in_liters: Estimated fuel consumption in liters using the Combustion - Consumption Model. Included if vehicleEngineType is set to *combustion* and - constantSpeedConsumptionInLitersPerHundredkm is specified. The value will be non-negative. - :vartype fuel_consumption_in_liters: float - :ivar battery_consumption_in_kw_h: Estimated electric energy consumption in kilowatt hours - (kWh) using the Electric Consumption Model. Included if vehicleEngineType is set to electric - and constantSpeedConsumptionInkWhPerHundredkm is specified. The value of - batteryConsumptionInkWh includes the recuperated electric energy and can therefore be negative - (which indicates gaining energy). If both maxChargeInkWh and currentChargeInkWh are specified, - recuperation will be capped to ensure that the battery charge level never exceeds - maxChargeInkWh. If neither maxChargeInkWh nor currentChargeInkWh are specified, unconstrained - recuperation is assumed in the consumption calculation. - :vartype battery_consumption_in_kw_h: float - """ - - _validation = { - "length_in_meters": {"readonly": True}, - "travel_time_in_seconds": {"readonly": True}, - "traffic_delay_in_seconds": {"readonly": True}, - "departure_time": {"readonly": True}, - "arrival_time": {"readonly": True}, - "no_traffic_travel_time_in_seconds": {"readonly": True}, - "historic_traffic_travel_time_in_seconds": {"readonly": True}, - "live_traffic_incidents_travel_time_in_seconds": {"readonly": True}, - "fuel_consumption_in_liters": {"readonly": True}, - "battery_consumption_in_kw_h": {"readonly": True}, - } - - _attribute_map = { - "length_in_meters": {"key": "lengthInMeters", "type": "int"}, - "travel_time_in_seconds": {"key": "travelTimeInSeconds", "type": "int"}, - "traffic_delay_in_seconds": {"key": "trafficDelayInSeconds", "type": "int"}, - "departure_time": {"key": "departureTime", "type": "iso-8601"}, - "arrival_time": {"key": "arrivalTime", "type": "iso-8601"}, - "no_traffic_travel_time_in_seconds": {"key": "noTrafficTravelTimeInSeconds", "type": "int"}, - "historic_traffic_travel_time_in_seconds": {"key": "historicTrafficTravelTimeInSeconds", "type": "int"}, - "live_traffic_incidents_travel_time_in_seconds": { - "key": "liveTrafficIncidentsTravelTimeInSeconds", - "type": "int", - }, - "fuel_consumption_in_liters": {"key": "fuelConsumptionInLiters", "type": "float"}, - "battery_consumption_in_kw_h": {"key": "batteryConsumptionInkWh", "type": "float"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.length_in_meters = None - self.travel_time_in_seconds = None - self.traffic_delay_in_seconds = None - self.departure_time = None - self.arrival_time = None - self.no_traffic_travel_time_in_seconds = None - self.historic_traffic_travel_time_in_seconds = None - self.live_traffic_incidents_travel_time_in_seconds = None - self.fuel_consumption_in_liters = None - self.battery_consumption_in_kw_h = None - - -class RouteMatrix(_serialization.Model): - """Matrix result object. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar status_code: StatusCode property for the current cell in the input matrix. - :vartype status_code: int - :ivar response: Response object of the current cell in the input matrix. - :vartype response: ~azure.maps.route.models.RouteMatrixResultResponse - """ - - _validation = { - "status_code": {"readonly": True}, - "response": {"readonly": True}, - } - - _attribute_map = { - "status_code": {"key": "statusCode", "type": "int"}, - "response": {"key": "response", "type": "RouteMatrixResultResponse"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.status_code = None - self.response = None - - -class RouteMatrixQuery(_serialization.Model): - """An object with a matrix of coordinates. - - :ivar origins: A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 - `_ for details. - :vartype origins: ~azure.maps.route.models.GeoJsonMultiPoint - :ivar destinations: A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 - `_ for details. - :vartype destinations: ~azure.maps.route.models.GeoJsonMultiPoint - """ - - _attribute_map = { - "origins": {"key": "origins", "type": "GeoJsonMultiPoint"}, - "destinations": {"key": "destinations", "type": "GeoJsonMultiPoint"}, - } - - def __init__( - self, - *, - origins: Optional["_models.GeoJsonMultiPoint"] = None, - destinations: Optional["_models.GeoJsonMultiPoint"] = None, - **kwargs - ): - """ - :keyword origins: A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 - `_ for details. - :paramtype origins: ~azure.maps.route.models.GeoJsonMultiPoint - :keyword destinations: A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 - `_ for details. - :paramtype destinations: ~azure.maps.route.models.GeoJsonMultiPoint - """ - super().__init__(**kwargs) - self.origins = origins - self.destinations = destinations - - -class RouteMatrixResult(_serialization.Model): - """This object is returned from a successful Route Matrix call. For ex, if 2 origins and 3 destinations are provided, there are going to 2 arrays with 3 elements in each. Each element's content depends on the options provided in the query. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar format_version: Format Version property. - :vartype format_version: str - :ivar matrix: Results as a 2 dimensional array of route summaries. - :vartype matrix: list[list[~azure.maps.route.models.RouteMatrix]] - :ivar summary: Summary object. - :vartype summary: ~azure.maps.route.models.RouteMatrixSummary - """ - - _validation = { - "format_version": {"readonly": True}, - "matrix": {"readonly": True}, - "summary": {"readonly": True}, - } - - _attribute_map = { - "format_version": {"key": "formatVersion", "type": "str"}, - "matrix": {"key": "matrix", "type": "[[RouteMatrix]]"}, - "summary": {"key": "summary", "type": "RouteMatrixSummary"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.format_version = None - self.matrix = None - self.summary = None - - -class RouteMatrixResultResponse(_serialization.Model): - """Response object of the current cell in the input matrix. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar summary: Summary object for route section. - :vartype summary: ~azure.maps.route.models.RouteLegSummary - """ - - _validation = { - "summary": {"readonly": True}, - } - - _attribute_map = { - "summary": {"key": "routeSummary", "type": "RouteLegSummary"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.summary = None - - -class RouteMatrixSummary(_serialization.Model): - """Summary object. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar successful_routes: Number of successful routes in the response. - :vartype successful_routes: int - :ivar total_routes: Total number of routes requested. Number of cells in the input matrix. - :vartype total_routes: int - """ - - _validation = { - "successful_routes": {"readonly": True}, - "total_routes": {"readonly": True}, - } - - _attribute_map = { - "successful_routes": {"key": "successfulRoutes", "type": "int"}, - "total_routes": {"key": "totalRoutes", "type": "int"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.successful_routes = None - self.total_routes = None - - -class RouteOptimizedWaypoint(_serialization.Model): - """Optimized way point object. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provided_index: Way point index provided by the user. - :vartype provided_index: int - :ivar optimized_index: Optimized way point index from the system. - :vartype optimized_index: int - """ - - _validation = { - "provided_index": {"readonly": True}, - "optimized_index": {"readonly": True}, - } - - _attribute_map = { - "provided_index": {"key": "providedIndex", "type": "int"}, - "optimized_index": {"key": "optimizedIndex", "type": "int"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.provided_index = None - self.optimized_index = None - - -class RouteRange(_serialization.Model): - """Reachable Range. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar center: Center point of the reachable range. - :vartype center: ~azure.maps.route.models.LatLongPair - :ivar boundary: Polygon boundary of the reachable range represented as a list of points. - :vartype boundary: list[~azure.maps.route.models.LatLongPair] - """ - - _validation = { - "boundary": {"readonly": True}, - } - - _attribute_map = { - "center": {"key": "center", "type": "LatLongPair"}, - "boundary": {"key": "boundary", "type": "[LatLongPair]"}, - } - - def __init__(self, *, center: Optional["_models.LatLongPair"] = None, **kwargs): - """ - :keyword center: Center point of the reachable range. - :paramtype center: ~azure.maps.route.models.LatLongPair - """ - super().__init__(**kwargs) - self.center = center - self.boundary = None - - -class RouteRangeResult(_serialization.Model): - """This object is returned from a successful Route Reachable Range call. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar format_version: Format Version property. - :vartype format_version: str - :ivar reachable_range: Reachable Range. - :vartype reachable_range: ~azure.maps.route.models.RouteRange - :ivar report: Reports the effective settings used in the current call. - :vartype report: ~azure.maps.route.models.RouteReport - """ - - _validation = { - "format_version": {"readonly": True}, - } - - _attribute_map = { - "format_version": {"key": "formatVersion", "type": "str"}, - "reachable_range": {"key": "reachableRange", "type": "RouteRange"}, - "report": {"key": "report", "type": "RouteReport"}, - } - - def __init__( - self, - *, - reachable_range: Optional["_models.RouteRange"] = None, - report: Optional["_models.RouteReport"] = None, - **kwargs - ): - """ - :keyword reachable_range: Reachable Range. - :paramtype reachable_range: ~azure.maps.route.models.RouteRange - :keyword report: Reports the effective settings used in the current call. - :paramtype report: ~azure.maps.route.models.RouteReport - """ - super().__init__(**kwargs) - self.format_version = None - self.reachable_range = reachable_range - self.report = report - - -class RouteReport(_serialization.Model): - """Reports the effective settings used in the current call. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar effective_settings: Effective parameters or data used when calling this Route API. - :vartype effective_settings: list[~azure.maps.route.models.EffectiveSetting] - """ - - _validation = { - "effective_settings": {"readonly": True}, - } - - _attribute_map = { - "effective_settings": {"key": "effectiveSettings", "type": "[EffectiveSetting]"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.effective_settings = None - - -class RouteSection(_serialization.Model): - """Route sections contain additional information about parts of a route. Each section contains at least the elements ``startPointIndex``\ , ``endPointIndex``\ , and ``sectionType``. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar start_point_index: Index of the first point (offset 0) in the route this section applies - to. - :vartype start_point_index: int - :ivar end_point_index: Index of the last point (offset 0) in the route this section applies to. - :vartype end_point_index: int - :ivar section_type: Section types of the reported route response. Known values are: - "CAR_TRAIN", "COUNTRY", "FERRY", "MOTORWAY", "PEDESTRIAN", "TOLL_ROAD", "TOLL_VIGNETTE", - "TRAFFIC", "TRAVEL_MODE", "TUNNEL", "CARPOOL", and "URBAN". - :vartype section_type: str or ~azure.maps.route.models.ResponseSectionType - :ivar travel_mode: Travel mode for the calculated route. The value will be set to ``other`` if - the requested mode of transport is not possible in this section. Known values are: "car", - "truck", "taxi", "bus", "van", "motorcycle", "bicycle", "pedestrian", and "other". - :vartype travel_mode: str or ~azure.maps.route.models.ResponseTravelMode - :ivar simple_category: Type of the incident. Can currently be JAM, ROAD_WORK, ROAD_CLOSURE, or - OTHER. See "tec" for detailed information. Known values are: "JAM", "ROAD_WORK", - "ROAD_CLOSURE", and "OTHER". - :vartype simple_category: str or ~azure.maps.route.models.SimpleCategory - :ivar effective_speed_in_kmh: Effective speed of the incident in km/h, averaged over its entire - length. - :vartype effective_speed_in_kmh: int - :ivar delay_in_seconds: Delay in seconds caused by the incident. - :vartype delay_in_seconds: int - :ivar delay_magnitude: The magnitude of delay caused by the incident. These values correspond - to the values of the response field ty of the `Get Traffic Incident Detail API - `_. Known values - are: "0", "1", "2", "3", and "4". - :vartype delay_magnitude: str or ~azure.maps.route.models.DelayMagnitude - :ivar tec: Details of the traffic event, using definitions in the `TPEG2-TEC - `_ standard. Can contain effectCode and causes - elements. - :vartype tec: ~azure.maps.route.models.RouteSectionTec - """ - - _validation = { - "start_point_index": {"readonly": True}, - "end_point_index": {"readonly": True}, - "section_type": {"readonly": True}, - "travel_mode": {"readonly": True}, - "simple_category": {"readonly": True}, - "effective_speed_in_kmh": {"readonly": True}, - "delay_in_seconds": {"readonly": True}, - "delay_magnitude": {"readonly": True}, - } - - _attribute_map = { - "start_point_index": {"key": "startPointIndex", "type": "int"}, - "end_point_index": {"key": "endPointIndex", "type": "int"}, - "section_type": {"key": "sectionType", "type": "str"}, - "travel_mode": {"key": "travelMode", "type": "str"}, - "simple_category": {"key": "simpleCategory", "type": "str"}, - "effective_speed_in_kmh": {"key": "effectiveSpeedInKmh", "type": "int"}, - "delay_in_seconds": {"key": "delayInSeconds", "type": "int"}, - "delay_magnitude": {"key": "magnitudeOfDelay", "type": "str"}, - "tec": {"key": "tec", "type": "RouteSectionTec"}, - } - - def __init__(self, *, tec: Optional["_models.RouteSectionTec"] = None, **kwargs): - """ - :keyword tec: Details of the traffic event, using definitions in the `TPEG2-TEC - `_ standard. Can contain effectCode and causes - elements. - :paramtype tec: ~azure.maps.route.models.RouteSectionTec - """ - super().__init__(**kwargs) - self.start_point_index = None - self.end_point_index = None - self.section_type = None - self.travel_mode = None - self.simple_category = None - self.effective_speed_in_kmh = None - self.delay_in_seconds = None - self.delay_magnitude = None - self.tec = tec - - -class RouteSectionTec(_serialization.Model): - """Details of the traffic event, using definitions in the `TPEG2-TEC `_ standard. Can contain effectCode and causes elements. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar effect_code: The effect on the traffic flow. Contains a value in the tec001:EffectCode - table, as defined in the `TPEG2-TEC `_ standard. Can - be used to color-code traffic events according to severity. - :vartype effect_code: int - :ivar causes: Causes array. - :vartype causes: list[~azure.maps.route.models.RouteSectionTecCause] - """ - - _validation = { - "effect_code": {"readonly": True}, - } - - _attribute_map = { - "effect_code": {"key": "effectCode", "type": "int"}, - "causes": {"key": "causes", "type": "[RouteSectionTecCause]"}, - } - - def __init__(self, *, causes: Optional[List["_models.RouteSectionTecCause"]] = None, **kwargs): - """ - :keyword causes: Causes array. - :paramtype causes: list[~azure.maps.route.models.RouteSectionTecCause] - """ - super().__init__(**kwargs) - self.effect_code = None - self.causes = causes - - -class RouteSectionTecCause(_serialization.Model): - """The cause of the traffic event. Can contain mainCauseCode and subCauseCode elements. Can be used to define iconography and descriptions. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar main_cause_code: The main cause of the traffic event. Contains a value in the - tec002:CauseCode table, as defined in the `TPEG2-TEC - `_ standard. - :vartype main_cause_code: int - :ivar sub_cause_code: The subcause of the traffic event. Contains a value in the sub cause - table defined by the mainCauseCode, as defined in the `TPEG2-TEC - `_ standard. - :vartype sub_cause_code: int - """ - - _validation = { - "main_cause_code": {"readonly": True}, - "sub_cause_code": {"readonly": True}, - } - - _attribute_map = { - "main_cause_code": {"key": "mainCauseCode", "type": "int"}, - "sub_cause_code": {"key": "subCauseCode", "type": "int"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.main_cause_code = None - self.sub_cause_code = None - - -class RouteSummary(_serialization.Model): - """Summary object. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar length_in_meters: Length In Meters property. - :vartype length_in_meters: int - :ivar travel_time_in_seconds: Estimated travel time in seconds property that includes the delay - due to real-time traffic. Note that even when traffic=false travelTimeInSeconds still includes - the delay due to traffic. If DepartAt is in the future, travel time is calculated using - time-dependent historic traffic data. - :vartype travel_time_in_seconds: int - :ivar traffic_delay_in_seconds: Estimated delay in seconds caused by the real-time incident(s) - according to traffic information. For routes planned with departure time in the future, delays - is always 0. To return additional travel times using different types of traffic information, - parameter computeTravelTimeFor=all needs to be added. - :vartype traffic_delay_in_seconds: int - :ivar departure_time: The estimated departure time for the route or leg. - :vartype departure_time: ~datetime.datetime - :ivar arrival_time: The estimated arrival time for the route or leg. - :vartype arrival_time: ~datetime.datetime - """ - - _validation = { - "length_in_meters": {"readonly": True}, - "travel_time_in_seconds": {"readonly": True}, - "traffic_delay_in_seconds": {"readonly": True}, - "departure_time": {"readonly": True}, - "arrival_time": {"readonly": True}, - } - - _attribute_map = { - "length_in_meters": {"key": "lengthInMeters", "type": "int"}, - "travel_time_in_seconds": {"key": "travelTimeInSeconds", "type": "int"}, - "traffic_delay_in_seconds": {"key": "trafficDelayInSeconds", "type": "int"}, - "departure_time": {"key": "departureTime", "type": "iso-8601"}, - "arrival_time": {"key": "arrivalTime", "type": "iso-8601"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.length_in_meters = None - self.travel_time_in_seconds = None - self.traffic_delay_in_seconds = None - self.departure_time = None - self.arrival_time = None diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_patch.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_patch.py deleted file mode 100644 index f7dd32510333..000000000000 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/_patch.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/_patch.py deleted file mode 100644 index f7dd32510333..000000000000 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/py.typed b/sdk/maps/azure-maps-route/azure/maps/route/_generated/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_base_client.py b/sdk/maps/azure-maps-route/azure/maps/route/_patch.py similarity index 61% rename from sdk/maps/azure-maps-route/azure/maps/route/_base_client.py rename to sdk/maps/azure-maps-route/azure/maps/route/_patch.py index 4372c05dadf2..4620cbc00105 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/_base_client.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/_patch.py @@ -3,11 +3,27 @@ # Licensed under the MIT License. # ------------------------------------ -from typing import Union, Any -from azure.core.pipeline.policies import AzureKeyCredentialPolicy +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + +from typing import Union, Any, List + from azure.core.credentials import AzureKeyCredential, TokenCredential -from ._generated import MapsRouteClient as _MapsRouteClient -from ._version import API_VERSION +from azure.core.pipeline.policies import AzureKeyCredentialPolicy +from ._client import MapsRouteClient as MapsRouteClientGenerated + +__all__: List[str] = ["MapsRouteClient"] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ # To check the credential is either AzureKeyCredential or TokenCredential def _authentication_policy(credential): @@ -25,24 +41,18 @@ def _authentication_policy(credential): ) return authentication_policy -class MapsRouteClientBase: +# pylint: disable=C4748 +class MapsRouteClient(MapsRouteClientGenerated): def __init__( self, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any ) -> None: - self._maps_client = _MapsRouteClient( + super().__init__( credential=credential, # type: ignore - api_version=kwargs.pop("api_version", API_VERSION), + endpoint=kwargs.pop("endpoint", "https://atlas.microsoft.com"), + client_id=kwargs.pop("client_id", None), authentication_policy=kwargs.pop("authentication_policy", _authentication_policy(credential)), **kwargs ) - self._route_client = self._maps_client.route - - def __enter__(self): - self._maps_client.__enter__() # pylint:disable=no-member - return self - - def __exit__(self, *args): - self._maps_client.__exit__(*args) # pylint:disable=no-member diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_serialization.py b/sdk/maps/azure-maps-route/azure/maps/route/_serialization.py similarity index 77% rename from sdk/maps/azure-maps-route/azure/maps/route/_generated/_serialization.py rename to sdk/maps/azure-maps-route/azure/maps/route/_serialization.py index 7c1dedb5133d..7b3074215a30 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_serialization.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/_serialization.py @@ -24,7 +24,7 @@ # # -------------------------------------------------------------------------- -# pylint: skip-file +# pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode import calendar @@ -37,23 +37,37 @@ import re import sys import codecs +from typing import ( + Dict, + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + TypeVar, + MutableMapping, + Type, + List, +) try: from urllib import quote # type: ignore except ImportError: - from urllib.parse import quote # type: ignore + from urllib.parse import quote import xml.etree.ElementTree as ET -import isodate +import isodate # type: ignore -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping +ModelType = TypeVar("ModelType", bound="Model") +JSON = MutableMapping[str, Any] class RawDeserializer: @@ -65,8 +79,7 @@ class RawDeserializer: CONTEXT_NAME = "deserialized_data" @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: """Decode data according to content-type. Accept a stream of data as well, but will be load at once in memory for now. @@ -76,6 +89,8 @@ def deserialize_from_text(cls, data, content_type=None): :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 @@ -97,7 +112,7 @@ def deserialize_from_text(cls, data, content_type=None): 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: @@ -109,7 +124,7 @@ def deserialize_from_text(cls, data, content_type=None): 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 @@ -128,17 +143,23 @@ 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 - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: """Deserialize from HTTP response. Use bytes and headers to NOT use any requests/aiohttp or whatever specific implementation. Headers will tested for "content-type" + + :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 @@ -156,13 +177,6 @@ def deserialize_from_http_generics(cls, body_bytes, headers): return None -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - _LOGGER = logging.getLogger(__name__) try: @@ -175,20 +189,35 @@ class UTC(datetime.tzinfo): """Time Zone info for handling UTC""" def utcoffset(self, dt): - """UTF offset for UTC is 0.""" + """UTF offset for UTC is 0. + + :param datetime.datetime dt: The datetime + :returns: The offset + :rtype: datetime.timedelta + """ return datetime.timedelta(0) def tzname(self, dt): - """Timestamp representation.""" + """Timestamp representation. + + :param datetime.datetime dt: The datetime + :returns: The timestamp representation + :rtype: str + """ return "Z" def dst(self, dt): - """No daylight saving for UTC.""" + """No daylight saving for UTC. + + :param datetime.datetime dt: The datetime + :returns: The daylight saving time + :rtype: datetime.timedelta + """ return datetime.timedelta(hours=1) try: - from datetime import timezone as _FixedOffset + from datetime import timezone as _FixedOffset # type: ignore except ImportError: # Python 2.7 class _FixedOffset(datetime.tzinfo): # type: ignore @@ -219,31 +248,33 @@ def __getinitargs__(self): try: from datetime import timezone - TZ_UTC = timezone.utc # type: ignore + TZ_UTC = timezone.utc except ImportError: TZ_UTC = UTC() # type: ignore _FLATTEN = re.compile(r"(? None: + 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): @@ -290,43 +328,57 @@ def __init__(self, **kwargs): else: setattr(self, k, kwargs[k]) - def __eq__(self, other): - """Compare objects by comparing all attributes.""" + def __eq__(self, other: Any) -> bool: + """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): - """Compare objects by comparing all attributes.""" + def __ne__(self, other: Any) -> bool: + """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): + def __str__(self) -> str: return str(self.__dict__) @classmethod - def enable_additional_properties_sending(cls): + def enable_additional_properties_sending(cls) -> None: cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} @classmethod - def is_xml_model(cls): + def is_xml_model(cls) -> bool: try: - cls._xml_map + cls._xml_map # type: ignore except AttributeError: return False return True @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 + xml_map = cls._xml_map # type: ignore except AttributeError: xml_map = {} 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=False, **kwargs): - """Return the JSON that would be sent to azure from this model. + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """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)`. @@ -337,10 +389,17 @@ def serialize(self, keep_readonly=False, **kwargs): :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, keep_readonly=True, key_transformer=attribute_transformer, **kwargs): - """Return a dict that can be JSONify using json.dump. + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. Advanced usage might optionally use a callback as parameter: @@ -366,12 +425,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): @@ -381,25 +443,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, data, content_type=None): + def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: """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 + :rtype: ModelType """ 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, data, key_extractors=None, content_type=None): + def from_dict( + cls: Type[ModelType], + data: Any, + key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> ModelType: """Parse a dict using given key extractor return a model. By default consider key @@ -407,13 +475,15 @@ def from_dict(cls, data, key_extractors=None, content_type=None): and last_rest_key_case_insensitive_extractor) :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model :raises: DeserializationError if something went wrong + :rtype: ModelType """ deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( - [ + deserializer.key_extractors = ( # type: ignore + [ # type: ignore attribute_key_case_insensitive_extractor, rest_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, @@ -421,7 +491,7 @@ def from_dict(cls, data, key_extractors=None, content_type=None): 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): @@ -429,7 +499,7 @@ 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 @@ -437,6 +507,11 @@ 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 @@ -453,7 +528,7 @@ def _classify(cls, response, objects): return cls flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) try: - return objects[flatten_mapping_type[subtype_value]] + return objects[flatten_mapping_type[subtype_value]] # type: ignore except KeyError: _LOGGER.warning( "Subtype value %s has no mapping, use base class %s.", @@ -482,11 +557,13 @@ def _decode_attribute_map_key(key): inside the received data. :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str """ return key.replace("\\.", ".") -class Serializer(object): +class Serializer(object): # pylint: disable=too-many-public-methods """Request object model serializer.""" basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -521,7 +598,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -537,17 +614,20 @@ def __init__(self, classes=None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies = 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. + :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) @@ -573,12 +653,14 @@ def _serialize(self, target_obj, data_type=None, **kwargs): serialized = {} if is_xml_model_serialization: - serialized = target_obj._create_xml_node() + serialized = target_obj._create_xml_node() # pylint: disable=protected-access try: - attributes = target_obj._attribute_map + attributes = target_obj._attribute_map # pylint: disable=protected-access for attr, attr_desc in attributes.items(): attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): continue if attr_name == "additional_properties" and attr_desc["key"] == "": @@ -605,62 +687,63 @@ 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) - serialized.set(xml_name, new_attr) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore continue if xml_desc.get("text", False): - serialized.text = new_attr + serialized.text = new_attr # type: ignore continue if isinstance(new_attr, list): - serialized.extend(new_attr) + 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 new_attr.tag = "}".join([splitted_tag[0], xml_name]) else: new_attr.tag = xml_name - serialized.append(new_attr) + serialized.append(new_attr) # type: ignore else: # That's a basic type # Integrate namespace if necessary local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} _new_attr = new_attr _serialized = serialized - for k in keys: + for k in keys: # type: ignore if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] + _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 + :returns: The serialized request body """ # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) try: is_xml_model_serialization = kwargs["is_xml"] except KeyError: @@ -675,7 +758,7 @@ def body(self, data, data_type, **kwargs): # We're not able to deal with additional properties for now. deserializer.additional_properties_detection = False if is_xml_model_serialization: - deserializer.key_extractors = [ + deserializer.key_extractors = [ # type: ignore attribute_key_case_insensitive_extractor, ] else: @@ -684,18 +767,20 @@ 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 + :returns: The serialized URL path :raises: TypeError if serialization fails. :raises: ValueError if data is None """ @@ -706,30 +791,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 + :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) @@ -739,19 +824,20 @@ def query(self, name, data, data_type, **kwargs): output = str(output) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def header(self, name, data, data_type, **kwargs): """Serialize data intended for a request header. - :param data: The data to be serialized. + :param str name: The name of the header. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str :raises: TypeError if serialization fails. :raises: ValueError if data is None + :returns: The serialized header """ try: if data_type in ["[str]"]: @@ -760,30 +846,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. + :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 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 @@ -798,12 +885,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 @@ -819,23 +905,26 @@ def serialize_basic(cls, data, data_type, **kwargs): - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - is_xml bool : If set, use xml_basic_types_serializers - :param data: Object to be serialized. + :param obj data: Object to be serialized. :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec + return eval(data_type)(data) # nosec # pylint: disable=eval-used @classmethod def serialize_unicode(cls, data): """Special handling for serializing unicode strings in Py2. Encode to UTF-8 if unicode, otherwise handle as a str. - :param data: Object to be serialized. + :param str data: Object to be serialized. :rtype: str + :return: serialized object """ try: # If I received an enum, return its value return data.value @@ -843,14 +932,13 @@ def serialize_unicode(cls, data): pass try: - if isinstance(data, unicode): + if isinstance(data, unicode): # type: ignore # Don't change it, JSON and XML ElementTree are totally able # to serialize correctly u'' strings return data except NameError: return str(data) - else: - return str(data) + return str(data) def serialize_iter(self, data, iter_type, div=None, **kwargs): """Serialize iterable. @@ -860,13 +948,13 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): serialization_ctxt['type'] should be same as data_type. - is_xml bool : If set, serialize as XML - :param list attr: Object to be serialized. + :param list data: Object to be serialized. :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. :param str div: If set, this str will be used to combine the elements in the iterable into a combined string. Default is 'None'. + Defaults to False. :rtype: list, str + :return: serialized iterable """ if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") @@ -878,9 +966,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) @@ -916,16 +1009,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: @@ -940,7 +1034,7 @@ def serialize_dict(self, attr, dict_type, **kwargs): return serialized - def serialize_object(self, attr, **kwargs): + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Serialize a generic object. This will be handled as a dictionary. If object passed in is not a basic type (str, int, float, dict, list) it will simply be @@ -948,6 +1042,7 @@ def serialize_object(self, attr, **kwargs): :param dict attr: Object to be serialized. :rtype: dict or str + :return: serialized object """ if attr is None: return None @@ -958,7 +1053,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) @@ -972,7 +1067,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_decimal(attr) # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): + if obj_type in self.dependencies.values() or isinstance(attr, Model): return self._serialize(attr) if obj_type == dict: @@ -1001,58 +1096,63 @@ def serialize_enum(attr, enum_obj=None): except AttributeError: result = attr try: - enum_obj(result) + enum_obj(result) # type: ignore return result - except ValueError: - for enum_value in enum_obj: + 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) @@ -1060,11 +1160,12 @@ def serialize_date(attr, **kwargs): return t @staticmethod - def serialize_time(attr, **kwargs): + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument """Serialize Time object into ISO-8601 formatted string. :param datetime.time attr: Object to be serialized. :rtype: str + :return: serialized time """ if isinstance(attr, str): attr = isodate.parse_time(attr) @@ -1074,30 +1175,32 @@ def serialize_time(attr, **kwargs): return t @staticmethod - def serialize_duration(attr, **kwargs): + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument """Serialize TimeDelta object into ISO-8601 formatted string. :param TimeDelta attr: Object to be serialized. :rtype: str + :return: serialized duration """ if isinstance(attr, str): attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) @staticmethod - def serialize_rfc(attr, **kwargs): + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. :param Datetime attr: Object to be serialized. :rtype: str :raises: TypeError if format invalid. + :return: serialized rfc """ try: if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( Serializer.days[utc.tm_wday], @@ -1110,12 +1213,13 @@ def serialize_rfc(attr, **kwargs): ) @staticmethod - def serialize_iso(attr, **kwargs): + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into ISO-8601 formatted string. :param Datetime attr: Object to be serialized. :rtype: str :raises: SerializationError if format invalid. + :return: serialized iso """ if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -1135,19 +1239,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 + :return: serialied unix """ if isinstance(attr, int): return attr @@ -1155,16 +1260,17 @@ 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 while "." in key: - dict_keys = _FLATTEN.split(key) + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(List[str], _FLATTEN.split(key)) if len(dict_keys) == 1: key = _decode_attribute_map_key(dict_keys[0]) break @@ -1173,14 +1279,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 @@ -1194,7 +1301,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:]) @@ -1202,17 +1308,29 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): return attribute_key_case_insensitive_extractor(key, None, working_data) -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) return attribute_key_extractor(dict_keys[-1], None, data) -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument """Extract the attribute in "data" based on the last part of the JSON path key. This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) @@ -1245,11 +1363,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 @@ -1269,7 +1387,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): @@ -1301,22 +1419,21 @@ def xml_key_extractor(attr, attr_desc, data): if is_iter_type: if is_wrapped: return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list + return [] # not wrapped, assume empty list return None # Assume it's not there, maybe an optional node. # If is_iter_type and not wrapped, return all found children if is_iter_type: if not is_wrapped: return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( # pylint: disable=line-too-long + xml_name ) - return list(children[0]) # Might be empty list and that's ok. + ) + return list(children[0]) # Might be empty list and that's ok. # Here it's not a itertype, we should have found one element only or empty if len(children) > 1: @@ -1333,9 +1450,9 @@ class Deserializer(object): basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1355,7 +1472,7 @@ def __init__(self, classes=None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies = 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 @@ -1373,11 +1490,12 @@ def __call__(self, target_obj, response_data, content_type=None): :param str content_type: Swagger "produces" if available. :raises: DeserializationError if deserialization fails. :return: Deserialized object. + :rtype: object """ data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) - def _deserialize(self, target_obj, data): + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements """Call the deserializer on a model. Data needs to be already deserialized as JSON or XML ElementTree @@ -1386,12 +1504,13 @@ def _deserialize(self, target_obj, data): :param object data: Object to deserialize. :raises: DeserializationError if deserialization fails. :return: Deserialized object. + :rtype: object """ # This is already a model, go recursive just in case if hasattr(data, "_attribute_map"): constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] try: - for attr, mapconfig in data._attribute_map.items(): + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access if attr in constants: continue value = getattr(data, attr) @@ -1408,15 +1527,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 + 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"... @@ -1444,11 +1563,10 @@ def _deserialize(self, target_obj, data): value = self.deserialize_data(raw_value, attr_desc["type"]) d_attrs[attr] = value except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) + msg = "Unable to deserialize to object: " + class_name # type: ignore + 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: @@ -1474,22 +1592,24 @@ def _classify_target(self, target, data): Once classification has been determined, initialize object. :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :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__ + return target, target.__class__.__name__ # type: ignore def failsafe_deserialize(self, target_obj, data, content_type=None): """Ignores any errors encountered in deserialization, @@ -1499,12 +1619,14 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): a deserialization error. :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :param str/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 ) @@ -1522,10 +1644,12 @@ def _unpack_content(raw_data, content_type=None): If raw_data is something else, bypass all logic and return it directly. - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. :raises JSONDecodeError: If JSON is requested and parsing is impossible. :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. """ # Assume this is enough to detect a Pipeline Response without importing it context = getattr(raw_data, "context", {}) @@ -1542,21 +1666,28 @@ 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"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) + 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() if v.get("readonly") # pylint: disable=protected-access + ] + const = [ + k for k, v in response._validation.items() if v.get("constant") # pylint: disable=protected-access + ] kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} response_obj = response(**kwargs) for attr in readonly: @@ -1565,8 +1696,8 @@ def _instantiate_model(self, response, attrs, additional_properties=None): response_obj.additional_properties = additional_properties return response_obj except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err else: try: for attr, value in attrs.items(): @@ -1575,15 +1706,16 @@ def _instantiate_model(self, response, attrs, additional_properties=None): except Exception as exp: msg = "Unable to populate response model. " msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) + raise DeserializationError(msg) from exp - def deserialize_data(self, data, data_type): + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements """Process data for deserialization according to data type. :param str data: The response string to be deserialized. :param str data_type: The type to deserialize to. :raises: DeserializationError if deserialization fails. :return: Deserialized object. + :rtype: object """ if data is None: return data @@ -1597,7 +1729,11 @@ def deserialize_data(self, data, data_type): if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): return data - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: return None data_val = self.deserialize_type[data_type](data) @@ -1616,15 +1752,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: @@ -1641,6 +1777,7 @@ def deserialize_dict(self, attr, dict_type): :param dict/list attr: Dictionary to be deserialized. Also accepts a list of key, value pairs. :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. :rtype: dict """ if isinstance(attr, list): @@ -1651,11 +1788,12 @@ def deserialize_dict(self, attr, dict_type): attr = {el.tag: el.text for el in attr} return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - def deserialize_object(self, attr, **kwargs): + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Deserialize a generic object. This will be handled as a dictionary. :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. :rtype: dict :raises: TypeError if non-builtin datatype encountered. """ @@ -1664,7 +1802,7 @@ def deserialize_object(self, attr, **kwargs): if isinstance(attr, ET.Element): # Do no recurse on XML, just return the tree as-is return attr - if isinstance(attr, basestring): + if isinstance(attr, str): return self.deserialize_basic(attr, "str") obj_type = type(attr) if obj_type in self.basic_types: @@ -1690,11 +1828,10 @@ def deserialize_object(self, attr, **kwargs): pass return deserialized - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) - def deserialize_basic(self, attr, data_type): + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements """Deserialize basic builtin data type from string. Will attempt to convert to str, int, float and bool. This function will also accept '1', '0', 'true' and 'false' as @@ -1702,6 +1839,7 @@ def deserialize_basic(self, attr, data_type): :param str attr: response string to be deserialized. :param str data_type: deserialization data type. + :return: Deserialized basic type. :rtype: str, int, float or bool :raises: TypeError if string format is not valid. """ @@ -1713,24 +1851,23 @@ def deserialize_basic(self, attr, data_type): if data_type == "str": # None or '', node is empty string. return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, 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): @@ -1738,6 +1875,7 @@ def deserialize_unicode(data): as a string. :param str data: response string to be deserialized. + :return: Deserialized string. :rtype: str or unicode """ # We might be here because we have an enum modeled as string, @@ -1747,12 +1885,11 @@ def deserialize_unicode(data): # Consider this is real string try: - if isinstance(data, unicode): + if isinstance(data, unicode): # type: ignore return data except NameError: return str(data) - else: - return str(data) + return str(data) @staticmethod def deserialize_enum(data, enum_obj): @@ -1764,6 +1901,7 @@ def deserialize_enum(data, enum_obj): :param str data: Response string to be deserialized. If this value is None or invalid it will be returned as-is. :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. :rtype: Enum """ if isinstance(data, enum_obj) or data is None: @@ -1772,12 +1910,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: @@ -1793,25 +1930,27 @@ 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. """ if isinstance(attr, ET.Element): attr = attr.text - return bytearray(b64decode(attr)) + return bytearray(b64decode(attr)) # type: ignore @staticmethod 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. """ if isinstance(attr, ET.Element): attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore encoded = attr.replace("-", "+").replace("_", "/") return b64decode(encoded) @@ -1820,34 +1959,37 @@ def deserialize_decimal(attr): """Deserialize string into Decimal object. :param str attr: response string to be deserialized. - :rtype: Decimal + :return: Deserialized decimal :raises: DeserializationError if string format invalid. + :rtype: decimal """ if isinstance(attr, ET.Element): attr = attr.text try: - return decimal.Decimal(attr) + 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. """ if isinstance(attr, ET.Element): attr = attr.text - return _long_type(attr) + return _long_type(attr) # type: ignore @staticmethod 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. """ @@ -1857,36 +1999,37 @@ 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. """ if isinstance(attr, ET.Element): attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): + 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. """ if isinstance(attr, ET.Element): attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore raise DeserializationError("Date must have only digits and -. Received: %s" % attr) return isodate.parse_time(attr) @@ -1895,13 +2038,14 @@ 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. """ if isinstance(attr, ET.Element): attr = attr.text try: - parsed_date = email.utils.parsedate_tz(attr) + 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)) ) @@ -1909,22 +2053,22 @@ def deserialize_rfc(attr): date_obj = date_obj.astimezone(tz=TZ_UTC) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - 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. """ if isinstance(attr, ET.Element): attr = attr.text try: - attr = attr.upper() + attr = attr.upper() # type: ignore match = Deserializer.valid_date.match(attr) if not match: raise ValueError("Invalid datetime string: " + attr) @@ -1946,9 +2090,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): @@ -1956,15 +2099,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 """ if isinstance(attr, ET.Element): - attr = int(attr.text) + 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/maps/azure-maps-route/azure/maps/route/aio/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/aio/__init__.py index e126fbc768b0..8a3c08dfb6f2 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/aio/__init__.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/aio/__init__.py @@ -6,5 +6,16 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._route_client_async import MapsRouteClient -__all__ = ['MapsRouteClient'] +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "MapsRouteClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_client.py b/sdk/maps/azure-maps-route/azure/maps/route/aio/_client.py similarity index 67% rename from sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_client.py rename to sdk/maps/azure-maps-route/azure/maps/route/aio/_client.py index 331237b014f9..872a07fefdd7 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_client.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/aio/_client.py @@ -8,11 +8,13 @@ from copy import deepcopy from typing import Any, Awaitable, Optional, TYPE_CHECKING +from typing_extensions import Self from azure.core import AsyncPipelineClient +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest -from .. import models +from .. import models as _models from .._serialization import Deserializer, Serializer from ._configuration import MapsRouteClientConfiguration from .operations import RouteOperations @@ -22,13 +24,13 @@ from azure.core.credentials_async import AsyncTokenCredential -class MapsRouteClient: # pylint: disable=client-accepts-api-version-keyword +class MapsRouteClient(RouteOperations): """Azure Maps Route REST APIs. :ivar route: RouteOperations operations :vartype route: azure.maps.route.aio.operations.RouteOperations :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :type credential: ~azure.core.credentials.AzureKeyCredential :param client_id: Specifies which account is intended for usage in conjunction with the Azure AD security model. It represents a unique ID for the Azure Maps account and can be retrieved from the Azure Maps management plane Account API. To use Azure AD security in Azure Maps see @@ -52,15 +54,39 @@ def __init__( **kwargs: Any ) -> None: self._config = MapsRouteClientConfiguration(credential=credential, client_id=client_id, **kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + _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), + 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: AsyncPipelineClient = AsyncPipelineClient(base_url=endpoint, policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False - self.route = RouteOperations(self._client, self._config, self._serialize, self._deserialize) - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + super().__init__( + client=self._client, + config=self._config, + serializer=self._serialize, + deserializer=self._deserialize + ) + + 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 @@ -80,14 +106,14 @@ def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHt 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) -> "MapsRouteClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self - async def __aexit__(self, *exc_details) -> None: + async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_configuration.py b/sdk/maps/azure-maps-route/azure/maps/route/aio/_configuration.py similarity index 69% rename from sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_configuration.py rename to sdk/maps/azure-maps-route/azure/maps/route/aio/_configuration.py index 28f1bfdf933c..33709c514caf 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_configuration.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/aio/_configuration.py @@ -8,17 +8,16 @@ from typing import Any, Optional, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies -from .._version import VERSION - if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential +VERSION = "1.0.0b2" + -class MapsRouteClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MapsRouteClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for MapsRouteClient. Note that all parameters used to create this instance are saved as instance @@ -26,28 +25,41 @@ class MapsRouteClientConfiguration(Configuration): # pylint: disable=too-many-i :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param client_id: Specifies which account is intended for usage in conjunction with the Azure - AD security model. It represents a unique ID for the Azure Maps account and can be retrieved - from the Azure Maps management plane Account API. To use Azure AD security in Azure Maps see - the following `articles `_ for guidance. Default value is None. + :param accept: The Accept header field can be used to specify preferences regarding response + media types. Allowed media types include image/jpeg and image/png. Return image in image/png if + Accept header is not specified. Known values are: "image/png" and "image/jpeg". Default value + is None. + :type accept: str + :param client_id: Specifies which account is intended for usage in conjunction with the + Microsoft Entra ID security model. It represents a unique ID for the Azure Maps account and + can be retrieved from the Azure Maps management plane Account API. To use Microsoft Entra ID + security in Azure Maps see the following `articles `_ for + guidance. Default value is None. :type client_id: str - :keyword api_version: Api Version. Default value is "1.0". Note that overriding this default - value may result in unsupported behavior. + :keyword api_version: Api Version. Default value is "1.0". Note that overriding this + default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, credential: "AsyncTokenCredential", client_id: Optional[str] = None, **kwargs: Any) -> None: - super(MapsRouteClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "1.0") # type: str + def __init__( + self, + credential: "AsyncTokenCredential", + accept: Optional[str] = None, + client_id: Optional[str] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "1.0") if credential is None: raise ValueError("Parameter 'credential' must not be None.") self.credential = credential + self.accept = accept self.client_id = client_id self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://atlas.microsoft.com/.default"]) kwargs.setdefault("sdk_moniker", "maps-route/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +68,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 policies.HttpLoggingPolicy(**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 = policies.AsyncBearerTokenCredentialPolicy( diff --git a/sdk/maps/azure-maps-route/azure/maps/route/aio/_base_client_async.py b/sdk/maps/azure-maps-route/azure/maps/route/aio/_patch.py similarity index 51% rename from sdk/maps/azure-maps-route/azure/maps/route/aio/_base_client_async.py rename to sdk/maps/azure-maps-route/azure/maps/route/aio/_patch.py index 0fb5b838e380..d3edc91eb602 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/aio/_base_client_async.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/aio/_patch.py @@ -3,14 +3,30 @@ # Licensed under the MIT License. # ------------------------------------ -from typing import Union, TYPE_CHECKING -from azure.core.pipeline.policies import AzureKeyCredentialPolicy +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + +from typing import Union, Any, List + from azure.core.credentials import AzureKeyCredential -from .._generated.aio import MapsRouteClient as _MapsRouteClient -from .._version import VERSION -if TYPE_CHECKING: - from azure.core.credentials_async import AsyncTokenCredential +from azure.core.credentials_async import AsyncTokenCredential +from azure.core.pipeline.policies import AzureKeyCredentialPolicy +from ._client import MapsRouteClient as MapsRouteClientGenerated + +__all__: List[str] = ["MapsRouteClient"] # Add all objects you want publicly available to users at this package level + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ + +# To check the credential is either AzureKeyCredential or TokenCredential def _authentication_policy(credential): authentication_policy = None if credential is None: @@ -26,25 +42,18 @@ def _authentication_policy(credential): ) return authentication_policy -class AsyncMapsRouteClientBase: +# pylint: disable=C4748 +class MapsRouteClient(MapsRouteClientGenerated): def __init__( self, - credential, #type: Union[AzureKeyCredential, AsyncTokenCredential] - **kwargs #type: Any - ): - # type: (...) -> None + credential: Union[AzureKeyCredential, AsyncTokenCredential], + **kwargs: Any + ) -> None: - self._maps_client = _MapsRouteClient( + super().__init__( credential=credential, # type: ignore - api_version=kwargs.pop("api_version", VERSION), + endpoint=kwargs.pop("endpoint", "https://atlas.microsoft.com"), + client_id=kwargs.pop("client_id", None), authentication_policy=kwargs.pop("authentication_policy", _authentication_policy(credential)), **kwargs ) - self._route_client = self._maps_client.route - - async def __aenter__(self): - await self._maps_client.__aenter__() # pylint:disable=no-member - return self - - async def __aexit__(self, *args): - return await self._maps_client.__aexit__(*args) # pylint:disable=no-member diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/aio/operations/__init__.py similarity index 84% rename from sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/__init__.py rename to sdk/maps/azure-maps-route/azure/maps/route/aio/operations/__init__.py index 08df5df8aeba..f8e1ce9dec01 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/__init__.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/aio/operations/__init__.py @@ -6,10 +6,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._operations import RouteOperations - from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk __all__ = [ diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/_operations.py b/sdk/maps/azure-maps-route/azure/maps/route/aio/operations/_operations.py similarity index 85% rename from sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/_operations.py rename to sdk/maps/azure-maps-route/azure/maps/route/aio/operations/_operations.py index ef3a08d1b1b1..c38d4fde43b8 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/_operations.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/aio/operations/_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines, R0914 # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,21 +7,23 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime -from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload - +from io import IOBase +import sys +from typing import Any, AsyncIterator, Callable, Dict, IO, List, Optional, Type, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, 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.polling.async_base_polling import AsyncLROBasePolling -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 @@ -38,6 +40,10 @@ build_route_request_route_matrix_sync_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -63,7 +69,7 @@ def __init__(self, *args, **kwargs) -> None: async def _request_route_matrix_initial( self, - route_matrix_query: Union[_models.RouteMatrixQuery, IO], + route_matrix_query: Union[_models.RouteMatrixQuery, IO[bytes]], format: Union[str, _models.JsonFormat] = "json", *, wait_for_results: Optional[bool] = None, @@ -85,8 +91,8 @@ async def _request_route_matrix_initial( route_type: Optional[Union[str, _models.RouteType]] = None, vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, **kwargs: Any - ) -> Optional[_models.RouteMatrixResult]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -97,18 +103,18 @@ async def _request_route_matrix_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteMatrixResult]] + 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(route_matrix_query, (IO, bytes)): + if isinstance(route_matrix_query, (IOBase, bytes)): _content = route_matrix_query else: _json = self._serialize.body(route_matrix_query, "RouteMatrixQuery") - request = build_route_request_route_matrix_request( + _request = build_route_request_route_matrix_request( format=format, wait_for_results=wait_for_results, compute_travel_time=compute_travel_time, @@ -136,30 +142,33 @@ async def _request_route_matrix_initial( headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("RouteMatrixResult", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + deserialized = response.iter_bytes() + if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @overload async def begin_request_route_matrix( @@ -188,7 +197,7 @@ async def begin_request_route_matrix( content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.RouteMatrixResult]: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. The Matrix Routing service allows calculation of a matrix of route summaries for a set of routes defined by origin and destination locations by using an asynchronous (async) or @@ -217,8 +226,7 @@ async def begin_request_route_matrix( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} Submit Asynchronous Route Matrix Request ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -239,8 +247,7 @@ async def begin_request_route_matrix( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} Here's a typical sequence of asynchronous operations: @@ -268,7 +275,7 @@ async def begin_request_route_matrix( .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} #. Client issues a GET request on the download URL obtained in Step 3 to download the results @@ -290,7 +297,7 @@ async def begin_request_route_matrix( .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} The URL provided by the location header will return the following responses when a ``GET`` request is issued. @@ -322,7 +329,7 @@ async def begin_request_route_matrix( best-estimate travel time. Known values are: "none" and "all". Default value is None. :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -355,25 +362,23 @@ async def begin_request_route_matrix( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. :paramtype vehicle_weight: int :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -395,9 +400,8 @@ async def begin_request_route_matrix( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -415,13 +419,6 @@ async def begin_request_route_matrix( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 RouteMatrixResult :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteMatrixResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -430,7 +427,7 @@ async def begin_request_route_matrix( @overload async def begin_request_route_matrix( self, - route_matrix_query: IO, + route_matrix_query: IO[bytes], format: Union[str, _models.JsonFormat] = "json", *, wait_for_results: Optional[bool] = None, @@ -454,7 +451,7 @@ async def begin_request_route_matrix( content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.RouteMatrixResult]: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. The Matrix Routing service allows calculation of a matrix of route summaries for a set of routes defined by origin and destination locations by using an asynchronous (async) or @@ -483,8 +480,7 @@ async def begin_request_route_matrix( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} Submit Asynchronous Route Matrix Request ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -505,8 +501,7 @@ async def begin_request_route_matrix( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} Here's a typical sequence of asynchronous operations: @@ -534,7 +529,7 @@ async def begin_request_route_matrix( .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} #. Client issues a GET request on the download URL obtained in Step 3 to download the results @@ -556,7 +551,7 @@ async def begin_request_route_matrix( .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} The URL provided by the location header will return the following responses when a ``GET`` request is issued. @@ -574,7 +569,7 @@ async def begin_request_route_matrix( parameters. The minimum and the maximum cell count supported are 1 and **700** for async and **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 origins and 25 destinations for async API. Required. - :type route_matrix_query: IO + :type route_matrix_query: IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat @@ -588,7 +583,7 @@ async def begin_request_route_matrix( best-estimate travel time. Known values are: "none" and "all". Default value is None. :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -621,25 +616,23 @@ async def begin_request_route_matrix( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. :paramtype vehicle_weight: int :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -661,9 +654,8 @@ async def begin_request_route_matrix( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -681,13 +673,6 @@ async def begin_request_route_matrix( :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 RouteMatrixResult :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteMatrixResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -696,7 +681,7 @@ async def begin_request_route_matrix( @distributed_trace_async async def begin_request_route_matrix( self, - route_matrix_query: Union[_models.RouteMatrixQuery, IO], + route_matrix_query: Union[_models.RouteMatrixQuery, IO[bytes]], format: Union[str, _models.JsonFormat] = "json", *, wait_for_results: Optional[bool] = None, @@ -719,7 +704,7 @@ async def begin_request_route_matrix( vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, **kwargs: Any ) -> AsyncLROPoller[_models.RouteMatrixResult]: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. The Matrix Routing service allows calculation of a matrix of route summaries for a set of routes defined by origin and destination locations by using an asynchronous (async) or @@ -748,8 +733,7 @@ async def begin_request_route_matrix( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} Submit Asynchronous Route Matrix Request ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -770,36 +754,32 @@ async def begin_request_route_matrix( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} Here's a typical sequence of asynchronous operations: - #. - Client sends a Route Matrix POST request to Azure Maps + #. Client sends a Route Matrix POST request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Route Matrix request has been accepted. HTTP ``Error`` - There was an error processing your Route Matrix request. This could - either be a 400 Bad Request or any other Error status code. + either be a 400 Bad Request or any other Error status code. - #. - If the Matrix Route request was accepted successfully, the Location header in the response - contains the URL to download the results of the request. This status URI looks like the - following: + #. If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} #. Client issues a GET request on the download URL obtained in Step 3 to download the results @@ -821,7 +801,7 @@ async def begin_request_route_matrix( .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} The URL provided by the location header will return the following responses when a ``GET`` request is issued. @@ -829,17 +809,18 @@ async def begin_request_route_matrix( .. HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try - again in some time. + again in some time. HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of - the results. + the results. :param route_matrix_query: The matrix of origin and destination coordinates to compute the route distance, travel time and other summary for each cell of the matrix based on the input parameters. The minimum and the maximum cell count supported are 1 and **700** for async and **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 - origins and 25 destinations for async API. Is either a model type or a IO type. Required. - :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery or IO + origins and 25 destinations for async API. Is either a RouteMatrixQuery type or a IO[bytes] + type. Required. + :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery or IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat @@ -853,7 +834,7 @@ async def begin_request_route_matrix( best-estimate travel time. Known values are: "none" and "all". Default value is None. :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -886,25 +867,23 @@ async def begin_request_route_matrix( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. :paramtype vehicle_weight: int :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -926,9 +905,8 @@ async def begin_request_route_matrix( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -943,16 +921,6 @@ async def begin_request_route_matrix( "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is None. :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 RouteMatrixResult :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteMatrixResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -960,13 +928,13 @@ async def begin_request_route_matrix( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteMatrixResult] - polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RouteMatrixResult] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._request_route_matrix_initial( # type: ignore + raw_result = await self._request_route_matrix_initial( route_matrix_query=route_matrix_query, format=format, wait_for_results=wait_for_results, @@ -993,34 +961,37 @@ async def begin_request_route_matrix( 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("RouteMatrixResult", pipeline_response) + deserialized = self._deserialize("RouteMatrixResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: - polling_method = cast( + polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncLROBasePolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs), - ) # type: AsyncPollingMethod + ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.RouteMatrixResult].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) + return AsyncLROPoller[_models.RouteMatrixResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - async def _get_route_matrix_initial(self, matrix_id: str, **kwargs: Any) -> Optional[_models.RouteMatrixResult]: - error_map = { + async def _get_route_matrix_initial(self, matrix_id: str, **kwargs: Any) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1031,43 +1002,46 @@ async def _get_route_matrix_initial(self, matrix_id: str, **kwargs: Any) -> Opti _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteMatrixResult]] + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_route_get_route_matrix_request( + _request = build_route_get_route_matrix_request( matrix_id=matrix_id, client_id=self._config.client_id, api_version=self._config.api_version, headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("RouteMatrixResult", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + deserialized = response.iter_bytes() + if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace_async async def begin_get_route_matrix(self, matrix_id: str, **kwargs: Any) -> AsyncLROPoller[_models.RouteMatrixResult]: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. If the Matrix Route request was accepted successfully, the Location header in the response contains the URL to download the results of the request. This status URI looks like the @@ -1076,7 +1050,7 @@ async def begin_get_route_matrix(self, matrix_id: str, **kwargs: Any) -> AsyncLR .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} #. Client issues a GET request on the download URL obtained in Step 3 to download the results @@ -1098,7 +1072,7 @@ async def begin_get_route_matrix(self, matrix_id: str, **kwargs: Any) -> AsyncLR .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} The URL provided by the location header will return the following responses when a ``GET`` request is issued. @@ -1106,21 +1080,14 @@ async def begin_get_route_matrix(self, matrix_id: str, **kwargs: Any) -> AsyncLR .. HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try - again in some time. + again in some time. HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of - the results. + the results. :param matrix_id: Matrix id received after the Matrix Route request was accepted successfully. Required. :type matrix_id: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 RouteMatrixResult :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteMatrixResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -1128,39 +1095,42 @@ async def begin_get_route_matrix(self, matrix_id: str, **kwargs: Any) -> AsyncLR _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteMatrixResult] - polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + cls: ClsType[_models.RouteMatrixResult] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._get_route_matrix_initial( # type: ignore + raw_result = await self._get_route_matrix_initial( matrix_id=matrix_id, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("RouteMatrixResult", pipeline_response) + deserialized = self._deserialize("RouteMatrixResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: - polling_method = cast( + polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncLROBasePolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs), - ) # type: AsyncPollingMethod + ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.RouteMatrixResult].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) + return AsyncLROPoller[_models.RouteMatrixResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @overload async def request_route_matrix_sync( @@ -1189,7 +1159,7 @@ async def request_route_matrix_sync( content_type: str = "application/json", **kwargs: Any ) -> _models.RouteMatrixResult: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. The Matrix Routing service allows calculation of a matrix of route summaries for a set of routes defined by origin and destination locations by using an asynchronous (async) or @@ -1218,8 +1188,7 @@ async def request_route_matrix_sync( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} Submit Asynchronous Route Matrix Request ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -1240,36 +1209,32 @@ async def request_route_matrix_sync( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} Here's a typical sequence of asynchronous operations: - #. - Client sends a Route Matrix POST request to Azure Maps + #. Client sends a Route Matrix POST request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Route Matrix request has been accepted. HTTP ``Error`` - There was an error processing your Route Matrix request. This could - either be a 400 Bad Request or any other Error status code. + either be a 400 Bad Request or any other Error status code. - #. - If the Matrix Route request was accepted successfully, the Location header in the response - contains the URL to download the results of the request. This status URI looks like the - following: + #. If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} #. Client issues a GET request on the download URL obtained in Step 3 to download the results @@ -1291,7 +1256,7 @@ async def request_route_matrix_sync( .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} The URL provided by the location header will return the following responses when a ``GET`` request is issued. @@ -1299,10 +1264,10 @@ async def request_route_matrix_sync( .. HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try - again in some time. + again in some time. HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of - the results. + the results. :param route_matrix_query: The matrix of origin and destination coordinates to compute the route distance, travel time and other summary for each cell of the matrix based on the input @@ -1323,7 +1288,7 @@ async def request_route_matrix_sync( best-estimate travel time. Known values are: "none" and "all". Default value is None. :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -1356,25 +1321,23 @@ async def request_route_matrix_sync( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. :paramtype vehicle_weight: int :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -1396,9 +1359,8 @@ async def request_route_matrix_sync( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -1424,7 +1386,7 @@ async def request_route_matrix_sync( @overload async def request_route_matrix_sync( self, - route_matrix_query: IO, + route_matrix_query: IO[bytes], format: Union[str, _models.JsonFormat] = "json", *, wait_for_results: Optional[bool] = None, @@ -1448,7 +1410,7 @@ async def request_route_matrix_sync( content_type: str = "application/json", **kwargs: Any ) -> _models.RouteMatrixResult: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. The Matrix Routing service allows calculation of a matrix of route summaries for a set of routes defined by origin and destination locations by using an asynchronous (async) or @@ -1477,8 +1439,7 @@ async def request_route_matrix_sync( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} Submit Asynchronous Route Matrix Request ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -1499,36 +1460,32 @@ async def request_route_matrix_sync( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} Here's a typical sequence of asynchronous operations: - #. - Client sends a Route Matrix POST request to Azure Maps + #. Client sends a Route Matrix POST request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Route Matrix request has been accepted. HTTP ``Error`` - There was an error processing your Route Matrix request. This could - either be a 400 Bad Request or any other Error status code. + either be a 400 Bad Request or any other Error status code. - #. - If the Matrix Route request was accepted successfully, the Location header in the response - contains the URL to download the results of the request. This status URI looks like the - following: + #. If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} #. Client issues a GET request on the download URL obtained in Step 3 to download the results @@ -1550,7 +1507,7 @@ async def request_route_matrix_sync( .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} The URL provided by the location header will return the following responses when a ``GET`` request is issued. @@ -1558,17 +1515,17 @@ async def request_route_matrix_sync( .. HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try - again in some time. + again in some time. HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of - the results. + the results. :param route_matrix_query: The matrix of origin and destination coordinates to compute the route distance, travel time and other summary for each cell of the matrix based on the input parameters. The minimum and the maximum cell count supported are 1 and **700** for async and **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 origins and 25 destinations for async API. Required. - :type route_matrix_query: IO + :type route_matrix_query: IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat @@ -1582,7 +1539,7 @@ async def request_route_matrix_sync( best-estimate travel time. Known values are: "none" and "all". Default value is None. :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -1615,25 +1572,23 @@ async def request_route_matrix_sync( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. :paramtype vehicle_weight: int :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -1655,9 +1610,8 @@ async def request_route_matrix_sync( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -1683,7 +1637,7 @@ async def request_route_matrix_sync( @distributed_trace_async async def request_route_matrix_sync( self, - route_matrix_query: Union[_models.RouteMatrixQuery, IO], + route_matrix_query: Union[_models.RouteMatrixQuery, IO[bytes]], format: Union[str, _models.JsonFormat] = "json", *, wait_for_results: Optional[bool] = None, @@ -1706,7 +1660,7 @@ async def request_route_matrix_sync( vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, **kwargs: Any ) -> _models.RouteMatrixResult: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. The Matrix Routing service allows calculation of a matrix of route summaries for a set of routes defined by origin and destination locations by using an asynchronous (async) or @@ -1735,8 +1689,7 @@ async def request_route_matrix_sync( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} Submit Asynchronous Route Matrix Request ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -1757,36 +1710,32 @@ async def request_route_matrix_sync( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} Here's a typical sequence of asynchronous operations: - #. - Client sends a Route Matrix POST request to Azure Maps + #. Client sends a Route Matrix POST request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Route Matrix request has been accepted. HTTP ``Error`` - There was an error processing your Route Matrix request. This could - either be a 400 Bad Request or any other Error status code. + either be a 400 Bad Request or any other Error status code. - #. - If the Matrix Route request was accepted successfully, the Location header in the response - contains the URL to download the results of the request. This status URI looks like the - following: + #. If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} #. Client issues a GET request on the download URL obtained in Step 3 to download the results @@ -1808,7 +1757,7 @@ async def request_route_matrix_sync( .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} The URL provided by the location header will return the following responses when a ``GET`` request is issued. @@ -1816,17 +1765,18 @@ async def request_route_matrix_sync( .. HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try - again in some time. + again in some time. HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of - the results. + the results. :param route_matrix_query: The matrix of origin and destination coordinates to compute the route distance, travel time and other summary for each cell of the matrix based on the input parameters. The minimum and the maximum cell count supported are 1 and **700** for async and **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 - origins and 25 destinations for async API. Is either a model type or a IO type. Required. - :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery or IO + origins and 25 destinations for async API. Is either a RouteMatrixQuery type or a IO[bytes] + type. Required. + :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery or IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat @@ -1840,7 +1790,7 @@ async def request_route_matrix_sync( best-estimate travel time. Known values are: "none" and "all". Default value is None. :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -1873,25 +1823,23 @@ async def request_route_matrix_sync( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. :paramtype vehicle_weight: int :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -1913,9 +1861,8 @@ async def request_route_matrix_sync( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -1930,20 +1877,20 @@ async def request_route_matrix_sync( "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is None. :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str :return: RouteMatrixResult :rtype: ~azure.maps.route.models.RouteMatrixResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, - 408: lambda response: HttpResponseError( - response=response, model=self._deserialize(_models.ErrorResponse, response) + 408: cast( + Type[HttpResponseError], + lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.ErrorResponse, response) + ), ), } error_map.update(kwargs.pop("error_map", {}) or {}) @@ -1951,18 +1898,18 @@ async def request_route_matrix_sync( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteMatrixResult] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RouteMatrixResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(route_matrix_query, (IO, bytes)): + if isinstance(route_matrix_query, (IOBase, bytes)): _content = route_matrix_query else: _json = self._serialize.body(route_matrix_query, "RouteMatrixQuery") - request = build_route_request_route_matrix_sync_request( + _request = build_route_request_route_matrix_sync_request( format=format, wait_for_results=wait_for_results, compute_travel_time=compute_travel_time, @@ -1990,10 +1937,11 @@ async def request_route_matrix_sync( headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -2003,12 +1951,12 @@ async def request_route_matrix_sync( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("RouteMatrixResult", pipeline_response) + deserialized = self._deserialize("RouteMatrixResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace_async async def get_route_directions( @@ -2059,7 +2007,7 @@ async def get_route_directions( auxiliary_power_in_kw: Optional[float] = None, **kwargs: Any ) -> _models.RouteDirections: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. Returns a route between an origin and a destination, passing through waypoints if they are specified. The route will take into account factors such as current traffic and the typical @@ -2174,7 +2122,7 @@ async def get_route_directions( parameter was not specified by the caller. "effectiveSettings" Default value is None. :paramtype report: str or ~azure.maps.route.models.Report :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -2196,33 +2144,27 @@ async def get_route_directions( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. - * - It is mandatory if any of the *Efficiency parameters are set. + * It is mandatory if any of the *Efficiency parameters are set. - * - It must be strictly positive when used in the context of the Consumption Model. Weight - restrictions are considered. + * It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. - * - If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is - non-zero, then weight restrictions are considered. + * If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. - * - In all other cases, this parameter is ignored. + * In all other cases, this parameter is ignored. Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default value is 0. @@ -2231,11 +2173,11 @@ async def get_route_directions( vehicles may not be allowed to drive on some roads. Default value is False. :paramtype is_commercial_vehicle: bool :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -2257,9 +2199,8 @@ async def get_route_directions( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -2286,12 +2227,10 @@ async def get_route_directions( as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list + * by linear interpolation, if the given speed lies in between two speeds in the list - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by - the nearest two points in the list + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of @@ -2339,7 +2278,7 @@ async def get_route_directions( Must be paired with **decelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **decelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default value is None. @@ -2351,7 +2290,7 @@ async def get_route_directions( Must be paired with **accelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **accelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default value is None. @@ -2363,7 +2302,7 @@ async def get_route_directions( Must be paired with **downhillEfficiency**. - The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **downhillEfficiency**. Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default value is None. @@ -2375,7 +2314,7 @@ async def get_route_directions( Must be paired with **uphillEfficiency**. - The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **uphillEfficiency**. Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default value is None. @@ -2387,12 +2326,10 @@ async def get_route_directions( consumption curve. Consumption rates for speeds not in the list are found as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list + * by linear interpolation, if the given speed lies in between two speeds in the list - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by - the nearest two points in the list + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of @@ -2442,7 +2379,7 @@ async def get_route_directions( :rtype: ~azure.maps.route.models.RouteDirections :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2453,9 +2390,9 @@ async def get_route_directions( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirections] + cls: ClsType[_models.RouteDirections] = kwargs.pop("cls", None) - request = build_route_get_route_directions_request( + _request = build_route_get_route_directions_request( format=format, route_points=route_points, max_alternatives=max_alternatives, @@ -2504,10 +2441,11 @@ async def get_route_directions( headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -2517,15 +2455,15 @@ async def get_route_directions( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("RouteDirections", pipeline_response) + deserialized = self._deserialize("RouteDirections", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore @overload - async def get_route_directions_with_additional_parameters( + async def get_route_directions_with_additional_parameters( # pylint: disable=name-too-long self, route_direction_parameters: _models.RouteDirectionParameters, format: Union[str, _models.ResponseFormat] = "json", @@ -2575,7 +2513,7 @@ async def get_route_directions_with_additional_parameters( content_type: str = "application/json", **kwargs: Any ) -> _models.RouteDirections: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. Returns a route between an origin and a destination, passing through waypoints if they are specified. The route will take into account factors such as current traffic and the typical @@ -2604,14 +2542,14 @@ async def get_route_directions_with_additional_parameters( * The origin point of the calculateRoute request must be on (or very near) the input reference - route. If this is not the case, an error is returned. However, the origin point does not need - to be at the beginning of the input reference route (it can be thought of as the current - vehicle position on the reference route). + route. If this is not the case, an error is returned. However, the origin point does not need + to be at the beginning of the input reference route (it can be thought of as the current + vehicle position on the reference route). * The reference route, returned as the first route in the calculateRoute response, will start - at the origin point specified in the calculateRoute request. The initial part of the input - reference route up until the origin point will be excluded from the response. + at the origin point specified in the calculateRoute request. The initial part of the input + reference route up until the origin point will be excluded from the response. * The values of minDeviationDistance and minDeviationTime determine how far alternative routes - will be guaranteed to follow the reference route from the origin point onwards. + will be guaranteed to follow the reference route from the origin point onwards. * The route must use departAt. * The vehicleHeading is ignored. Required. :type route_direction_parameters: ~azure.maps.route.models.RouteDirectionParameters @@ -2700,7 +2638,7 @@ async def get_route_directions_with_additional_parameters( parameter was not specified by the caller. "effectiveSettings" Default value is None. :paramtype report: str or ~azure.maps.route.models.Report :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -2733,33 +2671,27 @@ async def get_route_directions_with_additional_parameters( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. - * - It is mandatory if any of the *Efficiency parameters are set. + * It is mandatory if any of the *Efficiency parameters are set. - * - It must be strictly positive when used in the context of the Consumption Model. Weight - restrictions are considered. + * It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. - * - If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is - non-zero, then weight restrictions are considered. + * If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. - * - In all other cases, this parameter is ignored. + * In all other cases, this parameter is ignored. Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default value is 0. @@ -2768,11 +2700,11 @@ async def get_route_directions_with_additional_parameters( vehicles may not be allowed to drive on some roads. Default value is False. :paramtype is_commercial_vehicle: bool :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -2794,10 +2726,8 @@ async def get_route_directions_with_additional_parameters( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. - :paramtype use_traffic_data: bool + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. :paramtype route_type: str or ~azure.maps.route.models.RouteType @@ -2876,7 +2806,7 @@ async def get_route_directions_with_additional_parameters( Must be paired with **decelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **decelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default value is None. @@ -2888,7 +2818,7 @@ async def get_route_directions_with_additional_parameters( Must be paired with **accelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **accelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default value is None. @@ -2900,7 +2830,7 @@ async def get_route_directions_with_additional_parameters( Must be paired with **downhillEfficiency**. - The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **downhillEfficiency**. Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default value is None. @@ -2912,7 +2842,7 @@ async def get_route_directions_with_additional_parameters( Must be paired with **uphillEfficiency**. - The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **uphillEfficiency**. Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default value is None. @@ -2984,9 +2914,9 @@ async def get_route_directions_with_additional_parameters( """ @overload - async def get_route_directions_with_additional_parameters( + async def get_route_directions_with_additional_parameters( # pylint: disable=name-too-long self, - route_direction_parameters: IO, + route_direction_parameters: IO[bytes], format: Union[str, _models.ResponseFormat] = "json", *, route_points: str, @@ -3034,7 +2964,7 @@ async def get_route_directions_with_additional_parameters( content_type: str = "application/json", **kwargs: Any ) -> _models.RouteDirections: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. Returns a route between an origin and a destination, passing through waypoints if they are specified. The route will take into account factors such as current traffic and the typical @@ -3063,17 +2993,17 @@ async def get_route_directions_with_additional_parameters( * The origin point of the calculateRoute request must be on (or very near) the input reference - route. If this is not the case, an error is returned. However, the origin point does not need - to be at the beginning of the input reference route (it can be thought of as the current - vehicle position on the reference route). + route. If this is not the case, an error is returned. However, the origin point does not need + to be at the beginning of the input reference route (it can be thought of as the current + vehicle position on the reference route). * The reference route, returned as the first route in the calculateRoute response, will start - at the origin point specified in the calculateRoute request. The initial part of the input - reference route up until the origin point will be excluded from the response. + at the origin point specified in the calculateRoute request. The initial part of the input + reference route up until the origin point will be excluded from the response. * The values of minDeviationDistance and minDeviationTime determine how far alternative routes - will be guaranteed to follow the reference route from the origin point onwards. + will be guaranteed to follow the reference route from the origin point onwards. * The route must use departAt. * The vehicleHeading is ignored. Required. - :type route_direction_parameters: IO + :type route_direction_parameters: IO[bytes] :param format: Desired format of the response. Value can be either *json* or *xml*. Known values are: "json" and "xml". Default value is "json". :type format: str or ~azure.maps.route.models.ResponseFormat @@ -3159,7 +3089,7 @@ async def get_route_directions_with_additional_parameters( parameter was not specified by the caller. "effectiveSettings" Default value is None. :paramtype report: str or ~azure.maps.route.models.Report :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -3192,33 +3122,27 @@ async def get_route_directions_with_additional_parameters( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. - * - It is mandatory if any of the *Efficiency parameters are set. + * It is mandatory if any of the *Efficiency parameters are set. - * - It must be strictly positive when used in the context of the Consumption Model. Weight - restrictions are considered. + * It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. - * - If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is - non-zero, then weight restrictions are considered. + * If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. - * - In all other cases, this parameter is ignored. + * In all other cases, this parameter is ignored. Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default value is 0. @@ -3227,11 +3151,11 @@ async def get_route_directions_with_additional_parameters( vehicles may not be allowed to drive on some roads. Default value is False. :paramtype is_commercial_vehicle: bool :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -3253,9 +3177,8 @@ async def get_route_directions_with_additional_parameters( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -3335,7 +3258,7 @@ async def get_route_directions_with_additional_parameters( Must be paired with **decelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **decelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default value is None. @@ -3347,7 +3270,7 @@ async def get_route_directions_with_additional_parameters( Must be paired with **accelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **accelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default value is None. @@ -3359,7 +3282,7 @@ async def get_route_directions_with_additional_parameters( Must be paired with **downhillEfficiency**. - The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **downhillEfficiency**. Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default value is None. @@ -3371,7 +3294,7 @@ async def get_route_directions_with_additional_parameters( Must be paired with **uphillEfficiency**. - The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **uphillEfficiency**. Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default value is None. @@ -3443,9 +3366,9 @@ async def get_route_directions_with_additional_parameters( """ @distributed_trace_async - async def get_route_directions_with_additional_parameters( + async def get_route_directions_with_additional_parameters( # pylint: disable=name-too-long self, - route_direction_parameters: Union[_models.RouteDirectionParameters, IO], + route_direction_parameters: Union[_models.RouteDirectionParameters, IO[bytes]], format: Union[str, _models.ResponseFormat] = "json", *, route_points: str, @@ -3492,7 +3415,7 @@ async def get_route_directions_with_additional_parameters( auxiliary_power_in_kw: Optional[float] = None, **kwargs: Any ) -> _models.RouteDirections: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. Returns a route between an origin and a destination, passing through waypoints if they are specified. The route will take into account factors such as current traffic and the typical @@ -3521,17 +3444,19 @@ async def get_route_directions_with_additional_parameters( * The origin point of the calculateRoute request must be on (or very near) the input reference - route. If this is not the case, an error is returned. However, the origin point does not need - to be at the beginning of the input reference route (it can be thought of as the current - vehicle position on the reference route). + route. If this is not the case, an error is returned. However, the origin point does not need + to be at the beginning of the input reference route (it can be thought of as the current + vehicle position on the reference route). * The reference route, returned as the first route in the calculateRoute response, will start - at the origin point specified in the calculateRoute request. The initial part of the input - reference route up until the origin point will be excluded from the response. + at the origin point specified in the calculateRoute request. The initial part of the input + reference route up until the origin point will be excluded from the response. * The values of minDeviationDistance and minDeviationTime determine how far alternative routes - will be guaranteed to follow the reference route from the origin point onwards. + will be guaranteed to follow the reference route from the origin point onwards. * The route must use departAt. - * The vehicleHeading is ignored. Is either a model type or a IO type. Required. - :type route_direction_parameters: ~azure.maps.route.models.RouteDirectionParameters or IO + * The vehicleHeading is ignored. Is either a RouteDirectionParameters type or a IO[bytes] + type. Required. + :type route_direction_parameters: ~azure.maps.route.models.RouteDirectionParameters or + IO[bytes] :param format: Desired format of the response. Value can be either *json* or *xml*. Known values are: "json" and "xml". Default value is "json". :type format: str or ~azure.maps.route.models.ResponseFormat @@ -3617,7 +3542,7 @@ async def get_route_directions_with_additional_parameters( parameter was not specified by the caller. "effectiveSettings" Default value is None. :paramtype report: str or ~azure.maps.route.models.Report :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -3650,33 +3575,27 @@ async def get_route_directions_with_additional_parameters( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. - * - It is mandatory if any of the *Efficiency parameters are set. + * It is mandatory if any of the Efficiency parameters are set. - * - It must be strictly positive when used in the context of the Consumption Model. Weight - restrictions are considered. + * It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. - * - If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is - non-zero, then weight restrictions are considered. + * If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. - * - In all other cases, this parameter is ignored. + * In all other cases, this parameter is ignored. Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default value is 0. @@ -3685,11 +3604,11 @@ async def get_route_directions_with_additional_parameters( vehicles may not be allowed to drive on some roads. Default value is False. :paramtype is_commercial_vehicle: bool :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -3711,9 +3630,8 @@ async def get_route_directions_with_additional_parameters( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -3740,12 +3658,10 @@ async def get_route_directions_with_additional_parameters( as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list + * by linear interpolation, if the given speed lies in between two speeds in the list - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by - the nearest two points in the list + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of @@ -3793,7 +3709,7 @@ async def get_route_directions_with_additional_parameters( Must be paired with **decelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **decelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default value is None. @@ -3805,7 +3721,7 @@ async def get_route_directions_with_additional_parameters( Must be paired with **accelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **accelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default value is None. @@ -3817,7 +3733,7 @@ async def get_route_directions_with_additional_parameters( Must be paired with **downhillEfficiency**. - The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **downhillEfficiency**. Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default value is None. @@ -3829,7 +3745,7 @@ async def get_route_directions_with_additional_parameters( Must be paired with **uphillEfficiency**. - The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **uphillEfficiency**. Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default value is None. @@ -3841,12 +3757,10 @@ async def get_route_directions_with_additional_parameters( consumption curve. Consumption rates for speeds not in the list are found as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list + * by linear interpolation, if the given speed lies in between two speeds in the list - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by - the nearest two points in the list + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of @@ -3892,14 +3806,11 @@ async def get_route_directions_with_additional_parameters( Sensible Values : 1.7. Default value is None. :paramtype auxiliary_power_in_kw: float - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str :return: RouteDirections :rtype: ~azure.maps.route.models.RouteDirections :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3910,18 +3821,18 @@ async def get_route_directions_with_additional_parameters( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirections] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RouteDirections] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(route_direction_parameters, (IO, bytes)): + if isinstance(route_direction_parameters, (IOBase, bytes)): _content = route_direction_parameters else: _json = self._serialize.body(route_direction_parameters, "RouteDirectionParameters") - request = build_route_get_route_directions_with_additional_parameters_request( + _request = build_route_get_route_directions_with_additional_parameters_request( format=format, route_points=route_points, max_alternatives=max_alternatives, @@ -3973,10 +3884,11 @@ async def get_route_directions_with_additional_parameters( headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -3986,12 +3898,12 @@ async def get_route_directions_with_additional_parameters( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("RouteDirections", pipeline_response) + deserialized = self._deserialize("RouteDirections", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace_async async def get_route_range( @@ -4035,7 +3947,7 @@ async def get_route_range( ) -> _models.RouteRangeResult: """**Route Range (Isochrone) API** - **Applies to**\ : see pricing `tiers `_. + **Applies to**\\ : see pricing `tiers `_. This service will calculate a set of locations that can be reached from the origin point based on fuel, energy, time or distance budget that is specified. A polygon boundary (or Isochrone) @@ -4052,26 +3964,26 @@ async def get_route_range( :keyword query: The Coordinate from which the range calculation should start. Required. :paramtype query: list[float] :keyword fuel_budget_in_liters: Fuel budget in liters that determines maximal range which can - be travelled using the specified Combustion Consumption Model.:code:`
` When + be travelled using the specified Combustion Consumption Model. When fuelBudgetInLiters is used, it is mandatory to specify a detailed Combustion Consumption - Model.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + Model. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype fuel_budget_in_liters: float :keyword energy_budget_in_kw_h: Electric energy budget in kilowatt hours (kWh) that determines maximal range which can be travelled using the specified Electric Consumption - Model.:code:`
` When energyBudgetInkWh is used, it is mandatory to specify a detailed - Electric Consumption Model.:code:`
` Exactly one budget (fuelBudgetInLiters, + Model. When energyBudgetInkWh is used, it is mandatory to specify a detailed + Electric Consumption Model. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype energy_budget_in_kw_h: float :keyword time_budget_in_sec: Time budget in seconds that determines maximal range which can be travelled using driving time. The Consumption Model will only affect the range when routeType - is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + is eco. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype time_budget_in_sec: float :keyword distance_budget_in_meters: Distance budget in meters that determines maximal range which can be travelled using driving distance. The Consumption Model will only affect the - range when routeType is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, + range when routeType is eco. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype distance_budget_in_meters: float @@ -4088,10 +4000,8 @@ async def get_route_range( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. - :paramtype use_traffic_data: bool + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword avoid: Specifies something that the route calculation should try to avoid when determining the route. Can be specified multiple times in one request, for example, '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the @@ -4107,11 +4017,11 @@ async def get_route_range( Default value is None. :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that @@ -4130,33 +4040,27 @@ async def get_route_range( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. - * - It is mandatory if any of the *Efficiency parameters are set. + * It is mandatory if any of the *Efficiency parameters are set. - * - It must be strictly positive when used in the context of the Consumption Model. Weight - restrictions are considered. + * It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. - * - If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is - non-zero, then weight restrictions are considered. + * If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. - * - In all other cases, this parameter is ignored. + * In all other cases, this parameter is ignored. Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default value is 0. @@ -4186,12 +4090,10 @@ async def get_route_range( as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list + * by linear interpolation, if the given speed lies in between two speeds in the list - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by - the nearest two points in the list + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of @@ -4239,7 +4141,7 @@ async def get_route_range( Must be paired with **decelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **decelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default value is None. @@ -4251,7 +4153,7 @@ async def get_route_range( Must be paired with **accelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **accelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default value is None. @@ -4263,7 +4165,7 @@ async def get_route_range( Must be paired with **downhillEfficiency**. - The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **downhillEfficiency**. Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default value is None. @@ -4275,7 +4177,7 @@ async def get_route_range( Must be paired with **uphillEfficiency**. - The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **uphillEfficiency**. Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default value is None. @@ -4287,12 +4189,10 @@ async def get_route_range( consumption curve. Consumption rates for speeds not in the list are found as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list + * by linear interpolation, if the given speed lies in between two speeds in the list - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by - the nearest two points in the list + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of @@ -4342,7 +4242,7 @@ async def get_route_range( :rtype: ~azure.maps.route.models.RouteRangeResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4353,9 +4253,9 @@ async def get_route_range( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteRangeResult] + cls: ClsType[_models.RouteRangeResult] = kwargs.pop("cls", None) - request = build_route_get_route_range_request( + _request = build_route_get_route_range_request( format=format, query=query, fuel_budget_in_liters=fuel_budget_in_liters, @@ -4395,10 +4295,11 @@ async def get_route_range( headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -4408,20 +4309,20 @@ async def get_route_range( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("RouteRangeResult", pipeline_response) + deserialized = self._deserialize("RouteRangeResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore async def _request_route_directions_batch_initial( self, - route_directions_batch_queries: Union[_models.BatchRequest, IO], + route_directions_batch_queries: Union[_models.BatchRequest, IO[bytes]], format: Union[str, _models.JsonFormat] = "json", **kwargs: Any - ) -> Optional[_models.RouteDirectionsBatchResult]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4432,18 +4333,18 @@ async def _request_route_directions_batch_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteDirectionsBatchResult]] + 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(route_directions_batch_queries, (IO, bytes)): + if isinstance(route_directions_batch_queries, (IOBase, bytes)): _content = route_directions_batch_queries else: _json = self._serialize.body(route_directions_batch_queries, "BatchRequest") - request = build_route_request_route_directions_batch_request( + _request = build_route_request_route_directions_batch_request( format=format, client_id=self._config.client_id, content_type=content_type, @@ -4453,30 +4354,33 @@ async def _request_route_directions_batch_initial( headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + deserialized = response.iter_bytes() + if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @overload async def begin_request_route_directions_batch( @@ -4489,7 +4393,7 @@ async def begin_request_route_directions_batch( ) -> AsyncLROPoller[_models.RouteDirectionsBatchResult]: """**Route Directions Batch API** - **Applies to**\ : see pricing `tiers `_. + **Applies to**\\ : see pricing `tiers `_. The Route Directions Batch API sends batches of queries to `Route Directions API `_ using just a single API @@ -4519,25 +4423,23 @@ async def begin_request_route_directions_batch( #. Client sends a Route Directions Batch ``POST`` request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Batch request has been accepted. HTTP ``Error`` - There was an error processing your Batch request. This could either be a - ``400 Bad Request`` or any other ``Error`` status code. + ``400 Bad Request`` or any other ``Error`` status code. - #. - If the batch request was accepted successfully, the ``Location`` header in the response - contains the URL to download the results of the batch request. - This status URI looks like following: + #. If the batch request was accepted successfully, the ``Location`` header in the response + contains the URL to download the results of the batch request. + This status URI looks like following: - ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` - Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security - <#security>`_\ ) to the *status URI* before running it. :code:`
` + ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` + Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security + <#security>`_\\ ) to the *status URI* before running it. #. Client issues a ``GET`` request on the *download URL* obtained in Step 3 to download the @@ -4556,10 +4458,10 @@ async def begin_request_route_directions_batch( { "batchItems": [ { "query": - "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" - }, + "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + }, { "query": - "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, + "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, { "query": "?query=48.923159,-122.557362:32.621279,-116.840362" } ] } @@ -4589,16 +4491,15 @@ async def begin_request_route_directions_batch( #. Client sends a ``GET`` request using the *download URL*. - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please - try again in some time. + try again in some time. HTTP ``200 OK`` - Batch request successfully processed. The response body contains all - the batch results. + the batch results. Batch Response Model @@ -4607,22 +4508,20 @@ async def begin_request_route_directions_batch( The returned data content is similar for async and sync requests. When downloading the results of an async batch request, if the batch has finished processing, the response body contains the batch response. This batch response contains a ``summary`` component that indicates the - ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. - queries which were executed successfully. The batch response also includes a ``batchItems`` - array which contains a response for each and every query in the batch request. The - ``batchItems`` will contain the results in the exact same order the original queries were sent - in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\\ + i.e. queries which were executed successfully. The batch response also includes a + ``batchItems`` array which contains a response for each and every query in the batch request. + The ``batchItems`` will contain the results in the exact same order the original queries were + sent in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` fields. Each ``response`` in ``batchItems`` is of one of the following types: - * - `\ ``RouteDirections`` - `_ - If the - query completed successfully. + * `\\ ``RouteDirections`` + `_ - If the + query completed successfully. - * - ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in - this case. + * ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. Here's a sample Batch Response with 1 *successful* and 1 *failed* result: @@ -4690,13 +4589,13 @@ async def begin_request_route_directions_batch( "error": { "code": "400 BadRequest", - "message": "Bad request: one or more parameters were incorrectly - specified or are mutually exclusive." + "message": + "Bad request: one or more parameters were incorrectly specified or are mutually exclusive." } } } ] - }. + } :param route_directions_batch_queries: The list of route directions queries/requests to process. The list can contain a max of 700 queries for async and 100 queries for sync version @@ -4708,13 +4607,6 @@ async def begin_request_route_directions_batch( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 RouteDirectionsBatchResult :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -4723,7 +4615,7 @@ async def begin_request_route_directions_batch( @overload async def begin_request_route_directions_batch( self, - route_directions_batch_queries: IO, + route_directions_batch_queries: IO[bytes], format: Union[str, _models.JsonFormat] = "json", *, content_type: str = "application/json", @@ -4731,7 +4623,7 @@ async def begin_request_route_directions_batch( ) -> AsyncLROPoller[_models.RouteDirectionsBatchResult]: """**Route Directions Batch API** - **Applies to**\ : see pricing `tiers `_. + **Applies to**\\ : see pricing `tiers `_. The Route Directions Batch API sends batches of queries to `Route Directions API `_ using just a single API @@ -4761,25 +4653,23 @@ async def begin_request_route_directions_batch( #. Client sends a Route Directions Batch ``POST`` request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Batch request has been accepted. HTTP ``Error`` - There was an error processing your Batch request. This could either be a - ``400 Bad Request`` or any other ``Error`` status code. + ``400 Bad Request`` or any other ``Error`` status code. - #. - If the batch request was accepted successfully, the ``Location`` header in the response - contains the URL to download the results of the batch request. - This status URI looks like following: + #. If the batch request was accepted successfully, the ``Location`` header in the response + contains the URL to download the results of the batch request. + This status URI looks like following: - ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` - Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security - <#security>`_\ ) to the *status URI* before running it. :code:`
` + ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` + Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security + <#security>`_\\ ) to the *status URI* before running it. #. Client issues a ``GET`` request on the *download URL* obtained in Step 3 to download the @@ -4798,10 +4688,10 @@ async def begin_request_route_directions_batch( { "batchItems": [ { "query": - "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" - }, + "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + }, { "query": - "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, + "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, { "query": "?query=48.923159,-122.557362:32.621279,-116.840362" } ] } @@ -4831,16 +4721,15 @@ async def begin_request_route_directions_batch( #. Client sends a ``GET`` request using the *download URL*. - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please - try again in some time. + try again in some time. HTTP ``200 OK`` - Batch request successfully processed. The response body contains all - the batch results. + the batch results. Batch Response Model @@ -4849,22 +4738,20 @@ async def begin_request_route_directions_batch( The returned data content is similar for async and sync requests. When downloading the results of an async batch request, if the batch has finished processing, the response body contains the batch response. This batch response contains a ``summary`` component that indicates the - ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. - queries which were executed successfully. The batch response also includes a ``batchItems`` - array which contains a response for each and every query in the batch request. The - ``batchItems`` will contain the results in the exact same order the original queries were sent - in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\\ + i.e. queries which were executed successfully. The batch response also includes a + ``batchItems`` array which contains a response for each and every query in the batch request. + The ``batchItems`` will contain the results in the exact same order the original queries were + sent in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` fields. Each ``response`` in ``batchItems`` is of one of the following types: - * - `\ ``RouteDirections`` - `_ - If the - query completed successfully. + * `\\ ``RouteDirections`` + `_ - If the + query completed successfully. - * - ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in - this case. + * ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. Here's a sample Batch Response with 1 *successful* and 1 *failed* result: @@ -4932,31 +4819,24 @@ async def begin_request_route_directions_batch( "error": { "code": "400 BadRequest", - "message": "Bad request: one or more parameters were incorrectly - specified or are mutually exclusive." + "message": + "Bad request: one or more parameters were incorrectly specified or are mutually exclusive." } } } ] - }. + } :param route_directions_batch_queries: The list of route directions queries/requests to process. The list can contain a max of 700 queries for async and 100 queries for sync version and must contain at least 1 query. Required. - :type route_directions_batch_queries: IO + :type route_directions_batch_queries: IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 RouteDirectionsBatchResult :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -4965,13 +4845,13 @@ async def begin_request_route_directions_batch( @distributed_trace_async async def begin_request_route_directions_batch( self, - route_directions_batch_queries: Union[_models.BatchRequest, IO], + route_directions_batch_queries: Union[_models.BatchRequest, IO[bytes]], format: Union[str, _models.JsonFormat] = "json", **kwargs: Any ) -> AsyncLROPoller[_models.RouteDirectionsBatchResult]: """**Route Directions Batch API** - **Applies to**\ : see pricing `tiers `_. + **Applies to**\\ : see pricing `tiers `_. The Route Directions Batch API sends batches of queries to `Route Directions API `_ using just a single API @@ -5001,25 +4881,23 @@ async def begin_request_route_directions_batch( #. Client sends a Route Directions Batch ``POST`` request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Batch request has been accepted. HTTP ``Error`` - There was an error processing your Batch request. This could either be a - ``400 Bad Request`` or any other ``Error`` status code. + ``400 Bad Request`` or any other ``Error`` status code. - #. - If the batch request was accepted successfully, the ``Location`` header in the response - contains the URL to download the results of the batch request. - This status URI looks like following: + #. If the batch request was accepted successfully, the ``Location`` header in the response + contains the URL to download the results of the batch request. + This status URI looks like following: - ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` - Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security - <#security>`_\ ) to the *status URI* before running it. :code:`
` + ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` + Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security + <#security>`_\\ ) to the *status URI* before running it. #. Client issues a ``GET`` request on the *download URL* obtained in Step 3 to download the @@ -5038,10 +4916,10 @@ async def begin_request_route_directions_batch( { "batchItems": [ { "query": - "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" - }, + "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + }, { "query": - "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, + "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, { "query": "?query=48.923159,-122.557362:32.621279,-116.840362" } ] } @@ -5071,16 +4949,15 @@ async def begin_request_route_directions_batch( #. Client sends a ``GET`` request using the *download URL*. - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please - try again in some time. + try again in some time. HTTP ``200 OK`` - Batch request successfully processed. The response body contains all - the batch results. + the batch results. Batch Response Model @@ -5089,22 +4966,20 @@ async def begin_request_route_directions_batch( The returned data content is similar for async and sync requests. When downloading the results of an async batch request, if the batch has finished processing, the response body contains the batch response. This batch response contains a ``summary`` component that indicates the - ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. - queries which were executed successfully. The batch response also includes a ``batchItems`` - array which contains a response for each and every query in the batch request. The - ``batchItems`` will contain the results in the exact same order the original queries were sent - in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\\ + i.e. queries which were executed successfully. The batch response also includes a + ``batchItems`` array which contains a response for each and every query in the batch request. + The ``batchItems`` will contain the results in the exact same order the original queries were + sent in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` fields. Each ``response`` in ``batchItems`` is of one of the following types: - * - `\ ``RouteDirections`` - `_ - If the - query completed successfully. + * `\\ ``RouteDirections`` + `_ - If the + query completed successfully. - * - ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in - this case. + * ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. Here's a sample Batch Response with 1 *successful* and 1 *failed* result: @@ -5172,31 +5047,21 @@ async def begin_request_route_directions_batch( "error": { "code": "400 BadRequest", - "message": "Bad request: one or more parameters were incorrectly - specified or are mutually exclusive." + "message": + "Bad request: one or more parameters were incorrectly specified or are mutually exclusive." } } } ] - }. + } :param route_directions_batch_queries: The list of route directions queries/requests to process. The list can contain a max of 700 queries for async and 100 queries for sync version - and must contain at least 1 query. Is either a model type or a IO type. Required. - :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest or IO + and must contain at least 1 query. Is either a BatchRequest type or a IO[bytes] type. Required. + :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest or IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 RouteDirectionsBatchResult :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -5204,13 +5069,13 @@ async def begin_request_route_directions_batch( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirectionsBatchResult] - polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RouteDirectionsBatchResult] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._request_route_directions_batch_initial( # type: ignore + raw_result = await self._request_route_directions_batch_initial( route_directions_batch_queries=route_directions_batch_queries, format=format, content_type=content_type, @@ -5219,36 +5084,37 @@ async def begin_request_route_directions_batch( 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("RouteDirectionsBatchResult", pipeline_response) + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: - polling_method = cast( + polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncLROBasePolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs), - ) # type: AsyncPollingMethod + ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.RouteDirectionsBatchResult].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) + return AsyncLROPoller[_models.RouteDirectionsBatchResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - async def _get_route_directions_batch_initial( - self, batch_id: str, **kwargs: Any - ) -> Optional[_models.RouteDirectionsBatchResult]: - error_map = { + async def _get_route_directions_batch_initial(self, batch_id: str, **kwargs: Any) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5259,45 +5125,48 @@ async def _get_route_directions_batch_initial( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteDirectionsBatchResult]] + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_route_get_route_directions_batch_request( + _request = build_route_get_route_directions_batch_request( batch_id=batch_id, client_id=self._config.client_id, api_version=self._config.api_version, headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + deserialized = response.iter_bytes() + if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace_async async def begin_get_route_directions_batch( self, batch_id: str, **kwargs: Any ) -> AsyncLROPoller[_models.RouteDirectionsBatchResult]: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. Download Asynchronous Batch Results ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -5314,16 +5183,15 @@ async def begin_get_route_directions_batch( #. Client sends a ``GET`` request using the *download URL*. - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please - try again in some time. + try again in some time. HTTP ``200 OK`` - Batch request successfully processed. The response body contains all - the batch results. + the batch results. Batch Response Model @@ -5332,22 +5200,20 @@ async def begin_get_route_directions_batch( The returned data content is similar for async and sync requests. When downloading the results of an async batch request, if the batch has finished processing, the response body contains the batch response. This batch response contains a ``summary`` component that indicates the - ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. - queries which were executed successfully. The batch response also includes a ``batchItems`` - array which contains a response for each and every query in the batch request. The - ``batchItems`` will contain the results in the exact same order the original queries were sent - in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\\ + i.e. queries which were executed successfully. The batch response also includes a + ``batchItems`` array which contains a response for each and every query in the batch request. + The ``batchItems`` will contain the results in the exact same order the original queries were + sent in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` fields. Each ``response`` in ``batchItems`` is of one of the following types: - * - `\ ``RouteDirections`` - `_ - If the - query completed successfully. + * `\\ ``RouteDirections`` + `_ - If the + query completed successfully. - * - ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in - this case. + * ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. Here's a sample Batch Response with 1 *successful* and 1 *failed* result: @@ -5415,23 +5281,16 @@ async def begin_get_route_directions_batch( "error": { "code": "400 BadRequest", - "message": "Bad request: one or more parameters were incorrectly - specified or are mutually exclusive." + "message": + "Bad request: one or more parameters were incorrectly specified or are mutually exclusive." } } } ] - }. + } :param batch_id: Batch id for querying the operation. Required. :type batch_id: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 RouteDirectionsBatchResult :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -5439,39 +5298,42 @@ async def begin_get_route_directions_batch( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirectionsBatchResult] - polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + cls: ClsType[_models.RouteDirectionsBatchResult] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._get_route_directions_batch_initial( # type: ignore + raw_result = await self._get_route_directions_batch_initial( batch_id=batch_id, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) + await raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: - polling_method = cast( + polling_method: AsyncPollingMethod = cast( AsyncPollingMethod, AsyncLROBasePolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs), - ) # type: AsyncPollingMethod + ) elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.RouteDirectionsBatchResult].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) + return AsyncLROPoller[_models.RouteDirectionsBatchResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @overload async def request_route_directions_batch_sync( @@ -5484,7 +5346,7 @@ async def request_route_directions_batch_sync( ) -> _models.RouteDirectionsBatchResult: """**Route Directions Batch API** - **Applies to**\ : see pricing `tiers `_. + **Applies to**\\ : see pricing `tiers `_. The Route Directions Batch API sends batches of queries to `Route Directions API `_ using just a single API @@ -5504,7 +5366,7 @@ async def request_route_directions_batch_sync( .. code-block:: POST - https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} + https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} Batch Response Model ^^^^^^^^^^^^^^^^^^^^ @@ -5512,22 +5374,20 @@ async def request_route_directions_batch_sync( The returned data content is similar for async and sync requests. When downloading the results of an async batch request, if the batch has finished processing, the response body contains the batch response. This batch response contains a ``summary`` component that indicates the - ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. - queries which were executed successfully. The batch response also includes a ``batchItems`` - array which contains a response for each and every query in the batch request. The - ``batchItems`` will contain the results in the exact same order the original queries were sent - in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\\ + i.e. queries which were executed successfully. The batch response also includes a + ``batchItems`` array which contains a response for each and every query in the batch request. + The ``batchItems`` will contain the results in the exact same order the original queries were + sent in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` fields. Each ``response`` in ``batchItems`` is of one of the following types: - * - `\ ``RouteDirections`` - `_ - If the - query completed successfully. + * `\\ ``RouteDirections`` + `_ - If the + query completed successfully. - * - ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in - this case. + * ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. Here's a sample Batch Response with 1 *successful* and 1 *failed* result: @@ -5595,13 +5455,13 @@ async def request_route_directions_batch_sync( "error": { "code": "400 BadRequest", - "message": "Bad request: one or more parameters were incorrectly - specified or are mutually exclusive." + "message": + "Bad request: one or more parameters were incorrectly specified or are mutually exclusive." } } } ] - }. + } :param route_directions_batch_queries: The list of route directions queries/requests to process. The list can contain a max of 700 queries for async and 100 queries for sync version @@ -5621,7 +5481,7 @@ async def request_route_directions_batch_sync( @overload async def request_route_directions_batch_sync( self, - route_directions_batch_queries: IO, + route_directions_batch_queries: IO[bytes], format: Union[str, _models.JsonFormat] = "json", *, content_type: str = "application/json", @@ -5629,7 +5489,7 @@ async def request_route_directions_batch_sync( ) -> _models.RouteDirectionsBatchResult: """**Route Directions Batch API** - **Applies to**\ : see pricing `tiers `_. + **Applies to**\\ : see pricing `tiers `_. The Route Directions Batch API sends batches of queries to `Route Directions API `_ using just a single API @@ -5649,7 +5509,7 @@ async def request_route_directions_batch_sync( .. code-block:: POST - https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} + https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} Batch Response Model ^^^^^^^^^^^^^^^^^^^^ @@ -5657,22 +5517,20 @@ async def request_route_directions_batch_sync( The returned data content is similar for async and sync requests. When downloading the results of an async batch request, if the batch has finished processing, the response body contains the batch response. This batch response contains a ``summary`` component that indicates the - ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. - queries which were executed successfully. The batch response also includes a ``batchItems`` - array which contains a response for each and every query in the batch request. The - ``batchItems`` will contain the results in the exact same order the original queries were sent - in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\\ + i.e. queries which were executed successfully. The batch response also includes a + ``batchItems`` array which contains a response for each and every query in the batch request. + The ``batchItems`` will contain the results in the exact same order the original queries were + sent in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` fields. Each ``response`` in ``batchItems`` is of one of the following types: - * - `\ ``RouteDirections`` - `_ - If the - query completed successfully. + * `\\ ``RouteDirections`` + `_ - If the + query completed successfully. - * - ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in - this case. + * ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. Here's a sample Batch Response with 1 *successful* and 1 *failed* result: @@ -5740,18 +5598,18 @@ async def request_route_directions_batch_sync( "error": { "code": "400 BadRequest", - "message": "Bad request: one or more parameters were incorrectly - specified or are mutually exclusive." + "message": + "Bad request: one or more parameters were incorrectly specified or are mutually exclusive." } } } ] - }. + } :param route_directions_batch_queries: The list of route directions queries/requests to process. The list can contain a max of 700 queries for async and 100 queries for sync version and must contain at least 1 query. Required. - :type route_directions_batch_queries: IO + :type route_directions_batch_queries: IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat @@ -5766,13 +5624,13 @@ async def request_route_directions_batch_sync( @distributed_trace_async async def request_route_directions_batch_sync( self, - route_directions_batch_queries: Union[_models.BatchRequest, IO], + route_directions_batch_queries: Union[_models.BatchRequest, IO[bytes]], format: Union[str, _models.JsonFormat] = "json", **kwargs: Any ) -> _models.RouteDirectionsBatchResult: """**Route Directions Batch API** - **Applies to**\ : see pricing `tiers `_. + **Applies to**\\ : see pricing `tiers `_. The Route Directions Batch API sends batches of queries to `Route Directions API `_ using just a single API @@ -5792,7 +5650,7 @@ async def request_route_directions_batch_sync( .. code-block:: POST - https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} + https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} Batch Response Model ^^^^^^^^^^^^^^^^^^^^ @@ -5800,22 +5658,20 @@ async def request_route_directions_batch_sync( The returned data content is similar for async and sync requests. When downloading the results of an async batch request, if the batch has finished processing, the response body contains the batch response. This batch response contains a ``summary`` component that indicates the - ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. - queries which were executed successfully. The batch response also includes a ``batchItems`` - array which contains a response for each and every query in the batch request. The - ``batchItems`` will contain the results in the exact same order the original queries were sent - in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\\ + i.e. queries which were executed successfully. The batch response also includes a + ``batchItems`` array which contains a response for each and every query in the batch request. + The ``batchItems`` will contain the results in the exact same order the original queries were + sent in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` fields. Each ``response`` in ``batchItems`` is of one of the following types: - * - `\ ``RouteDirections`` - `_ - If the - query completed successfully. + * `\\ ``RouteDirections`` + `_ - If the + query completed successfully. - * - ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in - this case. + * ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. Here's a sample Batch Response with 1 *successful* and 1 *failed* result: @@ -5883,35 +5739,35 @@ async def request_route_directions_batch_sync( "error": { "code": "400 BadRequest", - "message": "Bad request: one or more parameters were incorrectly - specified or are mutually exclusive." + "message": + "Bad request: one or more parameters were incorrectly specified or are mutually exclusive." } } } ] - }. + } :param route_directions_batch_queries: The list of route directions queries/requests to process. The list can contain a max of 700 queries for async and 100 queries for sync version - and must contain at least 1 query. Is either a model type or a IO type. Required. - :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest or IO + and must contain at least 1 query. Is either a BatchRequest type or a IO[bytes] type. Required. + :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest or IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str :return: RouteDirectionsBatchResult :rtype: ~azure.maps.route.models.RouteDirectionsBatchResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, - 408: lambda response: HttpResponseError( - response=response, model=self._deserialize(_models.ErrorResponse, response) + 408: cast( + Type[HttpResponseError], + lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.ErrorResponse, response) + ), ), } error_map.update(kwargs.pop("error_map", {}) or {}) @@ -5919,18 +5775,18 @@ async def request_route_directions_batch_sync( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirectionsBatchResult] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RouteDirectionsBatchResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(route_directions_batch_queries, (IO, bytes)): + if isinstance(route_directions_batch_queries, (IOBase, bytes)): _content = route_directions_batch_queries else: _json = self._serialize.body(route_directions_batch_queries, "BatchRequest") - request = build_route_request_route_directions_batch_sync_request( + _request = build_route_request_route_directions_batch_sync_request( format=format, client_id=self._config.client_id, content_type=content_type, @@ -5940,10 +5796,11 @@ async def request_route_directions_batch_sync( headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -5953,9 +5810,9 @@ async def request_route_directions_batch_sync( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore diff --git a/sdk/maps/azure-maps-route/azure/maps/route/aio/_route_client_async.py b/sdk/maps/azure-maps-route/azure/maps/route/aio/operations/_patch.py similarity index 89% rename from sdk/maps/azure-maps-route/azure/maps/route/aio/_route_client_async.py rename to sdk/maps/azure-maps-route/azure/maps/route/aio/operations/_patch.py index 58a5cfb19011..aab5bb1ee320 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/aio/_route_client_async.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/aio/operations/_patch.py @@ -1,71 +1,46 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -# pylint: disable=unused-import,ungrouped-imports, R0904, C0302, W0212 -from typing import Any, List, Union, Tuple, overload -from azure.core.polling import AsyncLROPoller -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.credentials import AzureKeyCredential -from azure.core.credentials_async import AsyncTokenCredential -from ._base_client_async import AsyncMapsRouteClientBase +# pylint: disable=W0212, W0221, W0237, C4758 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ -from ..models import ( - RouteDirectionsBatchResult, +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List, Union, Any, Tuple + +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.polling import AsyncLROPoller +from ...models import ( + ResponseFormat, + LatLongPair, RouteDirections, RouteRangeResult, - RouteMatrixResult, + RouteDirectionParameters, + RouteDirectionsBatchResult, RouteMatrixQuery, - LatLon + RouteMatrixResult, + BatchRequest, + BatchRequestItem ) +from ._operations import RouteOperations as RouteOperationsGenerated -from .._generated.models import ( - ResponseFormat -) +__all__: List[str] = ["RouteOperations"] # Add all objects you want publicly available to users at this package level -def get_batch_id_from_poller(polling_method): - if hasattr(polling_method, "_operation"): - operation=polling_method._operation - return operation._location_url.split('/')[-1].split('?')[0] - return None - -# By default, use the latest supported API version -class MapsRouteClient(AsyncMapsRouteClientBase): - """Azure Maps Route REST APIs. - - :param credential: - Credential needed for the client to connect to Azure. - :type credential: - ~azure.core.credentials.TokenCredential or ~azure.core.credentials.AzureKeyCredential - :keyword str base_url: - Supported Maps Services or Language resource base_url - (protocol and hostname, for example: 'https://us.atlas.microsoft.com'). - :keyword str client_id: - Specifies which account is intended for usage with the Azure AD security model. - It represents a unique ID for the Azure Maps account. - :keyword api_version: - The API version of the service to use for requests. It defaults to the latest service version. - Setting to an older version may result in reduced feature compatibility. - :paramtype api_version: str - """ - def __init__( - self, - credential: Union[AzureKeyCredential, AsyncTokenCredential], - **kwargs: Any - )-> None: - - super().__init__( - credential=credential, **kwargs - ) +def patch_sdk(): + """Do not remove from this file. - # cSpell:disable + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ +class RouteOperations(RouteOperationsGenerated): @distributed_trace_async - async def get_route_directions( + async def get_route_directions( # type: ignore self, - route_points: Union[List[LatLon], List[Tuple]], + route_points: Union[List[LatLongPair], List[Tuple]], **kwargs: Any ) -> RouteDirections: """ @@ -78,7 +53,7 @@ async def get_route_directions( instructions is also available, depending on the options selected. :param route_points: The Coordinate from which the range calculation should start, coordinates as (lat, lon) - :type route_points: List[LatLon] or List[Tuple] + :type route_points: List[LatLongPair] or List[Tuple] :keyword supporting_points: A GeoJSON Geometry collection representing sequence of coordinates used as input for route reconstruction and for calculating zero or more alternative routes to this reference route. @@ -283,30 +258,36 @@ async def get_route_directions( :rtype: ~azure.maps.route.models.RouteDirections :raises ~azure.core.exceptions.HttpResponseError: """ - query_items="" - route_directions_body={} + query_items = "" + if route_points: - query_items = ":".join([(str(route_point[0])+","+str(route_point[1])) for route_point in route_points]) + coordinates = [] + for route_point in route_points: + if isinstance(route_point, LatLongPair): + coordinates.append(f"{route_point.latitude},{route_point.longitude}") + elif isinstance(route_point, tuple): + coordinates.append(f"{route_point[0]},{route_point[1]}") + query_items = ":".join(coordinates) supporting_points = kwargs.pop('supporting_points', None) avoid_vignette = kwargs.pop('avoid_vignette', None) allow_vignette = kwargs.pop('allow_vignette', None) avoid_areas = kwargs.pop('avoid_areas', None) - if supporting_points or avoid_vignette or allow_vignette or avoid_areas is not None: - route_directions_body['supporting_points'] = supporting_points - route_directions_body['avoid_vignette'] = avoid_vignette - route_directions_body['allow_vignette'] = allow_vignette - route_directions_body['avoid_areas'] = avoid_areas - - if route_directions_body: - # import pdb; pdb.set_trace() - return await self._route_client.get_route_directions_with_additional_parameters( - format=ResponseFormat.JSON, + + if supporting_points or avoid_areas or allow_vignette or avoid_vignette: + route_directions_body = RouteDirectionParameters( + supporting_points=supporting_points, + avoid_vignette=avoid_vignette, + allow_vignette=allow_vignette, + avoid_areas=avoid_areas + ) + return await super().get_route_directions_with_additional_parameters( route_direction_parameters=route_directions_body, + format=ResponseFormat.JSON, route_points=query_items, **kwargs ) - return await self._route_client.get_route_directions( + return await super().get_route_directions( format=ResponseFormat.JSON, route_points=query_items, **kwargs @@ -314,9 +295,9 @@ async def get_route_directions( # cSpell:disable @distributed_trace_async - async def get_route_range( + async def get_route_range( # type: ignore self, - coordinates: Union[LatLon, Tuple], + coordinates: Union[LatLongPair, Tuple[float, float]], **kwargs: Any ) -> RouteRangeResult: @@ -328,28 +309,28 @@ async def get_route_range( the result of the origin point. :param coordinates: The Coordinate from which the range calculation should start, coordinates as (lat, lon) - :type coordinates: LatLon or Tuple + :type coordinates: LatLongPair or Tuple :keyword fuel_budget_in_liters: Fuel budget in liters that determines maximal range which can - be travelled using the specified Combustion Consumption Model.:code:`
` When + be travelled using the specified Combustion Consumption Model. When fuelBudgetInLiters is used, it is mandatory to specify a detailed Combustion Consumption - Model.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + Model. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype fuel_budget_in_liters: float :keyword energy_budget_in_kw_h: Electric energy budget in kilowatt hours (kWh) that determines maximal range which can be travelled using the specified Electric Consumption - Model.:code:`
` When energyBudgetInkWh is used, it is mandatory to specify a detailed - Electric Consumption Model.:code:`
` Exactly one budget (fuelBudgetInLiters, + Model. When energyBudgetInkWh is used, it is mandatory to specify a detailed + Electric Consumption Model. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype energy_budget_in_kw_h: float :keyword time_budget_in_sec: Time budget in seconds that determines maximal range which can be travelled using driving time. The Consumption Model will only affect the range when routeType - is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + is eco. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype time_budget_in_sec: float :keyword distance_budget_in_meters: Distance budget in meters that determines maximal range which can be travelled using driving distance. The Consumption Model will only affect the - range when routeType is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, + range when routeType is eco. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype distance_budget_in_meters: float @@ -474,9 +455,13 @@ async def get_route_range( :rtype: ~azure.maps.route.models.RouteRangeResult :raises ~azure.core.exceptions.HttpResponseError: """ - query = [coordinates[0], coordinates[1]] + query = [] + if isinstance(coordinates, Tuple): + query = [coordinates[0], coordinates[1]] + elif isinstance(coordinates, LatLongPair) and coordinates.latitude and coordinates.longitude: + query = [coordinates.latitude, coordinates.longitude] - return await self._route_client.get_route_range( + return await super().get_route_range( format=ResponseFormat.JSON, query=query, **kwargs @@ -501,33 +486,16 @@ async def get_route_directions_batch_sync( :rtype: RouteDirectionsBatchResult :raises ~azure.core.exceptions.HttpResponseError: """ - batch_items = [{"query": f"?query={query}"} for query - in queries] if queries else [] - result = await self._route_client.request_route_directions_batch_sync( + return await super().request_route_directions_batch_sync( format=ResponseFormat.JSON, - route_directions_batch_queries={"batch_items": batch_items}, + route_directions_batch_queries=BatchRequest( + batch_items=[BatchRequestItem(query=f"?query={query}") for query in queries] if queries else [] + ), **kwargs ) - return RouteDirectionsBatchResult(summary=result.batch_summary, items=result.batch_items) - - @overload - def begin_get_route_directions_batch( - self, - batch_id: str, - **kwargs: Any - ) -> AsyncLROPoller[RouteDirectionsBatchResult]: - pass - - @overload - def begin_get_route_directions_batch( - self, - queries: List[str], - **kwargs: Any - ) -> AsyncLROPoller[RouteDirectionsBatchResult]: - pass @distributed_trace_async - async def begin_get_route_directions_batch( + async def begin_get_route_directions_batch( # type: ignore self, **kwargs: Any ) -> AsyncLROPoller[RouteDirectionsBatchResult]: @@ -556,21 +524,28 @@ async def begin_get_route_directions_batch( batch_id=kwargs.pop('batch_id', None) if batch_id: - poller = await self._route_client.begin_get_route_directions_batch( + poller = await super().begin_get_route_directions_batch( format=ResponseFormat.JSON, batch_id=batch_id, **kwargs ) return poller - batch_items = [{"query": f"?query={query}"} for query - in queries] if queries else [] - batch_poller = await self._route_client.begin_request_route_directions_batch( + batch_poller = await super().begin_request_route_directions_batch( format=ResponseFormat.JSON, - route_directions_batch_queries={"batch_items": batch_items}, + route_directions_batch_queries=BatchRequest( + batch_items=[BatchRequestItem(query=f"?query={query}") for query in queries] if queries else [] + ), **kwargs ) - batch_poller.batch_id = get_batch_id_from_poller(batch_poller.polling_method()) + + polling_method = batch_poller.polling_method() + if hasattr(polling_method, "_operation"): + operation = polling_method._operation + batch_poller.batch_id = operation._location_url.split('/')[-1].split('?')[0] + else: + batch_poller.batch_id = None + return batch_poller @distributed_trace_async @@ -684,28 +659,12 @@ async def get_route_matrix( :rtype: ~azure.maps.route.models.RouteMatrixResult :raises ~azure.core.exceptions.HttpResponseError: """ - return await self._route_client.request_route_matrix_sync( + return await super().request_route_matrix_sync( format=ResponseFormat.JSON, route_matrix_query=query, **kwargs ) - @overload - async def begin_get_route_matrix_batch( - self, - query: RouteMatrixQuery, - **kwargs: Any - ) -> AsyncLROPoller[RouteMatrixResult]: - pass - - @overload - async def begin_get_route_matrix_batch( - self, - matrix_id: str, - **kwargs: Any - ) -> AsyncLROPoller[RouteMatrixResult]: - pass - @distributed_trace_async async def begin_get_route_matrix_batch( self, @@ -830,12 +789,12 @@ async def begin_get_route_matrix_batch( matrix_id = kwargs.pop('matrix_id', None) if matrix_id: - return await self._route_client.begin_get_route_matrix( + return await super().begin_get_route_matrix( matrix_id=matrix_id, **kwargs ) - poller = await self._route_client.begin_request_route_matrix( + poller = await super().begin_request_route_matrix( format=ResponseFormat.JSON, route_matrix_query=query, **kwargs diff --git a/sdk/maps/azure-maps-route/azure/maps/route/models/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/models/__init__.py index 6f3ba8bd9658..85f614aa83a5 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/models/__init__.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/models/__init__.py @@ -1,110 +1,173 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- -from .._generated.models import ( - RouteRangeResult, - RouteDirections, - RouteInstructionsType, - ComputeTravelTime, - SectionType, - WindingnessLevel, - InclineLevel, - TravelMode, - RouteAvoidType, - RouteType, - VehicleLoadType, - VehicleEngineType, - RouteRepresentationForBestOrder, - AlternativeRouteType, - RouteMatrixQuery, - RouteMatrixResult, - RouteMatrixSummary, - RouteOptimizedWaypoint, - RouteSummary, - RouteGuidance, - Route, - RouteSectionTec, - BatchResultSummary, - GuidanceInstructionType, - JunctionType, - RouteLegSummary, - GeoJsonFeatureCollectionData, - GeoJsonGeometryCollectionData, -) - -from ._models import ( - LatLon, - BoundingBox, - GeoJsonObject, - GeoJsonFeatureData, - GeoJsonFeature, - GeoJsonFeatureCollection, - GeoJsonGeometry, - GeoJsonMultiLineString, - GeoJsonMultiPoint, - GeoJsonMultiPolygon, - GeoJsonPoint, - GeoJsonPolygon, - GeoJsonObjectType, - GeoJsonGeometryCollection, - RouteDirectionsBatchResult, - RouteDirectionsBatchItem, - RouteLeg, - TravelMode, - RouteDirectionsBatchItemResult, - GeoJsonMultiLineStringData, - GeoJsonMultiPolygonData, - GeoJsonMultiPointData -) +from ._models import BatchRequest +from ._models import BatchRequestItem +from ._models import BatchResult +from ._models import BatchResultItem +from ._models import BatchResultSummary +from ._models import EffectiveSetting +from ._models import ErrorAdditionalInfo +from ._models import ErrorDetail +from ._models import ErrorResponse +from ._models import GeoJsonFeature +from ._models import GeoJsonFeatureCollection +from ._models import GeoJsonFeatureCollectionData +from ._models import GeoJsonFeatureData +from ._models import GeoJsonGeometry +from ._models import GeoJsonGeometryCollection +from ._models import GeoJsonGeometryCollectionData +from ._models import GeoJsonLineString +from ._models import GeoJsonLineStringData +from ._models import GeoJsonMultiLineString +from ._models import GeoJsonMultiLineStringData +from ._models import GeoJsonMultiPoint +from ._models import GeoJsonMultiPointData +from ._models import GeoJsonMultiPolygon +from ._models import GeoJsonMultiPolygonData +from ._models import GeoJsonObject +from ._models import GeoJsonPoint +from ._models import GeoJsonPointData +from ._models import GeoJsonPolygon +from ._models import GeoJsonPolygonData +from ._models import LatLongPair +from ._models import Route +from ._models import RouteDirectionParameters +from ._models import RouteDirections +from ._models import RouteDirectionsBatchItem +from ._models import RouteDirectionsBatchItemResponse +from ._models import RouteDirectionsBatchResult +from ._models import RouteGuidance +from ._models import RouteInstruction +from ._models import RouteInstructionGroup +from ._models import RouteLeg +from ._models import RouteLegSummary +from ._models import RouteMatrix +from ._models import RouteMatrixQuery +from ._models import RouteMatrixResult +from ._models import RouteMatrixResultResponse +from ._models import RouteMatrixSummary +from ._models import RouteOptimizedWaypoint +from ._models import RouteRange +from ._models import RouteRangeResult +from ._models import RouteReport +from ._models import RouteSection +from ._models import RouteSectionTec +from ._models import RouteSectionTecCause +from ._models import RouteSummary +from ._enums import AlternativeRouteType +from ._enums import ComputeTravelTime +from ._enums import DelayMagnitude +from ._enums import DrivingSide +from ._enums import GeoJsonObjectType +from ._enums import GuidanceInstructionType +from ._enums import GuidanceManeuver +from ._enums import InclineLevel +from ._enums import JsonFormat +from ._enums import JunctionType +from ._enums import Report +from ._enums import ResponseFormat +from ._enums import ResponseSectionType +from ._enums import ResponseTravelMode +from ._enums import RouteAvoidType +from ._enums import RouteInstructionsType +from ._enums import RouteRepresentationForBestOrder +from ._enums import RouteType +from ._enums import SectionType +from ._enums import SimpleCategory +from ._enums import TravelMode +from ._enums import VehicleEngineType +from ._enums import VehicleLoadType +from ._enums import WindingnessLevel +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'RouteRangeResult', - 'LatLon', - 'BoundingBox', - 'BatchResultSummary', - 'JunctionType', - 'GuidanceInstructionType', - 'RouteLegSummary', - 'RouteDirections', - 'RouteInstructionsType', - 'ComputeTravelTime', - 'SectionType', - 'WindingnessLevel', - 'InclineLevel', - 'TravelMode', - 'RouteAvoidType', - 'RouteType', - 'VehicleLoadType', - 'VehicleEngineType', - 'RouteDirectionsBatchResult', - 'RouteRepresentationForBestOrder', - 'AlternativeRouteType', - 'RouteMatrixQuery', - 'RouteMatrixResult', - 'Route', - 'RouteLeg', - 'RouteSummary', - 'RouteGuidance', - 'RouteMatrixSummary', - 'RouteDirectionsBatchItem', - 'RouteOptimizedWaypoint', - 'GeoJsonObject', - 'GeoJsonFeatureData', - 'GeoJsonObjectType', - 'GeoJsonFeature', - 'GeoJsonFeatureCollection', - 'GeoJsonGeometry', - 'GeoJsonMultiLineString', - 'GeoJsonMultiPoint', - 'GeoJsonMultiPolygon', - 'GeoJsonPoint', - 'GeoJsonPolygon', - 'GeoJsonGeometryCollection', - 'TravelMode', - 'RouteDirectionsBatchItemResult', - 'RouteSectionTec', - 'GeoJsonFeatureCollectionData', - 'GeoJsonGeometryCollectionData', - 'GeoJsonMultiLineStringData', - 'GeoJsonMultiPolygonData', - 'GeoJsonMultiPointData' + "BatchRequest", + "BatchRequestItem", + "BatchResult", + "BatchResultItem", + "BatchResultSummary", + "EffectiveSetting", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "GeoJsonFeature", + "GeoJsonFeatureCollection", + "GeoJsonFeatureCollectionData", + "GeoJsonFeatureData", + "GeoJsonGeometry", + "GeoJsonGeometryCollection", + "GeoJsonGeometryCollectionData", + "GeoJsonLineString", + "GeoJsonLineStringData", + "GeoJsonMultiLineString", + "GeoJsonMultiLineStringData", + "GeoJsonMultiPoint", + "GeoJsonMultiPointData", + "GeoJsonMultiPolygon", + "GeoJsonMultiPolygonData", + "GeoJsonObject", + "GeoJsonPoint", + "GeoJsonPointData", + "GeoJsonPolygon", + "GeoJsonPolygonData", + "LatLongPair", + "Route", + "RouteDirectionParameters", + "RouteDirections", + "RouteDirectionsBatchItem", + "RouteDirectionsBatchItemResponse", + "RouteDirectionsBatchResult", + "RouteGuidance", + "RouteInstruction", + "RouteInstructionGroup", + "RouteLeg", + "RouteLegSummary", + "RouteMatrix", + "RouteMatrixQuery", + "RouteMatrixResult", + "RouteMatrixResultResponse", + "RouteMatrixSummary", + "RouteOptimizedWaypoint", + "RouteRange", + "RouteRangeResult", + "RouteReport", + "RouteSection", + "RouteSectionTec", + "RouteSectionTecCause", + "RouteSummary", + "AlternativeRouteType", + "ComputeTravelTime", + "DelayMagnitude", + "DrivingSide", + "GeoJsonObjectType", + "GuidanceInstructionType", + "GuidanceManeuver", + "InclineLevel", + "JsonFormat", + "JunctionType", + "Report", + "ResponseFormat", + "ResponseSectionType", + "ResponseTravelMode", + "RouteAvoidType", + "RouteInstructionsType", + "RouteRepresentationForBestOrder", + "RouteType", + "SectionType", + "SimpleCategory", + "TravelMode", + "VehicleEngineType", + "VehicleLoadType", + "WindingnessLevel", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_enums.py b/sdk/maps/azure-maps-route/azure/maps/route/models/_enums.py similarity index 51% rename from sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_enums.py rename to sdk/maps/azure-maps-route/azure/maps/route/models/_enums.py index 3136f5e0c51b..b593003b0131 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_enums.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/models/_enums.py @@ -13,23 +13,23 @@ class AlternativeRouteType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """AlternativeRouteType.""" - #: Allow any alternative route to be returned irrespective of how it compares to the reference - #: route in terms of optimality. ANY_ROUTE = "anyRoute" - #: Return an alternative route only if it is better than the reference route according to the - #: given planning criteria. + """Allow any alternative route to be returned irrespective of how it compares to the reference + route in terms of optimality.""" BETTER_ROUTE = "betterRoute" + """Return an alternative route only if it is better than the reference route according to the + given planning criteria.""" class ComputeTravelTime(str, Enum, metaclass=CaseInsensitiveEnumMeta): """ComputeTravelTime.""" - #: Does not compute additional travel times. NONE = "none" - #: Computes travel times for all types of traffic information and specifies all results in the - #: fields noTrafficTravelTimeInSeconds, historicTrafficTravelTimeInSeconds and - #: liveTrafficIncidentsTravelTimeInSeconds being included in the summaries in the route response. + """Does not compute additional travel times.""" ALL = "all" + """Computes travel times for all types of traffic information and specifies all results in the + fields noTrafficTravelTimeInSeconds, historicTrafficTravelTimeInSeconds and + liveTrafficIncidentsTravelTimeInSeconds being included in the summaries in the route response.""" class DelayMagnitude(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -38,25 +38,25 @@ class DelayMagnitude(str, Enum, metaclass=CaseInsensitiveEnumMeta): `_. """ - #: Unknown. UNKNOWN = "0" - #: Minor. + """Unknown.""" MINOR = "1" - #: Moderate. + """Minor.""" MODERATE = "2" - #: Major. + """Moderate.""" MAJOR = "3" - #: Undefined, used for road closures and other indefinite delays. + """Major.""" UNDEFINED = "4" + """Undefined, used for road closures and other indefinite delays.""" class DrivingSide(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Indicates left-hand vs. right-hand side driving at the point of the maneuver.""" - #: Left side. LEFT = "LEFT" - #: Right side. + """Left side.""" RIGHT = "RIGHT" + """Right side.""" class GeoJsonObjectType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -65,130 +65,130 @@ class GeoJsonObjectType(str, Enum, metaclass=CaseInsensitiveEnumMeta): FeatureCollection. """ - #: ``GeoJSON Point`` geometry. GEO_JSON_POINT = "Point" - #: ``GeoJSON MultiPoint`` geometry. + """``GeoJSON Point`` geometry.""" GEO_JSON_MULTI_POINT = "MultiPoint" - #: ``GeoJSON LineString`` geometry. + """``GeoJSON MultiPoint`` geometry.""" GEO_JSON_LINE_STRING = "LineString" - #: ``GeoJSON MultiLineString`` geometry. + """``GeoJSON LineString`` geometry.""" GEO_JSON_MULTI_LINE_STRING = "MultiLineString" - #: ``GeoJSON Polygon`` geometry. + """``GeoJSON MultiLineString`` geometry.""" GEO_JSON_POLYGON = "Polygon" - #: ``GeoJSON MultiPolygon`` geometry. + """``GeoJSON Polygon`` geometry.""" GEO_JSON_MULTI_POLYGON = "MultiPolygon" - #: ``GeoJSON GeometryCollection`` geometry. + """``GeoJSON MultiPolygon`` geometry.""" GEO_JSON_GEOMETRY_COLLECTION = "GeometryCollection" - #: ``GeoJSON Feature`` object. + """``GeoJSON GeometryCollection`` geometry.""" GEO_JSON_FEATURE = "Feature" - #: ``GeoJSON FeatureCollection`` object. + """``GeoJSON Feature`` object.""" GEO_JSON_FEATURE_COLLECTION = "FeatureCollection" + """``GeoJSON FeatureCollection`` object.""" class GuidanceInstructionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Type of the instruction, e.g., turn or change of road form.""" - #: Turn. TURN = "TURN" - #: Road Change. + """Turn.""" ROAD_CHANGE = "ROAD_CHANGE" - #: Departure location. + """Road Change.""" LOCATION_DEPARTURE = "LOCATION_DEPARTURE" - #: Arrival location. + """Departure location.""" LOCATION_ARRIVAL = "LOCATION_ARRIVAL" - #: Direction information. + """Arrival location.""" DIRECTION_INFO = "DIRECTION_INFO" - #: Way point location. + """Direction information.""" LOCATION_WAYPOINT = "LOCATION_WAYPOINT" + """Way point location.""" class GuidanceManeuver(str, Enum, metaclass=CaseInsensitiveEnumMeta): """A code identifying the maneuver.""" - #: You have arrived. ARRIVE = "ARRIVE" - #: You have arrived. Your destination is on the left. + """You have arrived.""" ARRIVE_LEFT = "ARRIVE_LEFT" - #: You have arrived. Your destination is on the right. + """You have arrived. Your destination is on the left.""" ARRIVE_RIGHT = "ARRIVE_RIGHT" - #: Leave. + """You have arrived. Your destination is on the right.""" DEPART = "DEPART" - #: Keep straight on. + """Leave.""" STRAIGHT = "STRAIGHT" - #: Keep right. + """Keep straight on.""" KEEP_RIGHT = "KEEP_RIGHT" - #: Bear right. + """Keep right.""" BEAR_RIGHT = "BEAR_RIGHT" - #: Turn right. + """Bear right.""" TURN_RIGHT = "TURN_RIGHT" - #: Turn sharp right. + """Turn right.""" SHARP_RIGHT = "SHARP_RIGHT" - #: Keep left. + """Turn sharp right.""" KEEP_LEFT = "KEEP_LEFT" - #: Bear left. + """Keep left.""" BEAR_LEFT = "BEAR_LEFT" - #: Turn left. + """Bear left.""" TURN_LEFT = "TURN_LEFT" - #: Turn sharp left. + """Turn left.""" SHARP_LEFT = "SHARP_LEFT" - #: Make a U-turn. + """Turn sharp left.""" MAKE_U_TURN = "MAKE_UTURN" - #: Take the motorway. + """Make a U-turn.""" ENTER_MOTORWAY = "ENTER_MOTORWAY" - #: Take the freeway. + """Take the motorway.""" ENTER_FREEWAY = "ENTER_FREEWAY" - #: Take the highway. + """Take the freeway.""" ENTER_HIGHWAY = "ENTER_HIGHWAY" - #: Take the exit. + """Take the highway.""" TAKE_EXIT = "TAKE_EXIT" - #: Take the left exit. + """Take the exit.""" MOTORWAY_EXIT_LEFT = "MOTORWAY_EXIT_LEFT" - #: Take the right exit. + """Take the left exit.""" MOTORWAY_EXIT_RIGHT = "MOTORWAY_EXIT_RIGHT" - #: Take the ferry. + """Take the right exit.""" TAKE_FERRY = "TAKE_FERRY" - #: Cross the roundabout. + """Take the ferry.""" ROUNDABOUT_CROSS = "ROUNDABOUT_CROSS" - #: At the roundabout take the exit on the right. + """Cross the roundabout.""" ROUNDABOUT_RIGHT = "ROUNDABOUT_RIGHT" - #: At the roundabout take the exit on the left. + """At the roundabout take the exit on the right.""" ROUNDABOUT_LEFT = "ROUNDABOUT_LEFT" - #: Go around the roundabout. + """At the roundabout take the exit on the left.""" ROUNDABOUT_BACK = "ROUNDABOUT_BACK" - #: Try to make a U-turn. + """Go around the roundabout.""" TRY_MAKE_U_TURN = "TRY_MAKE_UTURN" - #: Follow. + """Try to make a U-turn.""" FOLLOW = "FOLLOW" - #: Switch to the parallel road. + """Follow.""" SWITCH_PARALLEL_ROAD = "SWITCH_PARALLEL_ROAD" - #: Switch to the main road. + """Switch to the parallel road.""" SWITCH_MAIN_ROAD = "SWITCH_MAIN_ROAD" - #: Take the ramp. + """Switch to the main road.""" ENTRANCE_RAMP = "ENTRANCE_RAMP" - #: You have reached the waypoint. It is on the left. + """Take the ramp.""" WAYPOINT_LEFT = "WAYPOINT_LEFT" - #: You have reached the waypoint. It is on the right. + """You have reached the waypoint. It is on the left.""" WAYPOINT_RIGHT = "WAYPOINT_RIGHT" - #: You have reached the waypoint. + """You have reached the waypoint. It is on the right.""" WAYPOINT_REACHED = "WAYPOINT_REACHED" + """You have reached the waypoint.""" class InclineLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): """InclineLevel.""" - #: low LOW = "low" - #: normal + """low""" NORMAL = "normal" - #: high + """normal""" HIGH = "high" + """high""" class JsonFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): """JsonFormat.""" - #: `The JavaScript Object Notation Data Interchange Format `_ JSON = "json" + """`The JavaScript Object Notation Data Interchange Format `_""" class JunctionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -196,57 +196,57 @@ class JunctionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): instructions are generated for entering and leaving the roundabout. """ - #: regular REGULAR = "REGULAR" - #: roundabout + """regular""" ROUNDABOUT = "ROUNDABOUT" - #: bifurcation + """roundabout""" BIFURCATION = "BIFURCATION" + """bifurcation""" class Report(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Report.""" - #: Reports the effective parameters or data used when calling the API. EFFECTIVE_SETTINGS = "effectiveSettings" + """Reports the effective parameters or data used when calling the API.""" class ResponseFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): """ResponseFormat.""" - #: `The JavaScript Object Notation Data Interchange Format `_ JSON = "json" - #: `The Extensible Markup Language `_ + """`The JavaScript Object Notation Data Interchange Format `_""" XML = "xml" + """`The Extensible Markup Language `_""" class ResponseSectionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Section types of the reported route response.""" - #: Sections of the route that are cars or trains. CAR_OR_TRAIN = "CAR_TRAIN" - #: Sections indicating which countries the route is in. + """Sections of the route that are cars or trains.""" COUNTRY = "COUNTRY" - #: Sections of the route that are ferries. + """Sections indicating which countries the route is in.""" FERRY = "FERRY" - #: Sections of the route that are motorways. + """Sections of the route that are ferries.""" MOTORWAY = "MOTORWAY" - #: Sections of the route that are only suited for pedestrians. + """Sections of the route that are motorways.""" PEDESTRIAN = "PEDESTRIAN" - #: Sections of the route that require a toll to be payed. + """Sections of the route that are only suited for pedestrians.""" TOLL_ROAD = "TOLL_ROAD" - #: Sections of the route that require a toll vignette to be present. + """Sections of the route that require a toll to be payed.""" TOLL_VIGNETTE = "TOLL_VIGNETTE" - #: Sections of the route that contain traffic information. + """Sections of the route that require a toll vignette to be present.""" TRAFFIC = "TRAFFIC" - #: Sections in relation to the request parameter ``travelMode``. + """Sections of the route that contain traffic information.""" TRAVEL_MODE = "TRAVEL_MODE" - #: Sections of the route that are tunnels. + """Sections in relation to the request parameter ``travelMode``.""" TUNNEL = "TUNNEL" - #: Sections of the route that require use of carpool (HOV/High Occupancy Vehicle) lanes. + """Sections of the route that are tunnels.""" CARPOOL = "CARPOOL" - #: Sections of the route that are located within urban areas. + """Sections of the route that require use of carpool (HOV/High Occupancy Vehicle) lanes.""" URBAN = "URBAN" + """Sections of the route that are located within urban areas.""" class ResponseTravelMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -254,125 +254,125 @@ class ResponseTravelMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): of transport is not possible in this section. """ - #: The returned routes are optimized for cars. CAR = "car" - #: The returned routes are optimized for commercial vehicles, like for trucks. + """The returned routes are optimized for cars.""" TRUCK = "truck" - #: The returned routes are optimized for taxis. BETA functionality. + """The returned routes are optimized for commercial vehicles, like for trucks.""" TAXI = "taxi" - #: The returned routes are optimized for buses, including the use of bus only lanes. BETA - #: functionality. + """The returned routes are optimized for taxis. BETA functionality.""" BUS = "bus" - #: The returned routes are optimized for vans. BETA functionality. + """The returned routes are optimized for buses, including the use of bus only lanes. BETA + functionality.""" VAN = "van" - #: The returned routes are optimized for motorcycles. BETA functionality. + """The returned routes are optimized for vans. BETA functionality.""" MOTORCYCLE = "motorcycle" - #: The returned routes are optimized for bicycles, including use of bicycle lanes. + """The returned routes are optimized for motorcycles. BETA functionality.""" BICYCLE = "bicycle" - #: The returned routes are optimized for pedestrians, including the use of sidewalks. + """The returned routes are optimized for bicycles, including use of bicycle lanes.""" PEDESTRIAN = "pedestrian" - #: The given mode of transport is not possible in this section + """The returned routes are optimized for pedestrians, including the use of sidewalks.""" OTHER = "other" + """The given mode of transport is not possible in this section""" class RouteAvoidType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """RouteAvoidType.""" - #: Avoids toll roads. TOLL_ROADS = "tollRoads" - #: Avoids motorways + """Avoids toll roads.""" MOTORWAYS = "motorways" - #: Avoids ferries + """Avoids motorways""" FERRIES = "ferries" - #: Avoids unpaved roads + """Avoids ferries""" UNPAVED_ROADS = "unpavedRoads" - #: Avoids routes that require the use of carpool (HOV/High Occupancy Vehicle) lanes. + """Avoids unpaved roads""" CARPOOLS = "carpools" - #: Avoids using the same road multiple times. Most useful in conjunction with ``routeType``\ - #: =thrilling. + """Avoids routes that require the use of carpool (HOV/High Occupancy Vehicle) lanes.""" ALREADY_USED_ROADS = "alreadyUsedRoads" - #: Avoids border crossings in route calculation. + """Avoids using the same road multiple times. Most useful in conjunction with ``routeType``\\ + =thrilling.""" BORDER_CROSSINGS = "borderCrossings" + """Avoids border crossings in route calculation.""" class RouteInstructionsType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """RouteInstructionsType.""" - #: Returns raw instruction data without human-readable messages. CODED = "coded" - #: Returns raw instructions data with human-readable messages in plain text. + """Returns raw instruction data without human-readable messages.""" TEXT = "text" - #: Returns raw instruction data with tagged human-readable messages to permit formatting. A - #: human-readable message is built up from repeatable identified elements. These are tagged to - #: allow client applications to format them correctly. The following message components are tagged - #: when instructionsType=tagged: street, roadNumber, signpostText, exitNumber, - #: roundaboutExitNumber. - #: - #: Example of tagged 'Turn left' message:​ - #: - #: .. code-block:: - #: - #: Turn left onto A4/E19 - #: towards Den Haag + """Returns raw instructions data with human-readable messages in plain text.""" TAGGED = "tagged" + """Returns raw instruction data with tagged human-readable messages to permit formatting. A + human-readable message is built up from repeatable identified elements. These are tagged to + allow client applications to format them correctly. The following message components are tagged + when instructionsType=tagged: street, roadNumber, signpostText, exitNumber, + roundaboutExitNumber. + + Example of tagged 'Turn left' message: + + .. code-block:: + + Turn left onto A4/E19 + towards Den Haag""" class RouteRepresentationForBestOrder(str, Enum, metaclass=CaseInsensitiveEnumMeta): """RouteRepresentationForBestOrder.""" - #: Includes route geometry in the response. POLYLINE = "polyline" - #: Summary as per polyline but excluding the point geometry elements for the routes in the - #: response. + """Includes route geometry in the response.""" SUMMARY_ONLY = "summaryOnly" - #: Includes only the optimized waypoint indices but does not include the route geometry in the - #: response. + """Summary as per polyline but excluding the point geometry elements for the routes in the + response.""" NONE = "none" + """Includes only the optimized waypoint indices but does not include the route geometry in the + response.""" class RouteType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """RouteType.""" - #: The fastest route. FASTEST = "fastest" - #: The shortest route by distance. + """The fastest route.""" SHORTEST = "shortest" - #: A route balanced by economy and speed. + """The shortest route by distance.""" ECONOMY = "eco" - #: Includes interesting or challenging roads and uses as few motorways as possible. You can choose - #: the level of turns included and also the degree of hilliness. See the hilliness and windingness - #: parameters for how to set this. There is a limit of 900 km on routes planned with - #: ``routeType``\ =thrilling + """A route balanced by economy and speed.""" THRILLING = "thrilling" + """Includes interesting or challenging roads and uses as few motorways as possible. You can choose + the level of turns included and also the degree of hilliness. See the hilliness and windingness + parameters for how to set this. There is a limit of 900 km on routes planned with + ``routeType``\\ =thrilling""" class SectionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """SectionType.""" - #: Sections of the route that are cars or trains. CAR_OR_TRAIN = "carTrain" - #: Sections indicating which countries the route is in. + """Sections of the route that are cars or trains.""" COUNTRY = "country" - #: Sections of the route that are ferries. + """Sections indicating which countries the route is in.""" FERRY = "ferry" - #: Sections of the route that are motorways. + """Sections of the route that are ferries.""" MOTORWAY = "motorway" - #: Sections of the route that are only suited for pedestrians. + """Sections of the route that are motorways.""" PEDESTRIAN = "pedestrian" - #: Sections of the route that require a toll to be payed. + """Sections of the route that are only suited for pedestrians.""" TOLL_ROAD = "tollRoad" - #: Sections of the route that require a toll vignette to be present. + """Sections of the route that require a toll to be payed.""" TOLL_VIGNETTE = "tollVignette" - #: Sections of the route that contain traffic information. + """Sections of the route that require a toll vignette to be present.""" TRAFFIC = "traffic" - #: Sections in relation to the request parameter ``travelMode``. + """Sections of the route that contain traffic information.""" TRAVEL_MODE = "travelMode" - #: Sections of the route that are tunnels. + """Sections in relation to the request parameter ``travelMode``.""" TUNNEL = "tunnel" - #: Sections of the route that require use of carpool (HOV/High Occupancy Vehicle) lanes. + """Sections of the route that are tunnels.""" CARPOOL = "carpool" - #: Sections of the route that are located within urban areas. + """Sections of the route that require use of carpool (HOV/High Occupancy Vehicle) lanes.""" URBAN = "urban" + """Sections of the route that are located within urban areas.""" class SimpleCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -380,82 +380,82 @@ class SimpleCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): detailed information. """ - #: Traffic jam. JAM = "JAM" - #: Road work. + """Traffic jam.""" ROAD_WORK = "ROAD_WORK" - #: Road closure. + """Road work.""" ROAD_CLOSURE = "ROAD_CLOSURE" - #: Other. + """Road closure.""" OTHER = "OTHER" + """Other.""" class TravelMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """TravelMode.""" - #: The returned routes are optimized for cars. CAR = "car" - #: The returned routes are optimized for commercial vehicles, like for trucks. + """The returned routes are optimized for cars.""" TRUCK = "truck" - #: The returned routes are optimized for taxis. BETA functionality. + """The returned routes are optimized for commercial vehicles, like for trucks.""" TAXI = "taxi" - #: The returned routes are optimized for buses, including the use of bus only lanes. BETA - #: functionality. + """The returned routes are optimized for taxis. BETA functionality.""" BUS = "bus" - #: The returned routes are optimized for vans. BETA functionality. + """The returned routes are optimized for buses, including the use of bus only lanes. BETA + functionality.""" VAN = "van" - #: The returned routes are optimized for motorcycles. BETA functionality. + """The returned routes are optimized for vans. BETA functionality.""" MOTORCYCLE = "motorcycle" - #: The returned routes are optimized for bicycles, including use of bicycle lanes. + """The returned routes are optimized for motorcycles. BETA functionality.""" BICYCLE = "bicycle" - #: The returned routes are optimized for pedestrians, including the use of sidewalks. + """The returned routes are optimized for bicycles, including use of bicycle lanes.""" PEDESTRIAN = "pedestrian" + """The returned routes are optimized for pedestrians, including the use of sidewalks.""" class VehicleEngineType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """VehicleEngineType.""" - #: Internal combustion engine. COMBUSTION = "combustion" - #: Electric engine. + """Internal combustion engine.""" ELECTRIC = "electric" + """Electric engine.""" class VehicleLoadType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """VehicleLoadType.""" - #: Explosives US_HAZMAT_CLASS1 = "USHazmatClass1" - #: Compressed gas + """Explosives""" US_HAZMAT_CLASS2 = "USHazmatClass2" - #: Flammable liquids + """Compressed gas""" US_HAZMAT_CLASS3 = "USHazmatClass3" - #: Flammable solids + """Flammable liquids""" US_HAZMAT_CLASS4 = "USHazmatClass4" - #: Oxidizers + """Flammable solids""" US_HAZMAT_CLASS5 = "USHazmatClass5" - #: Poisons + """Oxidizers""" US_HAZMAT_CLASS6 = "USHazmatClass6" - #: Radioactive + """Poisons""" US_HAZMAT_CLASS7 = "USHazmatClass7" - #: Corrosives + """Radioactive""" US_HAZMAT_CLASS8 = "USHazmatClass8" - #: Miscellaneous + """Corrosives""" US_HAZMAT_CLASS9 = "USHazmatClass9" - #: Explosives + """Miscellaneous""" OTHER_HAZMAT_EXPLOSIVE = "otherHazmatExplosive" - #: Miscellaneous + """Explosives""" OTHER_HAZMAT_GENERAL = "otherHazmatGeneral" - #: Harmful to water + """Miscellaneous""" OTHER_HAZMAT_HARMFUL_TO_WATER = "otherHazmatHarmfulToWater" + """Harmful to water""" class WindingnessLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): """WindingnessLevel.""" - #: low LOW = "low" - #: normal + """low""" NORMAL = "normal" - #: high + """normal""" HIGH = "high" + """high""" diff --git a/sdk/maps/azure-maps-route/azure/maps/route/models/_models.py b/sdk/maps/azure-maps-route/azure/maps/route/models/_models.py index 0c48f037af60..ea31764fdb6c 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/models/_models.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/models/_models.py @@ -1,1096 +1,1540 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -# pylint: disable=unused-import,ungrouped-imports, super-init-not-called, W0212, C0302 -from typing import List, Optional, Union, NamedTuple -from enum import Enum -import msrest.serialization - -from azure.core import CaseInsensitiveEnumMeta -from .._generated.models import ( - BatchResult as GenBatchResult, - RouteLeg as GenRouteLeg, - BatchResultSummary, - ErrorDetail, - RouteReport, - RouteSectionTec, - GuidanceInstructionType -) - -class LatLon(NamedTuple): - """Represents coordinate latitude and longitude - - :keyword lat: The coordinate as latitude. - :paramtype lat: float - :keyword lon: The coordinate as longitude. - :paramtype lon: float - """ - lat: float = 0 - lon: float = 0 - -class BoundingBox(NamedTuple): - """Represents information about the coordinate range - - :keyword west: The westmost value of coordinates. - :paramtype west: float - :keyword south: The southmost value of coordinates. - :paramtype south: float - :keyword east: The eastmost value of coordinates. - :paramtype east: float - :keyword north: The northmost value of coordinates. - :paramtype north: float - """ - west: float = 0.0 - south: float = 0.0 - east: float = 0.0 - north: float = 0.0 +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- -# cSpell:disable -class RouteSection(object): - """Route sections contain additional information about parts of a route. - Each section contains at least the elements ``startPointIndex``, ``endPointIndex``, and ``sectionType``. +import sys +from typing import Any, List, Optional, TYPE_CHECKING, Union - Variables are only populated by the server, and will be ignored when sending a request. +from .. import _serialization - :ivar start_point_index: Index of the first point (offset 0) in the route this section applies - to. - :vartype start_point_index: int - :ivar end_point_index: Index of the last point (offset 0) in the route this section applies to. - :vartype end_point_index: int - :ivar section_type: Section types of the reported route response. Known values are: - "CAR_TRAIN", "COUNTRY", "FERRY", "MOTORWAY", "PEDESTRIAN", "TOLL_ROAD", "TOLL_VIGNETTE", - "TRAFFIC", "TRAVEL_MODE", "TUNNEL", "CARPOOL", and "URBAN". - :vartype section_type: str or ~azure.maps.route.models.SectionType - :ivar travel_mode: Travel mode for the calculated route. The value will be set to ``other`` if - the requested mode of transport is not possible in this section. Known values are: "car", - "truck", "taxi", "bus", "van", "motorcycle", "bicycle", "pedestrian", and "other". - :vartype travel_mode: str or ~azure.maps.route.models.TravelMode - :ivar simple_category: Type of the incident. Can currently be JAM, ROAD_WORK, ROAD_CLOSURE, or - OTHER. See "tec" for detailed information. Known values are: "JAM", "ROAD_WORK", - "ROAD_CLOSURE", and "OTHER". - :vartype simple_category: str or ~azure.maps.route.models.SimpleCategory - :ivar effective_speed_in_kmh: Effective speed of the incident in km/h, averaged over its entire - length. - :vartype effective_speed_in_kmh: int - :ivar delay_in_seconds: Delay in seconds caused by the incident. - :vartype delay_in_seconds: int - :ivar delay_magnitude: The magnitude of delay caused by the incident. These values correspond - to the values of the response field ty of the `Get Traffic Incident Detail API - `_. Known values - are: "0", "1", "2", "3", and "4". - :vartype delay_magnitude: str or ~azure.maps.route.models.DelayMagnitude - :ivar tec: Details of the traffic event, using definitions in the `TPEG2-TEC - `_ standard. Can contain effectCode and causes - elements. - :vartype tec: ~azure.maps.route.models.RouteSectionTec +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore + +if TYPE_CHECKING: + from .. import models as _models +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object + + +class BatchRequest(_serialization.Model): + """This type represents the request body for the Batch service. + + :ivar batch_items: The list of queries to process. + :vartype batch_items: list[~azure.maps.route.models.BatchRequestItem] """ - _validation = { - "start_point_index": {"readonly": True}, - "end_point_index": {"readonly": True}, - "section_type": {"readonly": True}, - "travel_mode": {"readonly": True}, - "simple_category": {"readonly": True}, - "effective_speed_in_kmh": {"readonly": True}, - "delay_in_seconds": {"readonly": True}, - "delay_magnitude": {"readonly": True}, + _attribute_map = { + "batch_items": {"key": "batchItems", "type": "[BatchRequestItem]"}, } + def __init__(self, *, batch_items: Optional[List["_models.BatchRequestItem"]] = None, **kwargs: Any) -> None: + """ + :keyword batch_items: The list of queries to process. + :paramtype batch_items: list[~azure.maps.route.models.BatchRequestItem] + """ + super().__init__(**kwargs) + self.batch_items = batch_items + + +class BatchRequestItem(_serialization.Model): + """Batch request object. + + :ivar query: This parameter contains a query string used to perform an unstructured geocoding + operation. The query string will be passed verbatim to the search API for processing. + :vartype query: str + """ + _attribute_map = { - "start_point_index": {"key": "startPointIndex", "type": "int"}, - "end_point_index": {"key": "endPointIndex", "type": "int"}, - "section_type": {"key": "sectionType", "type": "str"}, - "travel_mode": {"key": "travelMode", "type": "str"}, - "simple_category": {"key": "simpleCategory", "type": "str"}, - "effective_speed_in_kmh": {"key": "effectiveSpeedInKmh", "type": "int"}, - "delay_in_seconds": {"key": "delayInSeconds", "type": "int"}, - "delay_magnitude": {"key": "magnitudeOfDelay", "type": "str"}, - "tec": {"key": "tec", "type": "RouteSectionTec"}, + "query": {"key": "query", "type": "str"}, } - def __init__(self, *, tec: Optional["RouteSectionTec"] = None, **kwargs): + def __init__(self, *, query: Optional[str] = None, **kwargs: Any) -> None: """ - :keyword tec: Details of the traffic event, using definitions in the `TPEG2-TEC - `_ standard. Can contain effectCode and causes - elements. - :paramtype tec: ~azure.maps.route.models.RouteSectionTec + :keyword query: This parameter contains a query string used to perform an unstructured + geocoding operation. The query string will be passed verbatim to the search API for processing. + :paramtype query: str """ super().__init__(**kwargs) - self.start_point_index = None - self.end_point_index = None - self.section_type = None - self.travel_mode = None - self.simple_category = None - self.effective_speed_in_kmh = None - self.delay_in_seconds = None - self.delay_magnitude = None - self.tec = tec + self.query = query -class RouteDirectionsBatchItemResult(object): - """The result of the query. RouteDirections if the query completed successfully, ErrorResponse otherwise. + +class BatchResult(_serialization.Model): + """This object is returned from a successful Batch service call. Extend with 'batchItems' + property. Variables are only populated by the server, and will be ignored when sending a request. - :ivar error: The error object. - :vartype error: ~azure.maps.route.models.ErrorDetail - :ivar format_version: Format Version property. - :vartype format_version: str - :ivar routes: Routes array. - :vartype routes: list[~azure.maps.route.models.Route] - :ivar optimized_waypoints: Optimized sequence of waypoints. It shows the index from the user - provided waypoint sequence for the original and optimized list. For instance, a response: + :ivar batch_summary: Summary of the results for the batch request. + :vartype batch_summary: ~azure.maps.route.models.BatchResultSummary + """ - .. code-block:: + _validation = { + "batch_summary": {"readonly": True}, + } - - - - - + _attribute_map = { + "batch_summary": {"key": "summary", "type": "BatchResultSummary"}, + } - means that the original sequence is [0, 1, 2] and optimized sequence is [1, 2, 0]. Since the - index starts by 0 the original is "first, second, third" while the optimized is "second, third, - first". - :vartype optimized_waypoints: list[~azure.maps.route.models.RouteOptimizedWaypoint] - :ivar report: Reports the effective settings used in the current call. - :vartype report: RouteReport + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.batch_summary = None + + +class BatchResultItem(_serialization.Model): + """An item returned from Batch API. Extend with 'response' property. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar status_code: HTTP request status code. + :vartype status_code: int """ _validation = { - "format_version": {"readonly": True}, - "routes": {"readonly": True}, - "optimized_waypoints": {"readonly": True}, + "status_code": {"readonly": True}, } _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, - "format_version": {"key": "formatVersion", "type": "str"}, - "routes": {"key": "routes", "type": "[Route]"}, - "optimized_waypoints": {"key": "optimizedWaypoints", "type": "[RouteOptimizedWaypoint]"}, - "report": {"key": "report", "type": "RouteReport"}, + "status_code": {"key": "statusCode", "type": "int"}, } - def __init__( - self, *, error: Optional["ErrorDetail"] = None, report: Optional["RouteReport"] = None, **kwargs - ): - """ - :keyword error: The error object. - :paramtype error: ~azure.maps.route.models.ErrorDetail - :keyword report: Reports the effective settings used in the current call. - :paramtype report: ~azure.maps.route.models.RouteReport - """ - super().__init__(report=report, error=error, **kwargs) - self.error = error - self.format_version = None - self.routes = None - self.optimized_waypoints = None - self.report = report + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.status_code = None -class RouteDirectionsBatchItem(object): - """An item returned from Route Directions Batch service call. + +class BatchResultSummary(_serialization.Model): + """Summary of the results for the batch request. Variables are only populated by the server, and will be ignored when sending a request. - :ivar result: The result of the query. RouteDirections if the query completed successfully, - ErrorResponse otherwise. - :vartype result: RouteDirectionsBatchItemResult + :ivar successful_requests: Number of successful requests in the batch. + :vartype successful_requests: int + :ivar total_requests: Total number of requests in the batch. + :vartype total_requests: int """ _validation = { - "result": {"readonly": True}, + "successful_requests": {"readonly": True}, + "total_requests": {"readonly": True}, } _attribute_map = { - "result": {"key": "result", "type": "RouteDirectionsBatchItemResult"}, + "successful_requests": {"key": "successfulRequests", "type": "int"}, + "total_requests": {"key": "totalRequests", "type": "int"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.result = None + self.successful_requests = None + self.total_requests = None -class RouteDirectionsBatchResult(object): - """This object is returned from a successful Route Directions Batch service call. + +class EffectiveSetting(_serialization.Model): + """Effective parameter or data used when calling this Route API. Variables are only populated by the server, and will be ignored when sending a request. - :keyword summary: Summary of the results for the batch request. - :paramtype summary: ~azure.maps.route.models.BatchResultSummary - :keyword items: Array containing the batch results. - :paramtype items: list[RouteDirectionsBatchItem] + :ivar key: Name of the parameter used. + :vartype key: str + :ivar value: Value of the parameter used. + :vartype value: str """ - def __init__( - self, - **kwargs - ): - self.summary = kwargs.get('summary', None) - self.items = kwargs.get('items', None) -class RouteLeg(GenRouteLeg): - """A description of a part of a route, comprised of a list of points. - Each additional waypoint provided in the request will result in an additional - leg in the returned route. + _validation = { + "key": {"readonly": True}, + "value": {"readonly": True}, + } + + _attribute_map = { + "key": {"key": "key", "type": "str"}, + "value": {"key": "value", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.key = None + self.value = None + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. Variables are only populated by the server, and will be ignored when sending a request. - :ivar summary: Summary object for route section. - :vartype summary: ~azure.maps.route.models.RouteLegSummary - :ivar points: Points array. - :vartype points: list[LatLon] + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON """ - def __init__(self, **kwargs): + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.summary = None - self.points = None + self.type = None + self.info = None -class GeoJsonObjectType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - Point, - MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and - FeatureCollection. - """ - GEO_JSON_POINT = "Point" #: ``GeoJSON Point`` geometry. - GEO_JSON_MULTI_POINT = "MultiPoint" #: ``GeoJSON MultiPoint`` geometry. - GEO_JSON_LINE_STRING = "LineString" #: ``GeoJSON LineString`` geometry. - GEO_JSON_MULTI_LINE_STRING = "MultiLineString" #: ``GeoJSON MultiLineString`` geometry. - GEO_JSON_POLYGON = "Polygon" #: ``GeoJSON Polygon`` geometry. - GEO_JSON_MULTI_POLYGON = "MultiPolygon" #: ``GeoJSON MultiPolygon`` geometry. - GEO_JSON_GEOMETRY_COLLECTION = "GeometryCollection" #: ``GeoJSON GeometryCollection`` geometry. - GEO_JSON_FEATURE = "Feature" #: ``GeoJSON Feature`` object. - GEO_JSON_FEATURE_COLLECTION = "FeatureCollection" #: ``GeoJSON FeatureCollection`` object. - -class GeoJsonObject(msrest.serialization.Model): - """A valid ``GeoJSON`` object. - Please refer to `RFC 7946 `__ for details. - - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: GeoJsonFeature, GeoJsonFeatureCollection, GeoJsonGeometry, - GeoJsonGeometryCollection, GeoJsonLineString, GeoJsonMultiLineString, - GeoJsonMultiPoint, GeoJsonMultiPolygon, GeoJsonPoint, GeoJsonPolygon. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON - object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, - GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values - include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", - "GeometryCollection", "Feature", "FeatureCollection". - :type type: str or GeoJsonObjectType +class ErrorDetail(_serialization.Model): + """The error detail. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.maps.route.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.maps.route.models.ErrorAdditionalInfo] """ _validation = { - 'type': {'required': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, } - _subtype_map = { - 'type': {'Feature': 'GeoJsonFeature', 'FeatureCollection': 'GeoJsonFeatureCollection', - 'GeoJsonGeometry': 'GeoJsonGeometry', 'GeometryCollection': 'GeoJsonGeometryCollection', - 'LineString': 'GeoJsonLineString', 'MultiLineString': 'GeoJsonMultiLineString', - 'MultiPoint': 'GeoJsonMultiPoint', 'MultiPolygon': 'GeoJsonMultiPolygon', - 'Point': 'GeoJsonPoint', 'Polygon': 'GeoJsonPolygon' - } + 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 + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.maps.route.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, } - def __init__( - self, - _type: Union[str, GeoJsonObjectType] = None, - **kwargs - ): - super(GeoJsonObject, self).__init__(**kwargs) - self.type = _type # type: Optional[Union[str, GeoJsonObjectType]] + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error object. + :paramtype error: ~azure.maps.route.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error -class GeoJsonFeatureData(msrest.serialization.Model): + +class GeoJsonFeatureData(_serialization.Model): """GeoJsonFeatureData. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :param geometry: Required. A valid ``GeoJSON`` object. Please refer to `RFC 7946 - `__ for details. - :type geometry: ~azure.maps.route.models.GeoJsonObject - :param properties: Properties can contain any additional metadata about the ``Feature``. Value + :ivar geometry: A valid ``GeoJSON`` geometry object. The type must be one of the seven valid + GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon + and GeometryCollection. Please refer to `RFC 7946 + `__ for details. Required. + :vartype geometry: ~azure.maps.route.models.GeoJsonGeometry + :ivar properties: Properties can contain any additional metadata about the ``Feature``. Value can be any JSON object or a JSON null value. - :type properties: object - :param feature_type: The type of the feature. The value depends on the data model the current + :vartype properties: JSON + :ivar id: Identifier for the feature. + :vartype id: str + :ivar feature_type: The type of the feature. The value depends on the data model the current feature is part of. Some data models may have an empty value. - :type feature_type: str + :vartype feature_type: str """ _validation = { - 'geometry': {'required': True}, + "geometry": {"required": True}, } _attribute_map = { - 'geometry': {'key': 'geometry', 'type': 'GeoJsonObject'}, - 'properties': {'key': 'properties', 'type': 'object'}, - 'feature_type': {'key': 'featureType', 'type': 'str'}, + "geometry": {"key": "geometry", "type": "GeoJsonGeometry"}, + "properties": {"key": "properties", "type": "object"}, + "id": {"key": "id", "type": "str"}, + "feature_type": {"key": "featureType", "type": "str"}, } def __init__( self, *, - geometry: "GeoJsonObject", - properties: Optional[object] = None, + geometry: "_models.GeoJsonGeometry", + properties: Optional[JSON] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin feature_type: Optional[str] = None, - **kwargs - ): - super(GeoJsonFeatureData, self).__init__(**kwargs) + **kwargs: Any + ) -> None: + """ + :keyword geometry: A valid ``GeoJSON`` geometry object. The type must be one of the seven valid + GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon + and GeometryCollection. Please refer to `RFC 7946 + `__ for details. Required. + :paramtype geometry: ~azure.maps.route.models.GeoJsonGeometry + :keyword properties: Properties can contain any additional metadata about the ``Feature``. + Value can be any JSON object or a JSON null value. + :paramtype properties: JSON + :keyword id: Identifier for the feature. + :paramtype id: str + :keyword feature_type: The type of the feature. The value depends on the data model the current + feature is part of. Some data models may have an empty value. + :paramtype feature_type: str + """ + super().__init__(**kwargs) self.geometry = geometry self.properties = properties + self.id = id self.feature_type = feature_type + +class GeoJsonObject(_serialization.Model): + """A valid ``GeoJSON`` object. Please refer to `RFC 7946 + `__ for details. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + GeoJsonFeature, GeoJsonFeatureCollection, GeoJsonGeometry + + All required parameters must be populated in order to send to server. + + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType + """ + + _validation = { + "type": {"required": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + } + + _subtype_map = { + "type": { + "Feature": "GeoJsonFeature", + "FeatureCollection": "GeoJsonFeatureCollection", + "GeoJsonGeometry": "GeoJsonGeometry", + } + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type: Optional[str] = None + + class GeoJsonFeature(GeoJsonObject, GeoJsonFeatureData): - """A valid ``GeoJSON Feature`` object type. - Please refer to `RFC 7946 `__ for details. + """A valid ``GeoJSON Feature`` object type. Please refer to `RFC 7946 + `__ for details. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :param geometry: Required. A valid ``GeoJSON`` object. Please refer to `RFC 7946 - `__ for details. - :type geometry: ~azure.maps.route.models.GeoJsonObject - :param properties: Properties can contain any additional metadata about the ``Feature``. Value + :ivar geometry: A valid ``GeoJSON`` geometry object. The type must be one of the seven valid + GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon + and GeometryCollection. Please refer to `RFC 7946 + `__ for details. Required. + :vartype geometry: ~azure.maps.route.models.GeoJsonGeometry + :ivar properties: Properties can contain any additional metadata about the ``Feature``. Value can be any JSON object or a JSON null value. - :type properties: object - :keyword feature_type: The type of the feature. The value depends on the data model the current + :vartype properties: JSON + :ivar id: Identifier for the feature. + :vartype id: str + :ivar feature_type: The type of the feature. The value depends on the data model the current feature is part of. Some data models may have an empty value. - :paramtype feature_type: str - :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON - object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, - GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values - include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", - "GeometryCollection", "Feature", "FeatureCollection". - :type type: str or GeoJsonObjectType + :vartype feature_type: str + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType """ _validation = { - 'geometry': {'required': True}, - 'type': {'required': True}, + "geometry": {"required": True}, + "type": {"required": True}, } _attribute_map = { - 'geometry': {'key': 'geometry', 'type': 'GeoJsonObject'}, - 'properties': {'key': 'properties', 'type': 'object'}, - 'feature_type': {'key': 'featureType', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "geometry": {"key": "geometry", "type": "GeoJsonGeometry"}, + "properties": {"key": "properties", "type": "object"}, + "id": {"key": "id", "type": "str"}, + "feature_type": {"key": "featureType", "type": "str"}, + "type": {"key": "type", "type": "str"}, } def __init__( self, *, - geometry: "GeoJsonObject", - properties: Optional[object] = None, + geometry: "_models.GeoJsonGeometry", + properties: Optional[JSON] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin feature_type: Optional[str] = None, - **kwargs - ): - super(GeoJsonFeature, self).__init__( - geometry=geometry, properties=properties, feature_type=feature_type, **kwargs - ) + **kwargs: Any + ) -> None: + """ + :keyword geometry: A valid ``GeoJSON`` geometry object. The type must be one of the seven valid + GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon + and GeometryCollection. Please refer to `RFC 7946 + `__ for details. Required. + :paramtype geometry: ~azure.maps.route.models.GeoJsonGeometry + :keyword properties: Properties can contain any additional metadata about the ``Feature``. + Value can be any JSON object or a JSON null value. + :paramtype properties: JSON + :keyword id: Identifier for the feature. + :paramtype id: str + :keyword feature_type: The type of the feature. The value depends on the data model the current + feature is part of. Some data models may have an empty value. + :paramtype feature_type: str + """ + super().__init__(geometry=geometry, properties=properties, id=id, feature_type=feature_type, **kwargs) self.geometry = geometry self.properties = properties + self.id = id self.feature_type = feature_type - self.type = 'Feature' # type: str + self.type: str = "Feature" # type: ignore -class GeoJsonFeatureCollectionData(msrest.serialization.Model): +class GeoJsonFeatureCollectionData(_serialization.Model): """GeoJsonFeatureCollectionData. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :param features: Required. Contains a list of valid ``GeoJSON Feature`` objects. - :type features: list[~azure.maps.route.models.GeoJsonFeature] + :ivar features: Contains a list of valid ``GeoJSON Feature`` objects. Required. + :vartype features: list[~azure.maps.route.models.GeoJsonFeature] """ _validation = { - 'features': {'required': True}, + "features": {"required": True}, } _attribute_map = { - 'features': {'key': 'features', 'type': '[GeoJsonFeature]'}, + "features": {"key": "features", "type": "[GeoJsonFeature]"}, } - def __init__( - self, - *, - features: List["GeoJsonFeature"], - **kwargs - ): - super(GeoJsonFeatureCollectionData, self).__init__(**kwargs) + def __init__(self, *, features: List["_models.GeoJsonFeature"], **kwargs: Any) -> None: + """ + :keyword features: Contains a list of valid ``GeoJSON Feature`` objects. Required. + :paramtype features: list[~azure.maps.route.models.GeoJsonFeature] + """ + super().__init__(**kwargs) self.features = features class GeoJsonFeatureCollection(GeoJsonObject, GeoJsonFeatureCollectionData): - """A valid ``GeoJSON FeatureCollection`` object type. - Please refer to `RFC 7946 `__ for details. - - All required parameters must be populated in order to send to Azure. - - :param features: Required. Contains a list of valid ``GeoJSON Feature`` objects. - :type features: list[~azure.maps.route.models.GeoJsonFeature] - :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON - object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, - GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values - include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", - "GeometryCollection", "Feature", "FeatureCollection". - :type type: str or GeoJsonObjectType + """A valid ``GeoJSON FeatureCollection`` object type. Please refer to `RFC 7946 + `__ for details. + + All required parameters must be populated in order to send to server. + + :ivar features: Contains a list of valid ``GeoJSON Feature`` objects. Required. + :vartype features: list[~azure.maps.route.models.GeoJsonFeature] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType """ _validation = { - 'features': {'required': True}, - 'type': {'required': True}, + "features": {"required": True}, + "type": {"required": True}, } _attribute_map = { - 'features': {'key': 'features', 'type': '[GeoJsonFeature]'}, - 'type': {'key': 'type', 'type': 'str'}, + "features": {"key": "features", "type": "[GeoJsonFeature]"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - *, - features: List["GeoJsonFeature"], - **kwargs - ): - super(GeoJsonFeatureCollection, self).__init__(features=features, **kwargs) + def __init__(self, *, features: List["_models.GeoJsonFeature"], **kwargs: Any) -> None: + """ + :keyword features: Contains a list of valid ``GeoJSON Feature`` objects. Required. + :paramtype features: list[~azure.maps.route.models.GeoJsonFeature] + """ + super().__init__(features=features, **kwargs) self.features = features - self.type = 'FeatureCollection' # type: str + self.type: str = "FeatureCollection" # type: ignore class GeoJsonGeometry(GeoJsonObject): - """A valid ``GeoJSON`` geometry object. - The type must be one of the seven valid GeoJSON geometry types - - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon and GeometryCollection. - Please refer to `RFC 7946 `__ for details. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON - object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, - GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values - include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", - "GeometryCollection", "Feature", "FeatureCollection". - :type type: str or GeoJsonObjectType + """A valid ``GeoJSON`` geometry object. The type must be one of the seven valid GeoJSON geometry + types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon and + GeometryCollection. Please refer to `RFC 7946 + `__ for details. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + GeoJsonGeometryCollection, GeoJsonLineString, GeoJsonMultiLineString, GeoJsonMultiPoint, + GeoJsonMultiPolygon, GeoJsonPoint, GeoJsonPolygon + + All required parameters must be populated in order to send to server. + + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType """ _validation = { - 'type': {'required': True}, + "type": {"required": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(GeoJsonGeometry, self).__init__(**kwargs) - self.type = 'GeoJsonGeometry' # type: str + _subtype_map = { + "type": { + "GeometryCollection": "GeoJsonGeometryCollection", + "LineString": "GeoJsonLineString", + "MultiLineString": "GeoJsonMultiLineString", + "MultiPoint": "GeoJsonMultiPoint", + "MultiPolygon": "GeoJsonMultiPolygon", + "Point": "GeoJsonPoint", + "Polygon": "GeoJsonPolygon", + } + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type: str = "GeoJsonGeometry" # type: ignore -class GeoJsonGeometryCollectionData(msrest.serialization.Model): +class GeoJsonGeometryCollectionData(_serialization.Model): """GeoJsonGeometryCollectionData. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :param geometries: Required. Contains a list of valid ``GeoJSON`` geometry objects. **Note** - that coordinates in GeoJSON are in x, y order (longitude, latitude). - :type geometries: list[~azure.maps.route.models.GeoJsonObject] + :ivar geometries: Contains a list of valid ``GeoJSON`` geometry objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :vartype geometries: list[~azure.maps.route.models.GeoJsonGeometry] """ _validation = { - 'geometries': {'required': True}, + "geometries": {"required": True}, } _attribute_map = { - 'geometries': {'key': 'geometries', 'type': '[GeoJsonObject]'}, + "geometries": {"key": "geometries", "type": "[GeoJsonGeometry]"}, } - def __init__( - self, - *, - geometries: List["GeoJsonObject"], - **kwargs - ): - super(GeoJsonGeometryCollectionData, self).__init__(**kwargs) + def __init__(self, *, geometries: List["_models.GeoJsonGeometry"], **kwargs: Any) -> None: + """ + :keyword geometries: Contains a list of valid ``GeoJSON`` geometry objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :paramtype geometries: list[~azure.maps.route.models.GeoJsonGeometry] + """ + super().__init__(**kwargs) self.geometries = geometries -class GeoJsonGeometryCollection(GeoJsonObject, GeoJsonGeometryCollectionData): - """A valid ``GeoJSON GeometryCollection`` object type. - Please refer to `RFC 7946 `__ for details. +class GeoJsonGeometryCollection(GeoJsonGeometry, GeoJsonGeometryCollectionData): + """A valid ``GeoJSON GeometryCollection`` object type. Please refer to `RFC 7946 + `__ for details. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :param geometries: Required. Contains a list of valid ``GeoJSON`` geometry objects. **Note** - that coordinates in GeoJSON are in x, y order (longitude, latitude). - :type geometries: list[~azure.maps.route.models.GeoJsonObject] - :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON - object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, - GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values - include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", - "GeometryCollection", "Feature", "FeatureCollection". - :type type: str or GeoJsonObjectType + :ivar geometries: Contains a list of valid ``GeoJSON`` geometry objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :vartype geometries: list[~azure.maps.route.models.GeoJsonGeometry] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType """ _validation = { - 'geometries': {'required': True}, - 'type': {'required': True}, + "geometries": {"required": True}, + "type": {"required": True}, } _attribute_map = { - 'geometries': {'key': 'geometries', 'type': '[GeoJsonObject]'}, - 'type': {'key': 'type', 'type': 'str'}, + "geometries": {"key": "geometries", "type": "[GeoJsonGeometry]"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - *, - geometries: List["GeoJsonObject"], - **kwargs - ): - super(GeoJsonGeometryCollection, self).__init__(geometries=geometries, **kwargs) + def __init__(self, *, geometries: List["_models.GeoJsonGeometry"], **kwargs: Any) -> None: + """ + :keyword geometries: Contains a list of valid ``GeoJSON`` geometry objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :paramtype geometries: list[~azure.maps.route.models.GeoJsonGeometry] + """ + super().__init__(geometries=geometries, **kwargs) self.geometries = geometries - self.type = 'GeometryCollection' # type: str + self.type: str = "GeometryCollection" -class GeoJsonLineStringData(msrest.serialization.Model): +class GeoJsonLineStringData(_serialization.Model): """GeoJsonLineStringData. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :param coordinates: Required. Coordinates for the ``GeoJson LineString`` geometry. - :type coordinates: list[LatLon] + :ivar coordinates: Coordinates for the ``GeoJson LineString`` geometry. Required. + :vartype coordinates: list[list[float]] """ _validation = { - 'coordinates': {'required': True}, + "coordinates": {"required": True}, } _attribute_map = { - 'coordinates': {'key': 'coordinates', 'type': '[LatLon]'}, + "coordinates": {"key": "coordinates", "type": "[[float]]"}, } - def __init__( - self, - *, - coordinates: List[LatLon], - **kwargs - ): - super(GeoJsonLineStringData, self).__init__(**kwargs) + def __init__(self, *, coordinates: List[List[float]], **kwargs: Any) -> None: + """ + :keyword coordinates: Coordinates for the ``GeoJson LineString`` geometry. Required. + :paramtype coordinates: list[list[float]] + """ + super().__init__(**kwargs) self.coordinates = coordinates -class GeoJsonLineString(GeoJsonObject, GeoJsonLineStringData): - """A valid ``GeoJSON LineString`` geometry type. - Please refer to `RFC 7946 `__ for details. - All required parameters must be populated in order to send to Azure. +class GeoJsonLineString(GeoJsonGeometry, GeoJsonLineStringData): + """A valid ``GeoJSON LineString`` geometry type. Please refer to `RFC 7946 + `__ for details. - :param coordinates: Required. Coordinates for the ``GeoJson LineString`` geometry. - :type coordinates: list[LatLon] - :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON - object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, - GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values - include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", - "GeometryCollection", "Feature", "FeatureCollection". - :type type: str or GeoJsonObjectType + All required parameters must be populated in order to send to server. + + :ivar coordinates: Coordinates for the ``GeoJson LineString`` geometry. Required. + :vartype coordinates: list[list[float]] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType """ _validation = { - 'coordinates': {'required': True}, - 'type': {'required': True}, + "coordinates": {"required": True}, + "type": {"required": True}, } _attribute_map = { - 'coordinates': {'key': 'coordinates', 'type': '[LatLon]'}, - 'type': {'key': 'type', 'type': 'str'}, + "coordinates": {"key": "coordinates", "type": "[[float]]"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - *, - coordinates: List[LatLon], - **kwargs - ): - super(GeoJsonLineString, self).__init__(coordinates=coordinates, **kwargs) + def __init__(self, *, coordinates: List[List[float]], **kwargs: Any) -> None: + """ + :keyword coordinates: Coordinates for the ``GeoJson LineString`` geometry. Required. + :paramtype coordinates: list[list[float]] + """ + super().__init__(coordinates=coordinates, **kwargs) self.coordinates = coordinates - self.type = 'LineString' # type: str + self.type: str = "LineString" -class GeoJsonMultiLineStringData(object): +class GeoJsonMultiLineStringData(_serialization.Model): """GeoJsonMultiLineStringData. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :param coordinates: Required. Coordinates for the ``GeoJson MultiLineString`` geometry. - :type coordinates: list[list[list[LatLon]]] + :ivar coordinates: Coordinates for the ``GeoJson MultiLineString`` geometry. Required. + :vartype coordinates: list[list[list[float]]] """ - def __init__( - self, - **kwargs - ): - super(GeoJsonMultiLineStringData, self).__init__(**kwargs) - self.coordinates = kwargs['coordinates'] + _validation = { + "coordinates": {"required": True}, + } -class GeoJsonMultiPointData(object): - """Data contained by a ``GeoJson MultiPoint``. + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[[[float]]]"}, + } + + def __init__(self, *, coordinates: List[List[List[float]]], **kwargs: Any) -> None: + """ + :keyword coordinates: Coordinates for the ``GeoJson MultiLineString`` geometry. Required. + :paramtype coordinates: list[list[list[float]]] + """ + super().__init__(**kwargs) + self.coordinates = coordinates - All required parameters must be populated in order to send to Azure. - :param coordinates: Required. Coordinates for the ``GeoJson MultiPoint`` geometry. - :type coordinates: list[list[LatLon]] +class GeoJsonMultiLineString(GeoJsonGeometry, GeoJsonMultiLineStringData): + """A valid ``GeoJSON MultiLineString`` geometry type. Please refer to `RFC 7946 + `__ for details. + + All required parameters must be populated in order to send to server. + + :ivar coordinates: Coordinates for the ``GeoJson MultiLineString`` geometry. Required. + :vartype coordinates: list[list[list[float]]] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType """ - def __init__( - self, - **kwargs - ): - super(GeoJsonMultiPointData, self).__init__(**kwargs) - self.coordinates = kwargs['coordinates'] + _validation = { + "coordinates": {"required": True}, + "type": {"required": True}, + } -class GeoJsonMultiPolygonData(object): - """GeoJsonMultiPolygonData. + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[[[float]]]"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, coordinates: List[List[List[float]]], **kwargs: Any) -> None: + """ + :keyword coordinates: Coordinates for the ``GeoJson MultiLineString`` geometry. Required. + :paramtype coordinates: list[list[list[float]]] + """ + super().__init__(coordinates=coordinates, **kwargs) + self.coordinates = coordinates + self.type: str = "MultiLineString" - All required parameters must be populated in order to send to Azure. - :param coordinates: Required. Contains a list of valid ``GeoJSON Polygon`` objects. **Note** - that coordinates in GeoJSON are in x, y order (longitude, latitude). - :type coordinates: list[list[list[list[LatLon]]]] - """ +class GeoJsonMultiPointData(_serialization.Model): + """Data contained by a ``GeoJson MultiPoint``. - def __init__( - self, - **kwargs - ): - super(GeoJsonMultiPolygonData, self).__init__(**kwargs) - self.coordinates = kwargs['coordinates'] - -class GeoJsonMultiLineString(GeoJsonObject, GeoJsonMultiLineStringData): - """A valid ``GeoJSON MultiLineString`` geometry type. - Please refer to `RFC 7946 `__ for details. - - All required parameters must be populated in order to send to Azure. - - :param coordinates: Required. Coordinates for the ``GeoJson MultiLineString`` geometry. - :type coordinates: list[list[LatLon]] - :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON - object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, - GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values - include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", - "GeometryCollection", "Feature", "FeatureCollection". - :type type: str or GeoJsonObjectType + All required parameters must be populated in order to send to server. + + :ivar coordinates: Coordinates for the ``GeoJson MultiPoint`` geometry. Required. + :vartype coordinates: list[list[float]] """ - def __init__( - self, - *, - coordinates: List[List[LatLon]], - **kwargs - ): - super(GeoJsonMultiLineString, self).__init__(coordinates=coordinates, **kwargs) + _validation = { + "coordinates": {"required": True}, + } + + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[[float]]"}, + } + + def __init__(self, *, coordinates: List[List[float]], **kwargs: Any) -> None: + """ + :keyword coordinates: Coordinates for the ``GeoJson MultiPoint`` geometry. Required. + :paramtype coordinates: list[list[float]] + """ + super().__init__(**kwargs) self.coordinates = coordinates - self.type = 'MultiLineString' # type: str - -class GeoJsonMultiPoint(GeoJsonObject, GeoJsonMultiPointData): - """A valid ``GeoJSON MultiPoint`` geometry type. - Please refer to `RFC 7946 `__ for details. - - All required parameters must be populated in order to send to Azure. - - :param coordinates: Required. Coordinates for the ``GeoJson MultiPoint`` geometry. - :type coordinates: list[LatLon] - :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON - object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, - GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values - include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", - "GeometryCollection", "Feature", "FeatureCollection". - :type type: str or GeoJsonObjectType + + +class GeoJsonMultiPoint(GeoJsonGeometry, GeoJsonMultiPointData): + """A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 + `__ for details. + + All required parameters must be populated in order to send to server. + + :ivar coordinates: Coordinates for the ``GeoJson MultiPoint`` geometry. Required. + :vartype coordinates: list[list[float]] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType """ - def __init__( - self, - *, - coordinates: List[LatLon], - **kwargs - ): - super(GeoJsonMultiPoint, self).__init__(coordinates=coordinates, **kwargs) + _validation = { + "coordinates": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[[float]]"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, coordinates: List[List[float]], **kwargs: Any) -> None: + """ + :keyword coordinates: Coordinates for the ``GeoJson MultiPoint`` geometry. Required. + :paramtype coordinates: list[list[float]] + """ + super().__init__(coordinates=coordinates, **kwargs) self.coordinates = coordinates - self.type = 'MultiPoint' # type: str - -class GeoJsonMultiPolygon(GeoJsonObject, GeoJsonMultiPolygonData): - """A valid ``GeoJSON MultiPolygon`` object type. - Please refer to `RFC 7946 `__ for details. - - All required parameters must be populated in order to send to Azure. - - :param coordinates: Required. Contains a list of valid ``GeoJSON Polygon`` objects. **Note** - that coordinates in GeoJSON are in x, y order (longitude, latitude). - :type coordinates: list[list[list[LatLon]]] - :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON - object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, - GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values - include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", - "GeometryCollection", "Feature", "FeatureCollection". - :type type: str or GeoJsonObjectType + self.type: str = "MultiPoint" + + +class GeoJsonMultiPolygonData(_serialization.Model): + """GeoJsonMultiPolygonData. + + All required parameters must be populated in order to send to server. + + :ivar coordinates: Contains a list of valid ``GeoJSON Polygon`` objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :vartype coordinates: list[list[list[list[float]]]] """ _validation = { - 'coordinates': {'required': True}, - 'type': {'required': True}, + "coordinates": {"required": True}, } _attribute_map = { - 'coordinates': {'key': 'coordinates', 'type': '[[[LatLon]]]'}, - 'type': {'key': 'type', 'type': 'str'}, + "coordinates": {"key": "coordinates", "type": "[[[[float]]]]"}, } - def __init__( - self, - *, - coordinates: List[List[List[LatLon]]], - **kwargs - ): - super(GeoJsonMultiPolygon, self).__init__(coordinates=coordinates, **kwargs) + def __init__(self, *, coordinates: List[List[List[List[float]]]], **kwargs: Any) -> None: + """ + :keyword coordinates: Contains a list of valid ``GeoJSON Polygon`` objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :paramtype coordinates: list[list[list[list[float]]]] + """ + super().__init__(**kwargs) self.coordinates = coordinates - self.type = 'MultiPolygon' # type: str - self.type = 'MultiPolygon' # type: str -class GeoJsonPointData(msrest.serialization.Model): - """Data contained by a ``GeoJson Point``. +class GeoJsonMultiPolygon(GeoJsonGeometry, GeoJsonMultiPolygonData): + """A valid ``GeoJSON MultiPolygon`` object type. Please refer to `RFC 7946 + `__ for details. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :param coordinates: Required. A ``Position`` is an array of numbers with two or more elements. - The first two elements are *longitude* and *latitude*, precisely in that order. - *Altitude/Elevation* is an optional third element. Please refer to `RFC 7946 - `__ for details. - :type coordinates: LatLon + :ivar coordinates: Contains a list of valid ``GeoJSON Polygon`` objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :vartype coordinates: list[list[list[list[float]]]] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType """ _validation = { - 'coordinates': {'required': True}, + "coordinates": {"required": True}, + "type": {"required": True}, } _attribute_map = { - 'coordinates': {'key': 'coordinates', 'type': 'LatLon'}, + "coordinates": {"key": "coordinates", "type": "[[[[float]]]]"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - *, - coordinates: LatLon, - **kwargs - ): - super(GeoJsonPointData, self).__init__(**kwargs) + def __init__(self, *, coordinates: List[List[List[List[float]]]], **kwargs: Any) -> None: + """ + :keyword coordinates: Contains a list of valid ``GeoJSON Polygon`` objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :paramtype coordinates: list[list[list[list[float]]]] + """ + super().__init__(coordinates=coordinates, **kwargs) self.coordinates = coordinates + self.type: str = "MultiPolygon" -class GeoJsonPoint(GeoJsonObject, GeoJsonPointData): - """A valid ``GeoJSON Point`` geometry type. - Please refer to `RFC 7946 `__ for details. +class GeoJsonPointData(_serialization.Model): + """Data contained by a ``GeoJson Point``. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :param coordinates: Required. A ``Position`` is an array of numbers with two or more elements. - The first two elements are *longitude* and *latitude*, precisely in that order. - *Altitude/Elevation* is an optional third element. Please refer to `RFC 7946 - `__ for details. - :type coordinates: LatLon - :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON - object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, - GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values - include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", - "GeometryCollection", "Feature", "FeatureCollection". - :type type: str or ~azure.maps.route._models.GeoJsonObjectType + :ivar coordinates: A ``Position`` is an array of numbers with two or more elements. The first + two elements are *longitude* and *latitude*\\ , precisely in that order. *Altitude/Elevation* + is an optional third element. Please refer to `RFC 7946 + `__ for details. Required. + :vartype coordinates: list[float] """ _validation = { - 'coordinates': {'required': True}, - 'type': {'required': True}, + "coordinates": {"required": True}, } _attribute_map = { - 'coordinates': {'key': 'coordinates', 'type': 'LatLon'}, - 'type': {'key': 'type', 'type': 'str'}, + "coordinates": {"key": "coordinates", "type": "[float]"}, } - def __init__( - self, - *, - coordinates: LatLon, - **kwargs - ): - super(GeoJsonPoint, self).__init__(coordinates=coordinates, **kwargs) + def __init__(self, *, coordinates: List[float], **kwargs: Any) -> None: + """ + :keyword coordinates: A ``Position`` is an array of numbers with two or more elements. The + first two elements are *longitude* and *latitude*\\ , precisely in that order. + *Altitude/Elevation* is an optional third element. Please refer to `RFC 7946 + `__ for details. Required. + :paramtype coordinates: list[float] + """ + super().__init__(**kwargs) self.coordinates = coordinates - self.type = 'Point' # type: str -class GeoJsonPolygonData(msrest.serialization.Model): - """GeoJsonPolygonData. +class GeoJsonPoint(GeoJsonGeometry, GeoJsonPointData): + """A valid ``GeoJSON Point`` geometry type. Please refer to `RFC 7946 + `__ for details. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :param coordinates: Required. Coordinates for the ``GeoJson Polygon`` geometry type. - :type coordinates: list[list[LatLon]] + :ivar coordinates: A ``Position`` is an array of numbers with two or more elements. The first + two elements are *longitude* and *latitude*\\ , precisely in that order. *Altitude/Elevation* + is an optional third element. Please refer to `RFC 7946 + `__ for details. Required. + :vartype coordinates: list[float] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType """ _validation = { - 'coordinates': {'required': True}, + "coordinates": {"required": True}, + "type": {"required": True}, } _attribute_map = { - 'coordinates': {'key': 'coordinates', 'type': '[[LatLon]]'}, + "coordinates": {"key": "coordinates", "type": "[float]"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - *, - coordinates: List[List[LatLon]], - **kwargs - ): - super(GeoJsonPolygonData, self).__init__(**kwargs) + def __init__(self, *, coordinates: List[float], **kwargs: Any) -> None: + """ + :keyword coordinates: A ``Position`` is an array of numbers with two or more elements. The + first two elements are *longitude* and *latitude*\\ , precisely in that order. + *Altitude/Elevation* is an optional third element. Please refer to `RFC 7946 + `__ for details. Required. + :paramtype coordinates: list[float] + """ + super().__init__(coordinates=coordinates, **kwargs) self.coordinates = coordinates + self.type: str = "Point" -class GeoJsonPolygon(GeoJsonObject, GeoJsonPolygonData): - """A valid ``GeoJSON Polygon`` geometry type. - Please refer to `RFC 7946 `__ for details. +class GeoJsonPolygonData(_serialization.Model): + """GeoJsonPolygonData. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :param coordinates: Required. Coordinates for the ``GeoJson Polygon`` geometry type. - :type coordinates: list[list[LatLon]] - :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON - object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, - GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values - include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", - "GeometryCollection", "Feature", "FeatureCollection". - :type type: str or GeoJsonObjectType + :ivar coordinates: Coordinates for the ``GeoJson Polygon`` geometry type. Required. + :vartype coordinates: list[list[list[float]]] """ _validation = { - 'coordinates': {'required': True}, - 'type': {'required': True}, + "coordinates": {"required": True}, } _attribute_map = { - 'coordinates': {'key': 'coordinates', 'type': '[[LatLon]]'}, - 'type': {'key': 'type', 'type': 'str'}, + "coordinates": {"key": "coordinates", "type": "[[[float]]]"}, } - def __init__( - self, - *, - coordinates: List[List[LatLon]], - **kwargs - ): - super(GeoJsonPolygon, self).__init__(coordinates=coordinates, **kwargs) + def __init__(self, *, coordinates: List[List[List[float]]], **kwargs: Any) -> None: + """ + :keyword coordinates: Coordinates for the ``GeoJson Polygon`` geometry type. Required. + :paramtype coordinates: list[list[list[float]]] + """ + super().__init__(**kwargs) self.coordinates = coordinates - self.type = 'Polygon' # type: str -class TravelMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Travel mode for the calculated route. The value will be set to ``other`` if the requested mode - of transport is not possible in this section. - """ - #: The returned routes are optimized for cars. - CAR = "car" - #: The returned routes are optimized for commercial vehicles, like for trucks. - TRUCK = "truck" - #: The returned routes are optimized for taxis. BETA functionality. - TAXI = "taxi" - #: The returned routes are optimized for buses, including the use of bus only lanes. BETA - #: functionality. - BUS = "bus" - #: The returned routes are optimized for vans. BETA functionality. - VAN = "van" - #: The returned routes are optimized for motorcycles. BETA functionality. - MOTORCYCLE = "motorcycle" - #: The returned routes are optimized for bicycles, including use of bicycle lanes. - BICYCLE = "bicycle" - #: The returned routes are optimized for pedestrians, including the use of sidewalks. - PEDESTRIAN = "pedestrian" - #: The given mode of transport is not possible in this section - OTHER = "other" - -class RouteInstruction(object): # pylint: disable=too-many-instance-attributes - """A set of attributes describing a maneuver, e.g. 'Turn right', 'Keep left', - 'Take the ferry', 'Take the motorway', 'Arrive'. +class GeoJsonPolygon(GeoJsonGeometry, GeoJsonPolygonData): + """A valid ``GeoJSON Polygon`` geometry type. Please refer to `RFC 7946 + `__ for details. - 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 route_offset_in_meters: Distance from the start of the route to the point of the - instruction. - :vartype route_offset_in_meters: int - :ivar travel_time_in_seconds: Estimated travel time up to the point corresponding to - routeOffsetInMeters. - :vartype travel_time_in_seconds: int - :ivar point: A location represented as a latitude and longitude. - :vartype point: LatLon - :ivar point_index: The index of the point in the list of polyline "points" corresponding to the - point of the instruction. - :vartype point_index: int - :ivar instruction_type: Type of the instruction, e.g., turn or change of road form. Known - values are: "TURN", "ROAD_CHANGE", "LOCATION_DEPARTURE", "LOCATION_ARRIVAL", "DIRECTION_INFO", - and "LOCATION_WAYPOINT". - :vartype instruction_type: str or ~azure.maps.route.models.GuidanceInstructionType - :ivar road_numbers: The road number(s) of the next significant road segment(s) after the - maneuver, or of the road(s) to be followed. Example: ["E34", "N205"]. - :vartype road_numbers: list[str] - :ivar exit_number: The number(s) of a highway exit taken by the current maneuver. If an exit - has multiple exit numbers, they will be separated by "," and possibly aggregated by "-", e.g., - "10, 13-15". - :vartype exit_number: str - :ivar street: Street name of the next significant road segment after the maneuver, or of the - street that should be followed. - :vartype street: str - :ivar signpost_text: The text on a signpost which is most relevant to the maneuver, or to the - direction that should be followed. - :vartype signpost_text: str - :ivar country_code: 3-character `ISO 3166-1 `_ - alpha-3 country code. E.g. USA. - :vartype country_code: str - :ivar state_code: A subdivision (e.g., state) of the country, represented by the second part of - an `ISO 3166-2 `_ code. This is only available for - some countries like the US, Canada, and Mexico. - :vartype state_code: str - :ivar junction_type: The type of the junction where the maneuver takes place. For larger - roundabouts, two separate instructions are generated for entering and leaving the roundabout. - Known values are: "REGULAR", "ROUNDABOUT", and "BIFURCATION". - :vartype junction_type: str or ~azure.maps.route.models.JunctionType - :ivar turn_angle_in_degrees: Indicates the direction of an instruction. If junctionType - indicates a turn instruction: + :ivar coordinates: Coordinates for the ``GeoJson Polygon`` geometry type. Required. + :vartype coordinates: list[list[list[float]]] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType + """ + _validation = { + "coordinates": {"required": True}, + "type": {"required": True}, + } - * 180 = U-turn - * [-179, -1] = Left turn - * 0 = Straight on (a '0 degree' turn) - * [1, 179] = Right turn + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[[[float]]]"}, + "type": {"key": "type", "type": "str"}, + } - If junctionType indicates a bifurcation instruction: + def __init__(self, *, coordinates: List[List[List[float]]], **kwargs: Any) -> None: + """ + :keyword coordinates: Coordinates for the ``GeoJson Polygon`` geometry type. Required. + :paramtype coordinates: list[list[list[float]]] + """ + super().__init__(coordinates=coordinates, **kwargs) + self.coordinates = coordinates + self.type: str = "Polygon" - * <0 - keep left - * >0 - keep right. - :vartype turn_angle_in_degrees: int - :ivar roundabout_exit_number: This indicates which exit to take at a roundabout. - :vartype roundabout_exit_number: str - :ivar possible_combine_with_next: It is possible to optionally combine the instruction with the - next one. This can be used to build messages like "Turn left and then turn right". - :vartype possible_combine_with_next: bool - :ivar driving_side: Indicates left-hand vs. right-hand side driving at the point of the - maneuver. Known values are: "LEFT" and "RIGHT". - :vartype driving_side: str or ~azure.maps.route.models.DrivingSide - :ivar maneuver: A code identifying the maneuver. Known values are: "ARRIVE", "ARRIVE_LEFT", - "ARRIVE_RIGHT", "DEPART", "STRAIGHT", "KEEP_RIGHT", "BEAR_RIGHT", "TURN_RIGHT", "SHARP_RIGHT", - "KEEP_LEFT", "BEAR_LEFT", "TURN_LEFT", "SHARP_LEFT", "MAKE_UTURN", "ENTER_MOTORWAY", - "ENTER_FREEWAY", "ENTER_HIGHWAY", "TAKE_EXIT", "MOTORWAY_EXIT_LEFT", "MOTORWAY_EXIT_RIGHT", - "TAKE_FERRY", "ROUNDABOUT_CROSS", "ROUNDABOUT_RIGHT", "ROUNDABOUT_LEFT", "ROUNDABOUT_BACK", - "TRY_MAKE_UTURN", "FOLLOW", "SWITCH_PARALLEL_ROAD", "SWITCH_MAIN_ROAD", "ENTRANCE_RAMP", - "WAYPOINT_LEFT", "WAYPOINT_RIGHT", and "WAYPOINT_REACHED". - :vartype maneuver: str or ~azure.maps.route.models.GuidanceManeuver - :ivar message: A human-readable message for the maneuver. - :vartype message: str - :ivar combined_message: A human-readable message for the maneuver combined with the message - from the next instruction. Sometimes it is possible to combine two successive instructions into - a single instruction making it easier to follow. When this is the case the - possibleCombineWithNext flag will be true. For example: +class LatLongPair(_serialization.Model): + """A location represented as a latitude and longitude. - .. code-block:: + :ivar latitude: Latitude property. + :vartype latitude: float + :ivar longitude: Longitude property. + :vartype longitude: float + """ - 10. Turn left onto Einsteinweg/A10/E22 towards Ring Amsterdam - 11. Follow Einsteinweg/A10/E22 towards Ring Amsterdam + _attribute_map = { + "latitude": {"key": "latitude", "type": "float"}, + "longitude": {"key": "longitude", "type": "float"}, + } - The possibleCombineWithNext flag on instruction 10 is true. This indicates to the clients of - coded guidance that it can be combined with instruction 11. The instructions will be combined - automatically for clients requesting human-readable guidance. The combinedMessage field - contains the combined message: + def __init__(self, *, latitude: Optional[float] = None, longitude: Optional[float] = None, **kwargs: Any) -> None: + """ + :keyword latitude: Latitude property. + :paramtype latitude: float + :keyword longitude: Longitude property. + :paramtype longitude: float + """ + super().__init__(**kwargs) + self.latitude = latitude + self.longitude = longitude - .. code-block:: - Turn left onto Einsteinweg/A10/E22 towards Ring Amsterdam - then follow Einsteinweg/A10/E22 towards Ring Amsterdam. - :vartype combined_message: str +class Route(_serialization.Model): + """Route. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar summary: Summary object. + :vartype summary: ~azure.maps.route.models.RouteSummary + :ivar legs: Legs array. + :vartype legs: list[~azure.maps.route.models.RouteLeg] + :ivar sections: Sections array. + :vartype sections: list[~azure.maps.route.models.RouteSection] + :ivar guidance: Contains guidance related elements. This field is present only when guidance + was requested and is available. + :vartype guidance: ~azure.maps.route.models.RouteGuidance """ _validation = { - "route_offset_in_meters": {"readonly": True}, - "travel_time_in_seconds": {"readonly": True}, - "point_index": {"readonly": True}, - "road_numbers": {"readonly": True}, - "exit_number": {"readonly": True}, - "street": {"readonly": True}, - "signpost_text": {"readonly": True}, - "country_code": {"readonly": True}, - "state_code": {"readonly": True}, - "junction_type": {"readonly": True}, - "turn_angle_in_degrees": {"readonly": True}, - "roundabout_exit_number": {"readonly": True}, - "possible_combine_with_next": {"readonly": True}, - "driving_side": {"readonly": True}, - "maneuver": {"readonly": True}, - "message": {"readonly": True}, - "combined_message": {"readonly": True}, + "summary": {"readonly": True}, + "legs": {"readonly": True}, + "sections": {"readonly": True}, + "guidance": {"readonly": True}, } _attribute_map = { - "route_offset_in_meters": {"key": "routeOffsetInMeters", "type": "int"}, - "travel_time_in_seconds": {"key": "travelTimeInSeconds", "type": "int"}, - "point": {"key": "point", "type": "LatLongPair"}, - "point_index": {"key": "pointIndex", "type": "int"}, - "instruction_type": {"key": "instructionType", "type": "str"}, - "road_numbers": {"key": "roadNumbers", "type": "[str]"}, - "exit_number": {"key": "exitNumber", "type": "str"}, - "street": {"key": "street", "type": "str"}, - "signpost_text": {"key": "signpostText", "type": "str"}, - "country_code": {"key": "countryCode", "type": "str"}, - "state_code": {"key": "stateCode", "type": "str"}, - "junction_type": {"key": "junctionType", "type": "str"}, - "turn_angle_in_degrees": {"key": "turnAngleInDecimalDegrees", "type": "int"}, - "roundabout_exit_number": {"key": "roundaboutExitNumber", "type": "str"}, - "possible_combine_with_next": {"key": "possibleCombineWithNext", "type": "bool"}, - "driving_side": {"key": "drivingSide", "type": "str"}, - "maneuver": {"key": "maneuver", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "combined_message": {"key": "combinedMessage", "type": "str"}, + "summary": {"key": "summary", "type": "RouteSummary"}, + "legs": {"key": "legs", "type": "[RouteLeg]"}, + "sections": {"key": "sections", "type": "[RouteSection]"}, + "guidance": {"key": "guidance", "type": "RouteGuidance"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.summary = None + self.legs = None + self.sections = None + self.guidance = None + + +class RouteDirectionParameters(_serialization.Model): + """Post body parameters for Route directions. + + :ivar supporting_points: A GeoJSON Geometry collection representing sequence of coordinates + used as input for route reconstruction and for calculating zero or more alternative routes to + this reference route. + + + * The provided sequence of supporting points is used as input for route reconstruction. + * The alternative routes are calculated between the origin and destination points specified in + the base path parameter locations. + * If both *minDeviationDistance* and *minDeviationTime* are set to zero, then these origin and + destination points are + expected to be at (or very near) the beginning and end of the reference route, respectively. + * Intermediate locations (\\ *waypoints*\\ ) are not supported when using + :code:`<_supportingPoints_>`. + * The reference route may contain traffic incidents of type _ROAD\\ *CLOSURE*\\ , which are + ignored for the calculation of the reference route's travel time and traffic delay. + Please refer to `Supporting Points + `_ # pylint: disable=line-too-long + for details. + :vartype supporting_points: ~azure.maps.route.models.GeoJsonGeometryCollection + :ivar avoid_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of + countries in which all toll roads with vignettes are to be avoided, e.g. "AUS,CHE". Toll roads + with vignettes in countries not in the list are unaffected. Note: It is an error to specify + both **avoidVignette** and **allowVignette**. + :vartype avoid_vignette: list[str] + :ivar allow_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of + countries in which toll roads with vignettes are allowed, e.g. "AUS,CHE". Specifying + **allowVignette** with some countries X is equivalent to specifying **avoidVignette** with all + countries but X. Specifying **allowVignette** with an empty list is the same as avoiding all + toll roads with vignettes. Note: It is an error to specify both **avoidVignette** and + **allowVignette**. + :vartype allow_vignette: list[str] + :ivar avoid_areas: A GeoJSON MultiPolygon representing list of areas to avoid. Only rectangle + polygons are supported. The maximum size of a rectangle is about 160x160 km. Maximum number of + avoided areas is **10**. It cannot cross the 180th meridian. It must be between -80 and +80 + degrees of latitude. + :vartype avoid_areas: ~azure.maps.route.models.GeoJsonMultiPolygon + """ + + _attribute_map = { + "supporting_points": {"key": "supportingPoints", "type": "GeoJsonGeometryCollection"}, + "avoid_vignette": {"key": "avoidVignette", "type": "[str]"}, + "allow_vignette": {"key": "allowVignette", "type": "[str]"}, + "avoid_areas": {"key": "avoidAreas", "type": "GeoJsonMultiPolygon"}, } def __init__( self, *, - point: Optional["LatLon"] = None, - instruction_type: Optional[Union[str, "GuidanceInstructionType"]] = None, - **kwargs - ): + supporting_points: Optional["_models.GeoJsonGeometryCollection"] = None, + avoid_vignette: Optional[List[str]] = None, + allow_vignette: Optional[List[str]] = None, + avoid_areas: Optional["_models.GeoJsonMultiPolygon"] = None, + **kwargs: Any + ) -> None: """ - :keyword point: A location represented as a latitude and longitude. - :paramtype point: ~azure.maps.route.models.LatLongPair - :keyword instruction_type: Type of the instruction, e.g., turn or change of road form. Known - values are: "TURN", "ROAD_CHANGE", "LOCATION_DEPARTURE", "LOCATION_ARRIVAL", "DIRECTION_INFO", - and "LOCATION_WAYPOINT". - :paramtype instruction_type: str or ~azure.maps.route.models.GuidanceInstructionType + :keyword supporting_points: A GeoJSON Geometry collection representing sequence of coordinates + used as input for route reconstruction and for calculating zero or more alternative routes to + this reference route. + + + * The provided sequence of supporting points is used as input for route reconstruction. + * The alternative routes are calculated between the origin and destination points specified in + the base path parameter locations. + * If both *minDeviationDistance* and *minDeviationTime* are set to zero, then these origin and + destination points are + expected to be at (or very near) the beginning and end of the reference route, respectively. + * Intermediate locations (\\ *waypoints*\\ ) are not supported when using + :code:`<_supportingPoints_>`. + * The reference route may contain traffic incidents of type _ROAD\\ *CLOSURE*\\ , which are + ignored for the calculation of the reference route's travel time and traffic delay. + Please refer to `Supporting Points + `_ # pylint: disable=line-too-long + for details. + :paramtype supporting_points: ~azure.maps.route.models.GeoJsonGeometryCollection + :keyword avoid_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of + countries in which all toll roads with vignettes are to be avoided, e.g. "AUS,CHE". Toll roads + with vignettes in countries not in the list are unaffected. Note: It is an error to specify + both **avoidVignette** and **allowVignette**. + :paramtype avoid_vignette: list[str] + :keyword allow_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of + countries in which toll roads with vignettes are allowed, e.g. "AUS,CHE". Specifying + **allowVignette** with some countries X is equivalent to specifying **avoidVignette** with all + countries but X. Specifying **allowVignette** with an empty list is the same as avoiding all + toll roads with vignettes. Note: It is an error to specify both **avoidVignette** and + **allowVignette**. + :paramtype allow_vignette: list[str] + :keyword avoid_areas: A GeoJSON MultiPolygon representing list of areas to avoid. Only + rectangle polygons are supported. The maximum size of a rectangle is about 160x160 km. Maximum + number of avoided areas is **10**. It cannot cross the 180th meridian. It must be between -80 + and +80 degrees of latitude. + :paramtype avoid_areas: ~azure.maps.route.models.GeoJsonMultiPolygon """ super().__init__(**kwargs) - self.route_offset_in_meters = None - self.travel_time_in_seconds = None - self.point = point - self.point_index = None - self.instruction_type = instruction_type - self.road_numbers = None - self.exit_number = None - self.street = None - self.signpost_text = None - self.country_code = None - self.state_code = None - self.junction_type = None + self.supporting_points = supporting_points + self.avoid_vignette = avoid_vignette + self.allow_vignette = allow_vignette + self.avoid_areas = avoid_areas + + +class RouteDirections(_serialization.Model): + """This object is returned from a successful Route Directions call. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar format_version: Format Version property. + :vartype format_version: str + :ivar routes: Routes array. + :vartype routes: list[~azure.maps.route.models.Route] + :ivar optimized_waypoints: Optimized sequence of waypoints. It shows the index from the user + provided waypoint sequence for the original and optimized list. For instance, a response: + + .. code-block:: + + + + + + + + means that the original sequence is [0, 1, 2] and optimized sequence is [1, 2, 0]. Since the + index starts by 0 the original is "first, second, third" while the optimized is "second, third, + first". + :vartype optimized_waypoints: list[~azure.maps.route.models.RouteOptimizedWaypoint] + :ivar report: Reports the effective settings used in the current call. + :vartype report: ~azure.maps.route.models.RouteReport + """ + + _validation = { + "format_version": {"readonly": True}, + "routes": {"readonly": True}, + "optimized_waypoints": {"readonly": True}, + } + + _attribute_map = { + "format_version": {"key": "formatVersion", "type": "str"}, + "routes": {"key": "routes", "type": "[Route]"}, + "optimized_waypoints": {"key": "optimizedWaypoints", "type": "[RouteOptimizedWaypoint]"}, + "report": {"key": "report", "type": "RouteReport"}, + } + + def __init__(self, *, report: Optional["_models.RouteReport"] = None, **kwargs: Any) -> None: + """ + :keyword report: Reports the effective settings used in the current call. + :paramtype report: ~azure.maps.route.models.RouteReport + """ + super().__init__(**kwargs) + self.format_version = None + self.routes = None + self.optimized_waypoints = None + self.report = report + + +class RouteDirectionsBatchItem(BatchResultItem): + """An item returned from Route Directions Batch service call. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar status_code: HTTP request status code. + :vartype status_code: int + :ivar response: The result of the query. RouteDirections if the query completed successfully, + ErrorResponse otherwise. + :vartype response: ~azure.maps.route.models.RouteDirectionsBatchItemResponse + """ + + _validation = { + "status_code": {"readonly": True}, + "response": {"readonly": True}, + } + + _attribute_map = { + "status_code": {"key": "statusCode", "type": "int"}, + "response": {"key": "response", "type": "RouteDirectionsBatchItemResponse"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.response = None + + +class RouteDirectionsBatchItemResponse(RouteDirections, ErrorResponse): + """The result of the query. RouteDirections if the query completed successfully, ErrorResponse + otherwise. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar error: The error object. + :vartype error: ~azure.maps.route.models.ErrorDetail + :ivar format_version: Format Version property. + :vartype format_version: str + :ivar routes: Routes array. + :vartype routes: list[~azure.maps.route.models.Route] + :ivar optimized_waypoints: Optimized sequence of waypoints. It shows the index from the user + provided waypoint sequence for the original and optimized list. For instance, a response: + + .. code-block:: + + + + + + + + means that the original sequence is [0, 1, 2] and optimized sequence is [1, 2, 0]. Since the + index starts by 0 the original is "first, second, third" while the optimized is "second, third, + first". + :vartype optimized_waypoints: list[~azure.maps.route.models.RouteOptimizedWaypoint] + :ivar report: Reports the effective settings used in the current call. + :vartype report: ~azure.maps.route.models.RouteReport + """ + + _validation = { + "format_version": {"readonly": True}, + "routes": {"readonly": True}, + "optimized_waypoints": {"readonly": True}, + } + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + "format_version": {"key": "formatVersion", "type": "str"}, + "routes": {"key": "routes", "type": "[Route]"}, + "optimized_waypoints": {"key": "optimizedWaypoints", "type": "[RouteOptimizedWaypoint]"}, + "report": {"key": "report", "type": "RouteReport"}, + } + + def __init__( + self, + *, + error: Optional["_models.ErrorDetail"] = None, + report: Optional["_models.RouteReport"] = None, + **kwargs: Any + ) -> None: + """ + :keyword error: The error object. + :paramtype error: ~azure.maps.route.models.ErrorDetail + :keyword report: Reports the effective settings used in the current call. + :paramtype report: ~azure.maps.route.models.RouteReport + """ + super().__init__(report=report, error=error, **kwargs) + self.error = error + self.format_version = None + self.routes = None + self.optimized_waypoints = None + self.report = report + + +class RouteDirectionsBatchResult(BatchResult): + """This object is returned from a successful Route Directions Batch service call. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar batch_summary: Summary of the results for the batch request. + :vartype batch_summary: ~azure.maps.route.models.BatchResultSummary + :ivar batch_items: Array containing the batch results. + :vartype batch_items: list[~azure.maps.route.models.RouteDirectionsBatchItem] + """ + + _validation = { + "batch_summary": {"readonly": True}, + "batch_items": {"readonly": True}, + } + + _attribute_map = { + "batch_summary": {"key": "summary", "type": "BatchResultSummary"}, + "batch_items": {"key": "batchItems", "type": "[RouteDirectionsBatchItem]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.batch_items = None + + +class RouteGuidance(_serialization.Model): + """Contains guidance related elements. This field is present only when guidance was requested and + is available. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar instructions: A list of instructions describing maneuvers. + :vartype instructions: list[~azure.maps.route.models.RouteInstruction] + :ivar instruction_groups: Groups a sequence of instruction elements which are related to each + other. + :vartype instruction_groups: list[~azure.maps.route.models.RouteInstructionGroup] + """ + + _validation = { + "instructions": {"readonly": True}, + "instruction_groups": {"readonly": True}, + } + + _attribute_map = { + "instructions": {"key": "instructions", "type": "[RouteInstruction]"}, + "instruction_groups": {"key": "instructionGroups", "type": "[RouteInstructionGroup]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.instructions = None + self.instruction_groups = None + + +class RouteInstruction(_serialization.Model): # pylint: disable=too-many-instance-attributes + """A set of attributes describing a maneuver, e.g. 'Turn right', 'Keep left', 'Take the ferry', + 'Take the motorway', 'Arrive'. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar route_offset_in_meters: Distance from the start of the route to the point of the + instruction. + :vartype route_offset_in_meters: int + :ivar travel_time_in_seconds: Estimated travel time up to the point corresponding to + routeOffsetInMeters. + :vartype travel_time_in_seconds: int + :ivar point: A location represented as a latitude and longitude. + :vartype point: ~azure.maps.route.models.LatLongPair + :ivar point_index: The index of the point in the list of polyline "points" corresponding to the + point of the instruction. + :vartype point_index: int + :ivar instruction_type: Type of the instruction, e.g., turn or change of road form. Known + values are: "TURN", "ROAD_CHANGE", "LOCATION_DEPARTURE", "LOCATION_ARRIVAL", "DIRECTION_INFO", + and "LOCATION_WAYPOINT". + :vartype instruction_type: str or ~azure.maps.route.models.GuidanceInstructionType + :ivar road_numbers: The road number(s) of the next significant road segment(s) after the + maneuver, or of the road(s) to be followed. Example: ["E34", "N205"]. + :vartype road_numbers: list[str] + :ivar exit_number: The number(s) of a highway exit taken by the current maneuver. If an exit + has multiple exit numbers, they will be separated by "," and possibly aggregated by "-", e.g., + "10, 13-15". + :vartype exit_number: str + :ivar street: Street name of the next significant road segment after the maneuver, or of the + street that should be followed. + :vartype street: str + :ivar signpost_text: The text on a signpost which is most relevant to the maneuver, or to the + direction that should be followed. + :vartype signpost_text: str + :ivar country_code: 3-character `ISO 3166-1 `_ + alpha-3 country code. E.g. USA. + :vartype country_code: str + :ivar state_code: A subdivision (e.g., state) of the country, represented by the second part of + an `ISO 3166-2 `_ code. This is only available for + some countries like the US, Canada, and Mexico. + :vartype state_code: str + :ivar junction_type: The type of the junction where the maneuver takes place. For larger + roundabouts, two separate instructions are generated for entering and leaving the roundabout. + Known values are: "REGULAR", "ROUNDABOUT", and "BIFURCATION". + :vartype junction_type: str or ~azure.maps.route.models.JunctionType + :ivar turn_angle_in_degrees: Indicates the direction of an instruction. If junctionType + indicates a turn instruction: + + + * 180 = U-turn + * [-179, -1] = Left turn + * 0 = Straight on (a '0 degree' turn) + * [1, 179] = Right turn + + If junctionType indicates a bifurcation instruction: + + + * <0 - keep left + * >0 - keep right. + :vartype turn_angle_in_degrees: int + :ivar roundabout_exit_number: This indicates which exit to take at a roundabout. + :vartype roundabout_exit_number: str + :ivar possible_combine_with_next: It is possible to optionally combine the instruction with the + next one. This can be used to build messages like "Turn left and then turn right". + :vartype possible_combine_with_next: bool + :ivar driving_side: Indicates left-hand vs. right-hand side driving at the point of the + maneuver. Known values are: "LEFT" and "RIGHT". + :vartype driving_side: str or ~azure.maps.route.models.DrivingSide + :ivar maneuver: A code identifying the maneuver. Known values are: "ARRIVE", "ARRIVE_LEFT", + "ARRIVE_RIGHT", "DEPART", "STRAIGHT", "KEEP_RIGHT", "BEAR_RIGHT", "TURN_RIGHT", "SHARP_RIGHT", + "KEEP_LEFT", "BEAR_LEFT", "TURN_LEFT", "SHARP_LEFT", "MAKE_UTURN", "ENTER_MOTORWAY", + "ENTER_FREEWAY", "ENTER_HIGHWAY", "TAKE_EXIT", "MOTORWAY_EXIT_LEFT", "MOTORWAY_EXIT_RIGHT", + "TAKE_FERRY", "ROUNDABOUT_CROSS", "ROUNDABOUT_RIGHT", "ROUNDABOUT_LEFT", "ROUNDABOUT_BACK", + "TRY_MAKE_UTURN", "FOLLOW", "SWITCH_PARALLEL_ROAD", "SWITCH_MAIN_ROAD", "ENTRANCE_RAMP", + "WAYPOINT_LEFT", "WAYPOINT_RIGHT", and "WAYPOINT_REACHED". + :vartype maneuver: str or ~azure.maps.route.models.GuidanceManeuver + :ivar message: A human-readable message for the maneuver. + :vartype message: str + :ivar combined_message: A human-readable message for the maneuver combined with the message + from the next instruction. Sometimes it is possible to combine two successive instructions into + a single instruction making it easier to follow. When this is the case the + possibleCombineWithNext flag will be true. For example: + + .. code-block:: + + 10. Turn left onto Einsteinweg/A10/E22 towards Ring Amsterdam + 11. Follow Einsteinweg/A10/E22 towards Ring Amsterdam + + The possibleCombineWithNext flag on instruction 10 is true. This indicates to the clients of + coded guidance that it can be combined with instruction 11. The instructions will be combined + automatically for clients requesting human-readable guidance. The combinedMessage field + contains the combined message: + + .. code-block:: + + Turn left onto Einsteinweg/A10/E22 towards Ring Amsterdam + then follow Einsteinweg/A10/E22 towards Ring Amsterdam. + :vartype combined_message: str + """ + + _validation = { + "route_offset_in_meters": {"readonly": True}, + "travel_time_in_seconds": {"readonly": True}, + "point_index": {"readonly": True}, + "road_numbers": {"readonly": True}, + "exit_number": {"readonly": True}, + "street": {"readonly": True}, + "signpost_text": {"readonly": True}, + "country_code": {"readonly": True}, + "state_code": {"readonly": True}, + "junction_type": {"readonly": True}, + "turn_angle_in_degrees": {"readonly": True}, + "roundabout_exit_number": {"readonly": True}, + "possible_combine_with_next": {"readonly": True}, + "driving_side": {"readonly": True}, + "maneuver": {"readonly": True}, + "message": {"readonly": True}, + "combined_message": {"readonly": True}, + } + + _attribute_map = { + "route_offset_in_meters": {"key": "routeOffsetInMeters", "type": "int"}, + "travel_time_in_seconds": {"key": "travelTimeInSeconds", "type": "int"}, + "point": {"key": "point", "type": "LatLongPair"}, + "point_index": {"key": "pointIndex", "type": "int"}, + "instruction_type": {"key": "instructionType", "type": "str"}, + "road_numbers": {"key": "roadNumbers", "type": "[str]"}, + "exit_number": {"key": "exitNumber", "type": "str"}, + "street": {"key": "street", "type": "str"}, + "signpost_text": {"key": "signpostText", "type": "str"}, + "country_code": {"key": "countryCode", "type": "str"}, + "state_code": {"key": "stateCode", "type": "str"}, + "junction_type": {"key": "junctionType", "type": "str"}, + "turn_angle_in_degrees": {"key": "turnAngleInDecimalDegrees", "type": "int"}, + "roundabout_exit_number": {"key": "roundaboutExitNumber", "type": "str"}, + "possible_combine_with_next": {"key": "possibleCombineWithNext", "type": "bool"}, + "driving_side": {"key": "drivingSide", "type": "str"}, + "maneuver": {"key": "maneuver", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "combined_message": {"key": "combinedMessage", "type": "str"}, + } + + def __init__( + self, + *, + point: Optional["_models.LatLongPair"] = None, + instruction_type: Optional[Union[str, "_models.GuidanceInstructionType"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword point: A location represented as a latitude and longitude. + :paramtype point: ~azure.maps.route.models.LatLongPair + :keyword instruction_type: Type of the instruction, e.g., turn or change of road form. Known + values are: "TURN", "ROAD_CHANGE", "LOCATION_DEPARTURE", "LOCATION_ARRIVAL", "DIRECTION_INFO", + and "LOCATION_WAYPOINT". + :paramtype instruction_type: str or ~azure.maps.route.models.GuidanceInstructionType + """ + super().__init__(**kwargs) + self.route_offset_in_meters = None + self.travel_time_in_seconds = None + self.point = point + self.point_index = None + self.instruction_type = instruction_type + self.road_numbers = None + self.exit_number = None + self.street = None + self.signpost_text = None + self.country_code = None + self.state_code = None + self.junction_type = None self.turn_angle_in_degrees = None self.roundabout_exit_number = None self.possible_combine_with_next = None @@ -1098,3 +1542,637 @@ def __init__( self.maneuver = None self.message = None self.combined_message = None + + +class RouteInstructionGroup(_serialization.Model): + """Groups a sequence of instruction elements which are related to each other. The sequence range + is constrained with firstInstructionIndex and lastInstructionIndex. When human-readable text + messages are requested for guidance (instructionType=text or tagged), then the instructionGroup + has a summary message returned when available. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar first_instruction_index: Index of the first instruction in the instructions and belonging + to this group. + :vartype first_instruction_index: int + :ivar last_instruction_index: Index of the last instruction in the instructions and belonging + to this group. + :vartype last_instruction_index: int + :ivar group_length_in_meters: Length of the group. + :vartype group_length_in_meters: int + :ivar group_message: Summary message when human-readable text messages are requested for + guidance (instructionType=text or tagged). + :vartype group_message: str + """ + + _validation = { + "first_instruction_index": {"readonly": True}, + "last_instruction_index": {"readonly": True}, + "group_length_in_meters": {"readonly": True}, + "group_message": {"readonly": True}, + } + + _attribute_map = { + "first_instruction_index": {"key": "firstInstructionIndex", "type": "int"}, + "last_instruction_index": {"key": "lastInstructionIndex", "type": "int"}, + "group_length_in_meters": {"key": "groupLengthInMeters", "type": "int"}, + "group_message": {"key": "groupMessage", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.first_instruction_index = None + self.last_instruction_index = None + self.group_length_in_meters = None + self.group_message = None + + +class RouteLeg(_serialization.Model): + """A description of a part of a route, comprised of a list of points. Each additional waypoint + provided in the request will result in an additional leg in the returned route. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar summary: Summary object for route section. + :vartype summary: ~azure.maps.route.models.RouteLegSummary + :ivar points: Points array. + :vartype points: list[~azure.maps.route.models.LatLongPair] + """ + + _validation = { + "summary": {"readonly": True}, + "points": {"readonly": True}, + } + + _attribute_map = { + "summary": {"key": "summary", "type": "RouteLegSummary"}, + "points": {"key": "points", "type": "[LatLongPair]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.summary = None + self.points = None + + +class RouteLegSummary(_serialization.Model): + """Summary object for route section. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar length_in_meters: Length In Meters property. + :vartype length_in_meters: int + :ivar travel_time_in_seconds: Estimated travel time in seconds property that includes the delay + due to real-time traffic. Note that even when traffic=false travelTimeInSeconds still includes + the delay due to traffic. If DepartAt is in the future, travel time is calculated using + time-dependent historic traffic data. + :vartype travel_time_in_seconds: int + :ivar traffic_delay_in_seconds: Estimated delay in seconds caused by the real-time incident(s) + according to traffic information. For routes planned with departure time in the future, delays + is always 0. To return additional travel times using different types of traffic information, + parameter computeTravelTimeFor=all needs to be added. + :vartype traffic_delay_in_seconds: int + :ivar departure_time: The estimated departure time for the route or leg. + :vartype departure_time: ~datetime.datetime + :ivar arrival_time: The estimated arrival time for the route or leg. + :vartype arrival_time: ~datetime.datetime + :ivar no_traffic_travel_time_in_seconds: Estimated travel time calculated as if there are no + delays on the route due to traffic conditions (e.g. congestion). Included only if + computeTravelTimeFor = all is used in the query. + :vartype no_traffic_travel_time_in_seconds: int + :ivar historic_traffic_travel_time_in_seconds: Estimated travel time calculated using + time-dependent historic traffic data. Included only if computeTravelTimeFor = all is used in + the query. + :vartype historic_traffic_travel_time_in_seconds: int + :ivar live_traffic_incidents_travel_time_in_seconds: Estimated travel time calculated using + real-time speed data. Included only if computeTravelTimeFor = all is used in the query. + :vartype live_traffic_incidents_travel_time_in_seconds: int + :ivar fuel_consumption_in_liters: Estimated fuel consumption in liters using the Combustion + Consumption Model. Included if vehicleEngineType is set to *combustion* and + constantSpeedConsumptionInLitersPerHundredkm is specified. The value will be non-negative. + :vartype fuel_consumption_in_liters: float + :ivar battery_consumption_in_kw_h: Estimated electric energy consumption in kilowatt hours + (kWh) using the Electric Consumption Model. Included if vehicleEngineType is set to electric + and constantSpeedConsumptionInkWhPerHundredkm is specified. The value of + batteryConsumptionInkWh includes the recuperated electric energy and can therefore be negative + (which indicates gaining energy). If both maxChargeInkWh and currentChargeInkWh are specified, + recuperation will be capped to ensure that the battery charge level never exceeds + maxChargeInkWh. If neither maxChargeInkWh nor currentChargeInkWh are specified, unconstrained + recuperation is assumed in the consumption calculation. + :vartype battery_consumption_in_kw_h: float + """ + + _validation = { + "length_in_meters": {"readonly": True}, + "travel_time_in_seconds": {"readonly": True}, + "traffic_delay_in_seconds": {"readonly": True}, + "departure_time": {"readonly": True}, + "arrival_time": {"readonly": True}, + "no_traffic_travel_time_in_seconds": {"readonly": True}, + "historic_traffic_travel_time_in_seconds": {"readonly": True}, + "live_traffic_incidents_travel_time_in_seconds": {"readonly": True}, + "fuel_consumption_in_liters": {"readonly": True}, + "battery_consumption_in_kw_h": {"readonly": True}, + } + + _attribute_map = { + "length_in_meters": {"key": "lengthInMeters", "type": "int"}, + "travel_time_in_seconds": {"key": "travelTimeInSeconds", "type": "int"}, + "traffic_delay_in_seconds": {"key": "trafficDelayInSeconds", "type": "int"}, + "departure_time": {"key": "departureTime", "type": "iso-8601"}, + "arrival_time": {"key": "arrivalTime", "type": "iso-8601"}, + "no_traffic_travel_time_in_seconds": {"key": "noTrafficTravelTimeInSeconds", "type": "int"}, + "historic_traffic_travel_time_in_seconds": {"key": "historicTrafficTravelTimeInSeconds", "type": "int"}, + "live_traffic_incidents_travel_time_in_seconds": { + "key": "liveTrafficIncidentsTravelTimeInSeconds", + "type": "int", + }, + "fuel_consumption_in_liters": {"key": "fuelConsumptionInLiters", "type": "float"}, + "battery_consumption_in_kw_h": {"key": "batteryConsumptionInkWh", "type": "float"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.length_in_meters = None + self.travel_time_in_seconds = None + self.traffic_delay_in_seconds = None + self.departure_time = None + self.arrival_time = None + self.no_traffic_travel_time_in_seconds = None + self.historic_traffic_travel_time_in_seconds = None + self.live_traffic_incidents_travel_time_in_seconds = None + self.fuel_consumption_in_liters = None + self.battery_consumption_in_kw_h = None + + +class RouteMatrix(_serialization.Model): + """Matrix result object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar status_code: StatusCode property for the current cell in the input matrix. + :vartype status_code: int + :ivar response: Response object of the current cell in the input matrix. + :vartype response: ~azure.maps.route.models.RouteMatrixResultResponse + """ + + _validation = { + "status_code": {"readonly": True}, + "response": {"readonly": True}, + } + + _attribute_map = { + "status_code": {"key": "statusCode", "type": "int"}, + "response": {"key": "response", "type": "RouteMatrixResultResponse"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.status_code = None + self.response = None + + +class RouteMatrixQuery(_serialization.Model): + """An object with a matrix of coordinates. + + :ivar origins: A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 + `__ for details. + :vartype origins: ~azure.maps.route.models.GeoJsonMultiPoint + :ivar destinations: A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 + `__ for details. + :vartype destinations: ~azure.maps.route.models.GeoJsonMultiPoint + """ + + _attribute_map = { + "origins": {"key": "origins", "type": "GeoJsonMultiPoint"}, + "destinations": {"key": "destinations", "type": "GeoJsonMultiPoint"}, + } + + def __init__( + self, + *, + origins: Optional["_models.GeoJsonMultiPoint"] = None, + destinations: Optional["_models.GeoJsonMultiPoint"] = None, + **kwargs: Any + ) -> None: + """ + :keyword origins: A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 + `__ for details. + :paramtype origins: ~azure.maps.route.models.GeoJsonMultiPoint + :keyword destinations: A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 + `__ for details. + :paramtype destinations: ~azure.maps.route.models.GeoJsonMultiPoint + """ + super().__init__(**kwargs) + self.origins = origins + self.destinations = destinations + + +class RouteMatrixResult(_serialization.Model): + """This object is returned from a successful Route Matrix call. For ex, if 2 origins and 3 + destinations are provided, there are going to 2 arrays with 3 elements in each. Each element's + content depends on the options provided in the query. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar format_version: Format Version property. + :vartype format_version: str + :ivar matrix: Results as a 2 dimensional array of route summaries. + :vartype matrix: list[list[~azure.maps.route.models.RouteMatrix]] + :ivar summary: Summary object. + :vartype summary: ~azure.maps.route.models.RouteMatrixSummary + """ + + _validation = { + "format_version": {"readonly": True}, + "matrix": {"readonly": True}, + "summary": {"readonly": True}, + } + + _attribute_map = { + "format_version": {"key": "formatVersion", "type": "str"}, + "matrix": {"key": "matrix", "type": "[[RouteMatrix]]"}, + "summary": {"key": "summary", "type": "RouteMatrixSummary"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.format_version = None + self.matrix = None + self.summary = None + + +class RouteMatrixResultResponse(_serialization.Model): + """Response object of the current cell in the input matrix. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar summary: Summary object for route section. + :vartype summary: ~azure.maps.route.models.RouteLegSummary + """ + + _validation = { + "summary": {"readonly": True}, + } + + _attribute_map = { + "summary": {"key": "routeSummary", "type": "RouteLegSummary"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.summary = None + + +class RouteMatrixSummary(_serialization.Model): + """Summary object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar successful_routes: Number of successful routes in the response. + :vartype successful_routes: int + :ivar total_routes: Total number of routes requested. Number of cells in the input matrix. + :vartype total_routes: int + """ + + _validation = { + "successful_routes": {"readonly": True}, + "total_routes": {"readonly": True}, + } + + _attribute_map = { + "successful_routes": {"key": "successfulRoutes", "type": "int"}, + "total_routes": {"key": "totalRoutes", "type": "int"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.successful_routes = None + self.total_routes = None + + +class RouteOptimizedWaypoint(_serialization.Model): + """Optimized way point object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provided_index: Way point index provided by the user. + :vartype provided_index: int + :ivar optimized_index: Optimized way point index from the system. + :vartype optimized_index: int + """ + + _validation = { + "provided_index": {"readonly": True}, + "optimized_index": {"readonly": True}, + } + + _attribute_map = { + "provided_index": {"key": "providedIndex", "type": "int"}, + "optimized_index": {"key": "optimizedIndex", "type": "int"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.provided_index = None + self.optimized_index = None + + +class RouteRange(_serialization.Model): + """Reachable Range. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar center: Center point of the reachable range. + :vartype center: ~azure.maps.route.models.LatLongPair + :ivar boundary: Polygon boundary of the reachable range represented as a list of points. + :vartype boundary: list[~azure.maps.route.models.LatLongPair] + """ + + _validation = { + "boundary": {"readonly": True}, + } + + _attribute_map = { + "center": {"key": "center", "type": "LatLongPair"}, + "boundary": {"key": "boundary", "type": "[LatLongPair]"}, + } + + def __init__(self, *, center: Optional["_models.LatLongPair"] = None, **kwargs: Any) -> None: + """ + :keyword center: Center point of the reachable range. + :paramtype center: ~azure.maps.route.models.LatLongPair + """ + super().__init__(**kwargs) + self.center = center + self.boundary = None + + +class RouteRangeResult(_serialization.Model): + """This object is returned from a successful Route Reachable Range call. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar format_version: Format Version property. + :vartype format_version: str + :ivar reachable_range: Reachable Range. + :vartype reachable_range: ~azure.maps.route.models.RouteRange + :ivar report: Reports the effective settings used in the current call. + :vartype report: ~azure.maps.route.models.RouteReport + """ + + _validation = { + "format_version": {"readonly": True}, + } + + _attribute_map = { + "format_version": {"key": "formatVersion", "type": "str"}, + "reachable_range": {"key": "reachableRange", "type": "RouteRange"}, + "report": {"key": "report", "type": "RouteReport"}, + } + + def __init__( + self, + *, + reachable_range: Optional["_models.RouteRange"] = None, + report: Optional["_models.RouteReport"] = None, + **kwargs: Any + ) -> None: + """ + :keyword reachable_range: Reachable Range. + :paramtype reachable_range: ~azure.maps.route.models.RouteRange + :keyword report: Reports the effective settings used in the current call. + :paramtype report: ~azure.maps.route.models.RouteReport + """ + super().__init__(**kwargs) + self.format_version = None + self.reachable_range = reachable_range + self.report = report + + +class RouteReport(_serialization.Model): + """Reports the effective settings used in the current call. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar effective_settings: Effective parameters or data used when calling this Route API. + :vartype effective_settings: list[~azure.maps.route.models.EffectiveSetting] + """ + + _validation = { + "effective_settings": {"readonly": True}, + } + + _attribute_map = { + "effective_settings": {"key": "effectiveSettings", "type": "[EffectiveSetting]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.effective_settings = None + + +class RouteSection(_serialization.Model): + """Route sections contain additional information about parts of a route. Each section contains at + least the elements ``startPointIndex``\\ , ``endPointIndex``\\ , and ``sectionType``. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar start_point_index: Index of the first point (offset 0) in the route this section applies + to. + :vartype start_point_index: int + :ivar end_point_index: Index of the last point (offset 0) in the route this section applies to. + :vartype end_point_index: int + :ivar section_type: Section types of the reported route response. Known values are: + "CAR_TRAIN", "COUNTRY", "FERRY", "MOTORWAY", "PEDESTRIAN", "TOLL_ROAD", "TOLL_VIGNETTE", + "TRAFFIC", "TRAVEL_MODE", "TUNNEL", "CARPOOL", and "URBAN". + :vartype section_type: str or ~azure.maps.route.models.ResponseSectionType + :ivar travel_mode: Travel mode for the calculated route. The value will be set to ``other`` if + the requested mode of transport is not possible in this section. Known values are: "car", + "truck", "taxi", "bus", "van", "motorcycle", "bicycle", "pedestrian", and "other". + :vartype travel_mode: str or ~azure.maps.route.models.ResponseTravelMode + :ivar simple_category: Type of the incident. Can currently be JAM, ROAD_WORK, ROAD_CLOSURE, or + OTHER. See "tec" for detailed information. Known values are: "JAM", "ROAD_WORK", + "ROAD_CLOSURE", and "OTHER". + :vartype simple_category: str or ~azure.maps.route.models.SimpleCategory + :ivar effective_speed_in_kmh: Effective speed of the incident in km/h, averaged over its entire + length. + :vartype effective_speed_in_kmh: int + :ivar delay_in_seconds: Delay in seconds caused by the incident. + :vartype delay_in_seconds: int + :ivar delay_magnitude: The magnitude of delay caused by the incident. These values correspond + to the values of the response field ty of the `Get Traffic Incident Detail API + `_. Known values + are: "0", "1", "2", "3", and "4". + :vartype delay_magnitude: str or ~azure.maps.route.models.DelayMagnitude + :ivar tec: Details of the traffic event, using definitions in the `TPEG2-TEC + `_ standard. Can contain effectCode and causes + elements. + :vartype tec: ~azure.maps.route.models.RouteSectionTec + """ + + _validation = { + "start_point_index": {"readonly": True}, + "end_point_index": {"readonly": True}, + "section_type": {"readonly": True}, + "travel_mode": {"readonly": True}, + "simple_category": {"readonly": True}, + "effective_speed_in_kmh": {"readonly": True}, + "delay_in_seconds": {"readonly": True}, + "delay_magnitude": {"readonly": True}, + } + + _attribute_map = { + "start_point_index": {"key": "startPointIndex", "type": "int"}, + "end_point_index": {"key": "endPointIndex", "type": "int"}, + "section_type": {"key": "sectionType", "type": "str"}, + "travel_mode": {"key": "travelMode", "type": "str"}, + "simple_category": {"key": "simpleCategory", "type": "str"}, + "effective_speed_in_kmh": {"key": "effectiveSpeedInKmh", "type": "int"}, + "delay_in_seconds": {"key": "delayInSeconds", "type": "int"}, + "delay_magnitude": {"key": "magnitudeOfDelay", "type": "str"}, + "tec": {"key": "tec", "type": "RouteSectionTec"}, + } + + def __init__(self, *, tec: Optional["_models.RouteSectionTec"] = None, **kwargs: Any) -> None: + """ + :keyword tec: Details of the traffic event, using definitions in the `TPEG2-TEC + `_ standard. Can contain effectCode and causes + elements. + :paramtype tec: ~azure.maps.route.models.RouteSectionTec + """ + super().__init__(**kwargs) + self.start_point_index = None + self.end_point_index = None + self.section_type = None + self.travel_mode = None + self.simple_category = None + self.effective_speed_in_kmh = None + self.delay_in_seconds = None + self.delay_magnitude = None + self.tec = tec + + +class RouteSectionTec(_serialization.Model): + """Details of the traffic event, using definitions in the `TPEG2-TEC + `_ standard. Can contain effectCode and causes + elements. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar effect_code: The effect on the traffic flow. Contains a value in the tec001:EffectCode + table, as defined in the `TPEG2-TEC `_ standard. Can + be used to color-code traffic events according to severity. + :vartype effect_code: int + :ivar causes: Causes array. + :vartype causes: list[~azure.maps.route.models.RouteSectionTecCause] + """ + + _validation = { + "effect_code": {"readonly": True}, + } + + _attribute_map = { + "effect_code": {"key": "effectCode", "type": "int"}, + "causes": {"key": "causes", "type": "[RouteSectionTecCause]"}, + } + + def __init__(self, *, causes: Optional[List["_models.RouteSectionTecCause"]] = None, **kwargs: Any) -> None: + """ + :keyword causes: Causes array. + :paramtype causes: list[~azure.maps.route.models.RouteSectionTecCause] + """ + super().__init__(**kwargs) + self.effect_code = None + self.causes = causes + + +class RouteSectionTecCause(_serialization.Model): + """The cause of the traffic event. Can contain mainCauseCode and subCauseCode elements. Can be + used to define iconography and descriptions. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar main_cause_code: The main cause of the traffic event. Contains a value in the + tec002:CauseCode table, as defined in the `TPEG2-TEC + `_ standard. + :vartype main_cause_code: int + :ivar sub_cause_code: The subcause of the traffic event. Contains a value in the sub cause + table defined by the mainCauseCode, as defined in the `TPEG2-TEC + `_ standard. + :vartype sub_cause_code: int + """ + + _validation = { + "main_cause_code": {"readonly": True}, + "sub_cause_code": {"readonly": True}, + } + + _attribute_map = { + "main_cause_code": {"key": "mainCauseCode", "type": "int"}, + "sub_cause_code": {"key": "subCauseCode", "type": "int"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.main_cause_code = None + self.sub_cause_code = None + + +class RouteSummary(_serialization.Model): + """Summary object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar length_in_meters: Length In Meters property. + :vartype length_in_meters: int + :ivar travel_time_in_seconds: Estimated travel time in seconds property that includes the delay + due to real-time traffic. Note that even when traffic=false travelTimeInSeconds still includes + the delay due to traffic. If DepartAt is in the future, travel time is calculated using + time-dependent historic traffic data. + :vartype travel_time_in_seconds: int + :ivar traffic_delay_in_seconds: Estimated delay in seconds caused by the real-time incident(s) + according to traffic information. For routes planned with departure time in the future, delays + is always 0. To return additional travel times using different types of traffic information, + parameter computeTravelTimeFor=all needs to be added. + :vartype traffic_delay_in_seconds: int + :ivar departure_time: The estimated departure time for the route or leg. + :vartype departure_time: ~datetime.datetime + :ivar arrival_time: The estimated arrival time for the route or leg. + :vartype arrival_time: ~datetime.datetime + """ + + _validation = { + "length_in_meters": {"readonly": True}, + "travel_time_in_seconds": {"readonly": True}, + "traffic_delay_in_seconds": {"readonly": True}, + "departure_time": {"readonly": True}, + "arrival_time": {"readonly": True}, + } + + _attribute_map = { + "length_in_meters": {"key": "lengthInMeters", "type": "int"}, + "travel_time_in_seconds": {"key": "travelTimeInSeconds", "type": "int"}, + "traffic_delay_in_seconds": {"key": "trafficDelayInSeconds", "type": "int"}, + "departure_time": {"key": "departureTime", "type": "iso-8601"}, + "arrival_time": {"key": "arrivalTime", "type": "iso-8601"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.length_in_meters = None + self.travel_time_in_seconds = None + self.traffic_delay_in_seconds = None + self.departure_time = None + self.arrival_time = None diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_patch.py b/sdk/maps/azure-maps-route/azure/maps/route/models/_patch.py similarity index 99% rename from sdk/maps/azure-maps-route/azure/maps/route/_generated/_patch.py rename to sdk/maps/azure-maps-route/azure/maps/route/models/_patch.py index f7dd32510333..49900f6ab120 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_patch.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/models/_patch.py @@ -2,6 +2,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/operations/__init__.py similarity index 84% rename from sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/__init__.py rename to sdk/maps/azure-maps-route/azure/maps/route/operations/__init__.py index 08df5df8aeba..f8e1ce9dec01 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/__init__.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/operations/__init__.py @@ -6,10 +6,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._operations import RouteOperations - from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk __all__ = [ diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/_operations.py b/sdk/maps/azure-maps-route/azure/maps/route/operations/_operations.py similarity index 85% rename from sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/_operations.py rename to sdk/maps/azure-maps-route/azure/maps/route/operations/_operations.py index 8cd8752ec90b..e431345bf2b5 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/_operations.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/operations/_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines, R0914, R0915, R0912 # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,9 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime -from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterator, List, Optional, Type, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -15,20 +17,24 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.polling.base_polling import LROBasePolling -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 .. import models as _models from .._serialization import Serializer -from .._vendor import _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -63,8 +69,8 @@ def build_route_request_route_matrix_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "1.0")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -73,7 +79,7 @@ def build_route_request_route_matrix_request( "format": _SERIALIZER.url("format", format, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -130,7 +136,7 @@ def build_route_get_route_matrix_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "1.0")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -139,7 +145,7 @@ def build_route_get_route_matrix_request( "format": _SERIALIZER.url("matrix_id", matrix_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -152,7 +158,7 @@ def build_route_get_route_matrix_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_route_request_route_matrix_sync_request( +def build_route_request_route_matrix_sync_request( # pylint: disable=name-too-long format: Union[str, _models.JsonFormat] = "json", *, wait_for_results: Optional[bool] = None, @@ -179,8 +185,8 @@ def build_route_request_route_matrix_sync_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "1.0")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -189,7 +195,7 @@ def build_route_request_route_matrix_sync_request( "format": _SERIALIZER.url("format", format, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -291,7 +297,7 @@ def build_route_get_route_directions_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "1.0")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -300,7 +306,7 @@ def build_route_get_route_directions_request( "format": _SERIALIZER.url("format", format, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -422,7 +428,7 @@ def build_route_get_route_directions_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_route_get_route_directions_with_additional_parameters_request( +def build_route_get_route_directions_with_additional_parameters_request( # pylint: disable=name-too-long format: Union[str, _models.ResponseFormat] = "json", *, route_points: str, @@ -473,8 +479,8 @@ def build_route_get_route_directions_with_additional_parameters_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "1.0")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -483,7 +489,7 @@ def build_route_get_route_directions_with_additional_parameters_request( "format": _SERIALIZER.url("format", format, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -649,7 +655,7 @@ def build_route_get_route_range_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "1.0")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -658,7 +664,7 @@ def build_route_get_route_range_request( "format": _SERIALIZER.url("format", format, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -758,14 +764,14 @@ def build_route_get_route_range_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_route_request_route_directions_batch_request( +def build_route_request_route_directions_batch_request( # pylint: disable=name-too-long format: Union[str, _models.JsonFormat] = "json", *, client_id: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "1.0")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -774,7 +780,7 @@ def build_route_request_route_directions_batch_request( "format": _SERIALIZER.url("format", format, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -789,13 +795,13 @@ def build_route_request_route_directions_batch_request( return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_route_get_route_directions_batch_request( +def build_route_get_route_directions_batch_request( # pylint: disable=name-too-long batch_id: str, *, client_id: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "1.0")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -804,7 +810,7 @@ def build_route_get_route_directions_batch_request( "format": _SERIALIZER.url("batch_id", batch_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -817,14 +823,14 @@ def build_route_get_route_directions_batch_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_route_request_route_directions_batch_sync_request( +def build_route_request_route_directions_batch_sync_request( # pylint: disable=name-too-long format: Union[str, _models.JsonFormat] = "json", *, client_id: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "1.0")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -833,7 +839,7 @@ def build_route_request_route_directions_batch_sync_request( "format": _SERIALIZER.url("format", format, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -869,7 +875,7 @@ def __init__(self, *args, **kwargs): def _request_route_matrix_initial( self, - route_matrix_query: Union[_models.RouteMatrixQuery, IO], + route_matrix_query: Union[_models.RouteMatrixQuery, IO[bytes]], format: Union[str, _models.JsonFormat] = "json", *, wait_for_results: Optional[bool] = None, @@ -891,8 +897,8 @@ def _request_route_matrix_initial( route_type: Optional[Union[str, _models.RouteType]] = None, vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, **kwargs: Any - ) -> Optional[_models.RouteMatrixResult]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -903,18 +909,18 @@ def _request_route_matrix_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteMatrixResult]] + 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(route_matrix_query, (IO, bytes)): + if isinstance(route_matrix_query, (IOBase, bytes)): _content = route_matrix_query else: _json = self._serialize.body(route_matrix_query, "RouteMatrixQuery") - request = build_route_request_route_matrix_request( + _request = build_route_request_route_matrix_request( format=format, wait_for_results=wait_for_results, compute_travel_time=compute_travel_time, @@ -942,30 +948,33 @@ def _request_route_matrix_initial( headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("RouteMatrixResult", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + deserialized = response.iter_bytes() + if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @overload def begin_request_route_matrix( @@ -994,7 +1003,7 @@ def begin_request_route_matrix( content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.RouteMatrixResult]: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. The Matrix Routing service allows calculation of a matrix of route summaries for a set of routes defined by origin and destination locations by using an asynchronous (async) or @@ -1023,8 +1032,7 @@ def begin_request_route_matrix( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} Submit Asynchronous Route Matrix Request ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -1045,36 +1053,32 @@ def begin_request_route_matrix( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} Here's a typical sequence of asynchronous operations: - #. - Client sends a Route Matrix POST request to Azure Maps + #. Client sends a Route Matrix POST request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Route Matrix request has been accepted. HTTP ``Error`` - There was an error processing your Route Matrix request. This could - either be a 400 Bad Request or any other Error status code. + either be a 400 Bad Request or any other Error status code. - #. - If the Matrix Route request was accepted successfully, the Location header in the response - contains the URL to download the results of the request. This status URI looks like the - following: + #. If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} #. Client issues a GET request on the download URL obtained in Step 3 to download the results @@ -1096,7 +1100,7 @@ def begin_request_route_matrix( .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} The URL provided by the location header will return the following responses when a ``GET`` request is issued. @@ -1104,10 +1108,10 @@ def begin_request_route_matrix( .. HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try - again in some time. + again in some time. HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of - the results. + the results. :param route_matrix_query: The matrix of origin and destination coordinates to compute the route distance, travel time and other summary for each cell of the matrix based on the input @@ -1128,7 +1132,7 @@ def begin_request_route_matrix( best-estimate travel time. Known values are: "none" and "all". Default value is None. :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -1161,25 +1165,23 @@ def begin_request_route_matrix( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. :paramtype vehicle_weight: int :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -1201,9 +1203,8 @@ def begin_request_route_matrix( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -1221,13 +1222,6 @@ def begin_request_route_matrix( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. 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 RouteMatrixResult :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteMatrixResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -1236,7 +1230,7 @@ def begin_request_route_matrix( @overload def begin_request_route_matrix( self, - route_matrix_query: IO, + route_matrix_query: IO[bytes], format: Union[str, _models.JsonFormat] = "json", *, wait_for_results: Optional[bool] = None, @@ -1260,7 +1254,7 @@ def begin_request_route_matrix( content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.RouteMatrixResult]: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. The Matrix Routing service allows calculation of a matrix of route summaries for a set of routes defined by origin and destination locations by using an asynchronous (async) or @@ -1289,8 +1283,7 @@ def begin_request_route_matrix( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} Submit Asynchronous Route Matrix Request ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -1311,36 +1304,32 @@ def begin_request_route_matrix( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} Here's a typical sequence of asynchronous operations: - #. - Client sends a Route Matrix POST request to Azure Maps + #. Client sends a Route Matrix POST request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Route Matrix request has been accepted. HTTP ``Error`` - There was an error processing your Route Matrix request. This could - either be a 400 Bad Request or any other Error status code. + either be a 400 Bad Request or any other Error status code. - #. - If the Matrix Route request was accepted successfully, the Location header in the response - contains the URL to download the results of the request. This status URI looks like the - following: + #. If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} #. Client issues a GET request on the download URL obtained in Step 3 to download the results @@ -1362,7 +1351,7 @@ def begin_request_route_matrix( .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} The URL provided by the location header will return the following responses when a ``GET`` request is issued. @@ -1370,17 +1359,17 @@ def begin_request_route_matrix( .. HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try - again in some time. + again in some time. HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of - the results. + the results. :param route_matrix_query: The matrix of origin and destination coordinates to compute the route distance, travel time and other summary for each cell of the matrix based on the input parameters. The minimum and the maximum cell count supported are 1 and **700** for async and **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 origins and 25 destinations for async API. Required. - :type route_matrix_query: IO + :type route_matrix_query: IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat @@ -1394,7 +1383,7 @@ def begin_request_route_matrix( best-estimate travel time. Known values are: "none" and "all". Default value is None. :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -1427,25 +1416,23 @@ def begin_request_route_matrix( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. :paramtype vehicle_weight: int :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -1467,9 +1454,8 @@ def begin_request_route_matrix( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -1487,13 +1473,6 @@ def begin_request_route_matrix( :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. 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 RouteMatrixResult :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteMatrixResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -1502,7 +1481,7 @@ def begin_request_route_matrix( @distributed_trace def begin_request_route_matrix( self, - route_matrix_query: Union[_models.RouteMatrixQuery, IO], + route_matrix_query: Union[_models.RouteMatrixQuery, IO[bytes]], format: Union[str, _models.JsonFormat] = "json", *, wait_for_results: Optional[bool] = None, @@ -1525,7 +1504,7 @@ def begin_request_route_matrix( vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, **kwargs: Any ) -> LROPoller[_models.RouteMatrixResult]: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. The Matrix Routing service allows calculation of a matrix of route summaries for a set of routes defined by origin and destination locations by using an asynchronous (async) or @@ -1554,8 +1533,7 @@ def begin_request_route_matrix( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} Submit Asynchronous Route Matrix Request ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -1576,36 +1554,32 @@ def begin_request_route_matrix( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} Here's a typical sequence of asynchronous operations: - #. - Client sends a Route Matrix POST request to Azure Maps + #. Client sends a Route Matrix POST request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Route Matrix request has been accepted. HTTP ``Error`` - There was an error processing your Route Matrix request. This could - either be a 400 Bad Request or any other Error status code. + either be a 400 Bad Request or any other Error status code. - #. - If the Matrix Route request was accepted successfully, the Location header in the response - contains the URL to download the results of the request. This status URI looks like the - following: + #. If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} #. Client issues a GET request on the download URL obtained in Step 3 to download the results @@ -1627,7 +1601,7 @@ def begin_request_route_matrix( .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} The URL provided by the location header will return the following responses when a ``GET`` request is issued. @@ -1635,17 +1609,18 @@ def begin_request_route_matrix( .. HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try - again in some time. + again in some time. HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of - the results. + the results. :param route_matrix_query: The matrix of origin and destination coordinates to compute the route distance, travel time and other summary for each cell of the matrix based on the input parameters. The minimum and the maximum cell count supported are 1 and **700** for async and **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 - origins and 25 destinations for async API. Is either a model type or a IO type. Required. - :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery or IO + origins and 25 destinations for async API. Is either a RouteMatrixQuery type or a IO[bytes] + type. Required. + :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery or IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat @@ -1659,7 +1634,7 @@ def begin_request_route_matrix( best-estimate travel time. Known values are: "none" and "all". Default value is None. :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -1692,25 +1667,23 @@ def begin_request_route_matrix( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. :paramtype vehicle_weight: int :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -1732,9 +1705,8 @@ def begin_request_route_matrix( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -1749,16 +1721,6 @@ def begin_request_route_matrix( "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is None. :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. 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 RouteMatrixResult :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteMatrixResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -1766,13 +1728,13 @@ def begin_request_route_matrix( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteMatrixResult] - polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RouteMatrixResult] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._request_route_matrix_initial( # type: ignore + raw_result = self._request_route_matrix_initial( route_matrix_query=route_matrix_query, format=format, wait_for_results=wait_for_results, @@ -1799,33 +1761,36 @@ def begin_request_route_matrix( 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("RouteMatrixResult", pipeline_response) + deserialized = self._deserialize("RouteMatrixResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: - polling_method = cast( + polling_method: PollingMethod = cast( PollingMethod, LROBasePolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) # type: PollingMethod + ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.RouteMatrixResult].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) + return LROPoller[_models.RouteMatrixResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - def _get_route_matrix_initial(self, matrix_id: str, **kwargs: Any) -> Optional[_models.RouteMatrixResult]: - error_map = { + def _get_route_matrix_initial(self, matrix_id: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1836,43 +1801,46 @@ def _get_route_matrix_initial(self, matrix_id: str, **kwargs: Any) -> Optional[_ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteMatrixResult]] + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_route_get_route_matrix_request( + _request = build_route_get_route_matrix_request( matrix_id=matrix_id, client_id=self._config.client_id, api_version=self._config.api_version, headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("RouteMatrixResult", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + deserialized = response.iter_bytes() + if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace def begin_get_route_matrix(self, matrix_id: str, **kwargs: Any) -> LROPoller[_models.RouteMatrixResult]: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. If the Matrix Route request was accepted successfully, the Location header in the response contains the URL to download the results of the request. This status URI looks like the @@ -1881,7 +1849,7 @@ def begin_get_route_matrix(self, matrix_id: str, **kwargs: Any) -> LROPoller[_mo .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} #. Client issues a GET request on the download URL obtained in Step 3 to download the results @@ -1903,7 +1871,7 @@ def begin_get_route_matrix(self, matrix_id: str, **kwargs: Any) -> LROPoller[_mo .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} The URL provided by the location header will return the following responses when a ``GET`` request is issued. @@ -1911,21 +1879,14 @@ def begin_get_route_matrix(self, matrix_id: str, **kwargs: Any) -> LROPoller[_mo .. HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try - again in some time. + again in some time. HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of - the results. + the results. :param matrix_id: Matrix id received after the Matrix Route request was accepted successfully. Required. :type matrix_id: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. 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 RouteMatrixResult :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteMatrixResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -1933,38 +1894,41 @@ def begin_get_route_matrix(self, matrix_id: str, **kwargs: Any) -> LROPoller[_mo _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteMatrixResult] - polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + cls: ClsType[_models.RouteMatrixResult] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._get_route_matrix_initial( # type: ignore + raw_result = self._get_route_matrix_initial( matrix_id=matrix_id, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("RouteMatrixResult", pipeline_response) + deserialized = self._deserialize("RouteMatrixResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: - polling_method = cast( + polling_method: PollingMethod = cast( PollingMethod, LROBasePolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs) - ) # type: PollingMethod + ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.RouteMatrixResult].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) + return LROPoller[_models.RouteMatrixResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @overload def request_route_matrix_sync( @@ -1993,7 +1957,7 @@ def request_route_matrix_sync( content_type: str = "application/json", **kwargs: Any ) -> _models.RouteMatrixResult: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. The Matrix Routing service allows calculation of a matrix of route summaries for a set of routes defined by origin and destination locations by using an asynchronous (async) or @@ -2022,8 +1986,7 @@ def request_route_matrix_sync( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} Submit Asynchronous Route Matrix Request ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -2044,36 +2007,32 @@ def request_route_matrix_sync( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} Here's a typical sequence of asynchronous operations: - #. - Client sends a Route Matrix POST request to Azure Maps + #. Client sends a Route Matrix POST request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Route Matrix request has been accepted. HTTP ``Error`` - There was an error processing your Route Matrix request. This could - either be a 400 Bad Request or any other Error status code. + either be a 400 Bad Request or any other Error status code. - #. - If the Matrix Route request was accepted successfully, the Location header in the response - contains the URL to download the results of the request. This status URI looks like the - following: + #. If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} #. Client issues a GET request on the download URL obtained in Step 3 to download the results @@ -2095,7 +2054,7 @@ def request_route_matrix_sync( .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} The URL provided by the location header will return the following responses when a ``GET`` request is issued. @@ -2103,10 +2062,10 @@ def request_route_matrix_sync( .. HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try - again in some time. + again in some time. HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of - the results. + the results. :param route_matrix_query: The matrix of origin and destination coordinates to compute the route distance, travel time and other summary for each cell of the matrix based on the input @@ -2127,7 +2086,7 @@ def request_route_matrix_sync( best-estimate travel time. Known values are: "none" and "all". Default value is None. :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -2160,25 +2119,23 @@ def request_route_matrix_sync( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. :paramtype vehicle_weight: int :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -2200,9 +2157,8 @@ def request_route_matrix_sync( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -2228,7 +2184,7 @@ def request_route_matrix_sync( @overload def request_route_matrix_sync( self, - route_matrix_query: IO, + route_matrix_query: IO[bytes], format: Union[str, _models.JsonFormat] = "json", *, wait_for_results: Optional[bool] = None, @@ -2252,7 +2208,7 @@ def request_route_matrix_sync( content_type: str = "application/json", **kwargs: Any ) -> _models.RouteMatrixResult: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. The Matrix Routing service allows calculation of a matrix of route summaries for a set of routes defined by origin and destination locations by using an asynchronous (async) or @@ -2281,8 +2237,7 @@ def request_route_matrix_sync( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} Submit Asynchronous Route Matrix Request ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -2303,36 +2258,32 @@ def request_route_matrix_sync( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} Here's a typical sequence of asynchronous operations: - #. - Client sends a Route Matrix POST request to Azure Maps + #. Client sends a Route Matrix POST request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Route Matrix request has been accepted. HTTP ``Error`` - There was an error processing your Route Matrix request. This could - either be a 400 Bad Request or any other Error status code. + either be a 400 Bad Request or any other Error status code. - #. - If the Matrix Route request was accepted successfully, the Location header in the response - contains the URL to download the results of the request. This status URI looks like the - following: + #. If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} #. Client issues a GET request on the download URL obtained in Step 3 to download the results @@ -2354,7 +2305,7 @@ def request_route_matrix_sync( .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} The URL provided by the location header will return the following responses when a ``GET`` request is issued. @@ -2362,17 +2313,17 @@ def request_route_matrix_sync( .. HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try - again in some time. + again in some time. HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of - the results. + the results. :param route_matrix_query: The matrix of origin and destination coordinates to compute the route distance, travel time and other summary for each cell of the matrix based on the input parameters. The minimum and the maximum cell count supported are 1 and **700** for async and **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 origins and 25 destinations for async API. Required. - :type route_matrix_query: IO + :type route_matrix_query: IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat @@ -2386,7 +2337,7 @@ def request_route_matrix_sync( best-estimate travel time. Known values are: "none" and "all". Default value is None. :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -2419,25 +2370,23 @@ def request_route_matrix_sync( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. :paramtype vehicle_weight: int :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -2459,9 +2408,8 @@ def request_route_matrix_sync( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -2487,7 +2435,7 @@ def request_route_matrix_sync( @distributed_trace def request_route_matrix_sync( self, - route_matrix_query: Union[_models.RouteMatrixQuery, IO], + route_matrix_query: Union[_models.RouteMatrixQuery, IO[bytes]], format: Union[str, _models.JsonFormat] = "json", *, wait_for_results: Optional[bool] = None, @@ -2510,7 +2458,7 @@ def request_route_matrix_sync( vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, **kwargs: Any ) -> _models.RouteMatrixResult: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. The Matrix Routing service allows calculation of a matrix of route summaries for a set of routes defined by origin and destination locations by using an asynchronous (async) or @@ -2539,8 +2487,7 @@ def request_route_matrix_sync( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} Submit Asynchronous Route Matrix Request ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -2561,36 +2508,32 @@ def request_route_matrix_sync( .. code-block:: - POST - https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + POST https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} Here's a typical sequence of asynchronous operations: - #. - Client sends a Route Matrix POST request to Azure Maps + #. Client sends a Route Matrix POST request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Route Matrix request has been accepted. HTTP ``Error`` - There was an error processing your Route Matrix request. This could - either be a 400 Bad Request or any other Error status code. + either be a 400 Bad Request or any other Error status code. - #. - If the Matrix Route request was accepted successfully, the Location header in the response - contains the URL to download the results of the request. This status URI looks like the - following: + #. If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} #. Client issues a GET request on the download URL obtained in Step 3 to download the results @@ -2612,7 +2555,7 @@ def request_route_matrix_sync( .. code-block:: GET - https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} The URL provided by the location header will return the following responses when a ``GET`` request is issued. @@ -2620,17 +2563,18 @@ def request_route_matrix_sync( .. HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try - again in some time. + again in some time. HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of - the results. + the results. :param route_matrix_query: The matrix of origin and destination coordinates to compute the route distance, travel time and other summary for each cell of the matrix based on the input parameters. The minimum and the maximum cell count supported are 1 and **700** for async and **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 - origins and 25 destinations for async API. Is either a model type or a IO type. Required. - :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery or IO + origins and 25 destinations for async API. Is either a RouteMatrixQuery type or a IO[bytes] + type. Required. + :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery or IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat @@ -2644,7 +2588,7 @@ def request_route_matrix_sync( best-estimate travel time. Known values are: "none" and "all". Default value is None. :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -2677,25 +2621,23 @@ def request_route_matrix_sync( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. :paramtype vehicle_weight: int :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -2717,9 +2659,8 @@ def request_route_matrix_sync( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -2734,20 +2675,20 @@ def request_route_matrix_sync( "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is None. :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str :return: RouteMatrixResult :rtype: ~azure.maps.route.models.RouteMatrixResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, - 408: lambda response: HttpResponseError( - response=response, model=self._deserialize(_models.ErrorResponse, response) + 408: cast( + Type[HttpResponseError], + lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.ErrorResponse, response) + ), ), } error_map.update(kwargs.pop("error_map", {}) or {}) @@ -2755,18 +2696,18 @@ def request_route_matrix_sync( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteMatrixResult] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RouteMatrixResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(route_matrix_query, (IO, bytes)): + if isinstance(route_matrix_query, (IOBase, bytes)): _content = route_matrix_query else: _json = self._serialize.body(route_matrix_query, "RouteMatrixQuery") - request = build_route_request_route_matrix_sync_request( + _request = build_route_request_route_matrix_sync_request( format=format, wait_for_results=wait_for_results, compute_travel_time=compute_travel_time, @@ -2794,10 +2735,11 @@ def request_route_matrix_sync( headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -2807,12 +2749,12 @@ def request_route_matrix_sync( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("RouteMatrixResult", pipeline_response) + deserialized = self._deserialize("RouteMatrixResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace def get_route_directions( @@ -2863,7 +2805,7 @@ def get_route_directions( auxiliary_power_in_kw: Optional[float] = None, **kwargs: Any ) -> _models.RouteDirections: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. Returns a route between an origin and a destination, passing through waypoints if they are specified. The route will take into account factors such as current traffic and the typical @@ -2978,7 +2920,7 @@ def get_route_directions( parameter was not specified by the caller. "effectiveSettings" Default value is None. :paramtype report: str or ~azure.maps.route.models.Report :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -3000,33 +2942,27 @@ def get_route_directions( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. - * - It is mandatory if any of the *Efficiency parameters are set. + * It is mandatory if any of the *Efficiency parameters are set. - * - It must be strictly positive when used in the context of the Consumption Model. Weight + * It must be strictly positive when used in the context of the Consumption Model. Weight restrictions are considered. - * - If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + * If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is non-zero, then weight restrictions are considered. - * - In all other cases, this parameter is ignored. + * In all other cases, this parameter is ignored. Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default value is 0. @@ -3035,11 +2971,11 @@ def get_route_directions( vehicles may not be allowed to drive on some roads. Default value is False. :paramtype is_commercial_vehicle: bool :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -3061,9 +2997,8 @@ def get_route_directions( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -3090,12 +3025,10 @@ def get_route_directions( as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list + * by linear interpolation, if the given speed lies in between two speeds in the list - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by - the nearest two points in the list + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of @@ -3143,7 +3076,7 @@ def get_route_directions( Must be paired with **decelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **decelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default value is None. @@ -3155,7 +3088,7 @@ def get_route_directions( Must be paired with **accelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **accelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default value is None. @@ -3167,7 +3100,7 @@ def get_route_directions( Must be paired with **downhillEfficiency**. - The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **downhillEfficiency**. Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default value is None. @@ -3179,7 +3112,7 @@ def get_route_directions( Must be paired with **uphillEfficiency**. - The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **uphillEfficiency**. Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default value is None. @@ -3191,12 +3124,10 @@ def get_route_directions( consumption curve. Consumption rates for speeds not in the list are found as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list + * by linear interpolation, if the given speed lies in between two speeds in the list - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by - the nearest two points in the list + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of @@ -3246,7 +3177,7 @@ def get_route_directions( :rtype: ~azure.maps.route.models.RouteDirections :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3257,9 +3188,9 @@ def get_route_directions( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirections] + cls: ClsType[_models.RouteDirections] = kwargs.pop("cls", None) - request = build_route_get_route_directions_request( + _request = build_route_get_route_directions_request( format=format, route_points=route_points, max_alternatives=max_alternatives, @@ -3308,10 +3239,11 @@ def get_route_directions( headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -3321,15 +3253,15 @@ def get_route_directions( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("RouteDirections", pipeline_response) + deserialized = self._deserialize("RouteDirections", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore @overload - def get_route_directions_with_additional_parameters( + def get_route_directions_with_additional_parameters( # pylint: disable=name-too-long self, route_direction_parameters: _models.RouteDirectionParameters, format: Union[str, _models.ResponseFormat] = "json", @@ -3379,7 +3311,7 @@ def get_route_directions_with_additional_parameters( content_type: str = "application/json", **kwargs: Any ) -> _models.RouteDirections: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. Returns a route between an origin and a destination, passing through waypoints if they are specified. The route will take into account factors such as current traffic and the typical @@ -3408,14 +3340,14 @@ def get_route_directions_with_additional_parameters( * The origin point of the calculateRoute request must be on (or very near) the input reference - route. If this is not the case, an error is returned. However, the origin point does not need - to be at the beginning of the input reference route (it can be thought of as the current - vehicle position on the reference route). + route. If this is not the case, an error is returned. However, the origin point does not need + to be at the beginning of the input reference route (it can be thought of as the current + vehicle position on the reference route). * The reference route, returned as the first route in the calculateRoute response, will start - at the origin point specified in the calculateRoute request. The initial part of the input - reference route up until the origin point will be excluded from the response. + at the origin point specified in the calculateRoute request. The initial part of the input + reference route up until the origin point will be excluded from the response. * The values of minDeviationDistance and minDeviationTime determine how far alternative routes - will be guaranteed to follow the reference route from the origin point onwards. + will be guaranteed to follow the reference route from the origin point onwards. * The route must use departAt. * The vehicleHeading is ignored. Required. :type route_direction_parameters: ~azure.maps.route.models.RouteDirectionParameters @@ -3504,7 +3436,7 @@ def get_route_directions_with_additional_parameters( parameter was not specified by the caller. "effectiveSettings" Default value is None. :paramtype report: str or ~azure.maps.route.models.Report :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -3537,33 +3469,27 @@ def get_route_directions_with_additional_parameters( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. - * - It is mandatory if any of the *Efficiency parameters are set. + * It is mandatory if any of the *Efficiency parameters are set. - * - It must be strictly positive when used in the context of the Consumption Model. Weight - restrictions are considered. + * It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. - * - If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is - non-zero, then weight restrictions are considered. + * If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. - * - In all other cases, this parameter is ignored. + * In all other cases, this parameter is ignored. Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default value is 0. @@ -3572,11 +3498,11 @@ def get_route_directions_with_additional_parameters( vehicles may not be allowed to drive on some roads. Default value is False. :paramtype is_commercial_vehicle: bool :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -3598,9 +3524,8 @@ def get_route_directions_with_additional_parameters( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -3627,12 +3552,10 @@ def get_route_directions_with_additional_parameters( as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list + * by linear interpolation, if the given speed lies in between two speeds in the list - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by - the nearest two points in the list + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of @@ -3680,7 +3603,7 @@ def get_route_directions_with_additional_parameters( Must be paired with **decelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **decelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default value is None. @@ -3692,7 +3615,7 @@ def get_route_directions_with_additional_parameters( Must be paired with **accelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **accelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default value is None. @@ -3704,7 +3627,7 @@ def get_route_directions_with_additional_parameters( Must be paired with **downhillEfficiency**. - The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **downhillEfficiency**. Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default value is None. @@ -3716,7 +3639,7 @@ def get_route_directions_with_additional_parameters( Must be paired with **uphillEfficiency**. - The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **uphillEfficiency**. Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default value is None. @@ -3728,12 +3651,10 @@ def get_route_directions_with_additional_parameters( consumption curve. Consumption rates for speeds not in the list are found as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list + * by linear interpolation, if the given speed lies in between two speeds in the list - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by - the nearest two points in the list + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of @@ -3788,9 +3709,9 @@ def get_route_directions_with_additional_parameters( """ @overload - def get_route_directions_with_additional_parameters( + def get_route_directions_with_additional_parameters( # pylint: disable=name-too-long self, - route_direction_parameters: IO, + route_direction_parameters: IO[bytes], format: Union[str, _models.ResponseFormat] = "json", *, route_points: str, @@ -3838,7 +3759,7 @@ def get_route_directions_with_additional_parameters( content_type: str = "application/json", **kwargs: Any ) -> _models.RouteDirections: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. Returns a route between an origin and a destination, passing through waypoints if they are specified. The route will take into account factors such as current traffic and the typical @@ -3867,17 +3788,17 @@ def get_route_directions_with_additional_parameters( * The origin point of the calculateRoute request must be on (or very near) the input reference - route. If this is not the case, an error is returned. However, the origin point does not need - to be at the beginning of the input reference route (it can be thought of as the current - vehicle position on the reference route). + route. If this is not the case, an error is returned. However, the origin point does not need + to be at the beginning of the input reference route (it can be thought of as the current + vehicle position on the reference route). * The reference route, returned as the first route in the calculateRoute response, will start - at the origin point specified in the calculateRoute request. The initial part of the input - reference route up until the origin point will be excluded from the response. + at the origin point specified in the calculateRoute request. The initial part of the input + reference route up until the origin point will be excluded from the response. * The values of minDeviationDistance and minDeviationTime determine how far alternative routes - will be guaranteed to follow the reference route from the origin point onwards. + will be guaranteed to follow the reference route from the origin point onwards. * The route must use departAt. * The vehicleHeading is ignored. Required. - :type route_direction_parameters: IO + :type route_direction_parameters: IO[bytes] :param format: Desired format of the response. Value can be either *json* or *xml*. Known values are: "json" and "xml". Default value is "json". :type format: str or ~azure.maps.route.models.ResponseFormat @@ -3963,7 +3884,7 @@ def get_route_directions_with_additional_parameters( parameter was not specified by the caller. "effectiveSettings" Default value is None. :paramtype report: str or ~azure.maps.route.models.Report :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -3996,33 +3917,27 @@ def get_route_directions_with_additional_parameters( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. - * - It is mandatory if any of the *Efficiency parameters are set. + * It is mandatory if any of the *Efficiency parameters are set. - * - It must be strictly positive when used in the context of the Consumption Model. Weight - restrictions are considered. + * It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. - * - If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is - non-zero, then weight restrictions are considered. + * If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. - * - In all other cases, this parameter is ignored. + * In all other cases, this parameter is ignored. Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default value is 0. @@ -4031,11 +3946,11 @@ def get_route_directions_with_additional_parameters( vehicles may not be allowed to drive on some roads. Default value is False. :paramtype is_commercial_vehicle: bool :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -4057,9 +3972,8 @@ def get_route_directions_with_additional_parameters( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -4086,11 +4000,9 @@ def get_route_directions_with_additional_parameters( as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list + * by linear interpolation, if the given speed lies in between two speeds in the list - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate @@ -4139,7 +4051,7 @@ def get_route_directions_with_additional_parameters( Must be paired with **decelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **decelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default value is None. @@ -4151,7 +4063,7 @@ def get_route_directions_with_additional_parameters( Must be paired with **accelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **accelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default value is None. @@ -4163,7 +4075,7 @@ def get_route_directions_with_additional_parameters( Must be paired with **downhillEfficiency**. - The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **downhillEfficiency**. Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default value is None. @@ -4175,7 +4087,7 @@ def get_route_directions_with_additional_parameters( Must be paired with **uphillEfficiency**. - The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **uphillEfficiency**. Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default value is None. @@ -4187,12 +4099,10 @@ def get_route_directions_with_additional_parameters( consumption curve. Consumption rates for speeds not in the list are found as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list + * by linear interpolation, if the given speed lies in between two speeds in the list - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by - the nearest two points in the list + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of @@ -4247,9 +4157,9 @@ def get_route_directions_with_additional_parameters( """ @distributed_trace - def get_route_directions_with_additional_parameters( + def get_route_directions_with_additional_parameters( # pylint: disable=name-too-long self, - route_direction_parameters: Union[_models.RouteDirectionParameters, IO], + route_direction_parameters: Union[_models.RouteDirectionParameters, IO[bytes]], format: Union[str, _models.ResponseFormat] = "json", *, route_points: str, @@ -4296,7 +4206,7 @@ def get_route_directions_with_additional_parameters( auxiliary_power_in_kw: Optional[float] = None, **kwargs: Any ) -> _models.RouteDirections: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. Returns a route between an origin and a destination, passing through waypoints if they are specified. The route will take into account factors such as current traffic and the typical @@ -4325,17 +4235,21 @@ def get_route_directions_with_additional_parameters( * The origin point of the calculateRoute request must be on (or very near) the input reference - route. If this is not the case, an error is returned. However, the origin point does not need - to be at the beginning of the input reference route (it can be thought of as the current - vehicle position on the reference route). + route. If this is not the case, an error is returned. However, the origin point does not need + to be at the beginning of the input reference route (it can be thought of as the current + vehicle position on the reference route). + * The reference route, returned as the first route in the calculateRoute response, will start - at the origin point specified in the calculateRoute request. The initial part of the input - reference route up until the origin point will be excluded from the response. + at the origin point specified in the calculateRoute request. The initial part of the input + reference route up until the origin point will be excluded from the response. * The values of minDeviationDistance and minDeviationTime determine how far alternative routes - will be guaranteed to follow the reference route from the origin point onwards. + will be guaranteed to follow the reference route from the origin point onwards. * The route must use departAt. - * The vehicleHeading is ignored. Is either a model type or a IO type. Required. - :type route_direction_parameters: ~azure.maps.route.models.RouteDirectionParameters or IO + * The vehicleHeading is ignored. Is either a RouteDirectionParameters type or a IO[bytes] + type. Required. + + :type route_direction_parameters: ~azure.maps.route.models.RouteDirectionParameters or + IO[bytes] :param format: Desired format of the response. Value can be either *json* or *xml*. Known values are: "json" and "xml". Default value is "json". :type format: str or ~azure.maps.route.models.ResponseFormat @@ -4421,7 +4335,7 @@ def get_route_directions_with_additional_parameters( parameter was not specified by the caller. "effectiveSettings" Default value is None. :paramtype report: str or ~azure.maps.route.models.Report :keyword filter_section_type: Specifies which of the section types is reported in the route - response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + response. For example if sectionType = pedestrian the sections which are suited for pedestrians only are returned. Multiple types can be used. The default sectionType refers to the travelMode input. By default travelMode is set to car. Known values are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", @@ -4454,33 +4368,24 @@ def get_route_directions_with_additional_parameters( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. - - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. - * - It is mandatory if any of the *Efficiency parameters are set. - - * - It must be strictly positive when used in the context of the Consumption Model. Weight - restrictions are considered. - - * - If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is - non-zero, then weight restrictions are considered. - - * - In all other cases, this parameter is ignored. + * It is mandatory if any of the Efficiency parameters are set. + * It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. + * If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. + * In all other cases, this parameter is ignored. Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default value is 0. @@ -4489,11 +4394,11 @@ def get_route_directions_with_additional_parameters( vehicles may not be allowed to drive on some roads. Default value is False. :paramtype is_commercial_vehicle: bool :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword travel_mode: The mode of travel for the requested route. If not defined, default is @@ -4515,9 +4420,8 @@ def get_route_directions_with_additional_parameters( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", "eco", and "thrilling". Default value is None. @@ -4544,12 +4448,9 @@ def get_route_directions_with_additional_parameters( as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list - - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by - the nearest two points in the list + * by linear interpolation, if the given speed lies in between two speeds in the list + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of @@ -4597,7 +4498,7 @@ def get_route_directions_with_additional_parameters( Must be paired with **decelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **decelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default value is None. @@ -4609,7 +4510,7 @@ def get_route_directions_with_additional_parameters( Must be paired with **accelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **accelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default value is None. @@ -4621,7 +4522,7 @@ def get_route_directions_with_additional_parameters( Must be paired with **downhillEfficiency**. - The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **downhillEfficiency**. Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default value is None. @@ -4633,7 +4534,7 @@ def get_route_directions_with_additional_parameters( Must be paired with **uphillEfficiency**. - The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **uphillEfficiency**. Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default value is None. @@ -4645,12 +4546,9 @@ def get_route_directions_with_additional_parameters( consumption curve. Consumption rates for speeds not in the list are found as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list - - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by - the nearest two points in the list + * by linear interpolation, if the given speed lies in between two speeds in the list + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of @@ -4696,14 +4594,11 @@ def get_route_directions_with_additional_parameters( Sensible Values : 1.7. Default value is None. :paramtype auxiliary_power_in_kw: float - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str :return: RouteDirections :rtype: ~azure.maps.route.models.RouteDirections :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4714,18 +4609,18 @@ def get_route_directions_with_additional_parameters( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirections] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RouteDirections] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(route_direction_parameters, (IO, bytes)): + if isinstance(route_direction_parameters, (IOBase, bytes)): _content = route_direction_parameters else: _json = self._serialize.body(route_direction_parameters, "RouteDirectionParameters") - request = build_route_get_route_directions_with_additional_parameters_request( + _request = build_route_get_route_directions_with_additional_parameters_request( format=format, route_points=route_points, max_alternatives=max_alternatives, @@ -4777,10 +4672,11 @@ def get_route_directions_with_additional_parameters( headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -4790,12 +4686,12 @@ def get_route_directions_with_additional_parameters( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("RouteDirections", pipeline_response) + deserialized = self._deserialize("RouteDirections", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace def get_route_range( @@ -4839,7 +4735,7 @@ def get_route_range( ) -> _models.RouteRangeResult: """**Route Range (Isochrone) API** - **Applies to**\ : see pricing `tiers `_. + **Applies to**\\ : see pricing `tiers `_. This service will calculate a set of locations that can be reached from the origin point based on fuel, energy, time or distance budget that is specified. A polygon boundary (or Isochrone) @@ -4856,26 +4752,26 @@ def get_route_range( :keyword query: The Coordinate from which the range calculation should start. Required. :paramtype query: list[float] :keyword fuel_budget_in_liters: Fuel budget in liters that determines maximal range which can - be travelled using the specified Combustion Consumption Model.:code:`
` When + be travelled using the specified Combustion Consumption Model. When fuelBudgetInLiters is used, it is mandatory to specify a detailed Combustion Consumption - Model.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + Model. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype fuel_budget_in_liters: float :keyword energy_budget_in_kw_h: Electric energy budget in kilowatt hours (kWh) that determines maximal range which can be travelled using the specified Electric Consumption - Model.:code:`
` When energyBudgetInkWh is used, it is mandatory to specify a detailed - Electric Consumption Model.:code:`
` Exactly one budget (fuelBudgetInLiters, + Model. When energyBudgetInkWh is used, it is mandatory to specify a detailed + Electric Consumption Model. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype energy_budget_in_kw_h: float :keyword time_budget_in_sec: Time budget in seconds that determines maximal range which can be travelled using driving time. The Consumption Model will only affect the range when routeType - is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + is eco. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype time_budget_in_sec: float :keyword distance_budget_in_meters: Distance budget in meters that determines maximal range which can be travelled using driving distance. The Consumption Model will only affect the - range when routeType is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, + range when routeType is eco. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype distance_budget_in_meters: float @@ -4892,9 +4788,8 @@ def get_route_range( * true - Do consider all available traffic information during routing * false - Ignore current traffic data during routing. Note that although the current traffic - data is ignored - during routing, the effect of historic traffic on effective road speeds is still - incorporated. Default value is None. + data is ignored during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. :paramtype use_traffic_data: bool :keyword avoid: Specifies something that the route calculation should try to avoid when determining the route. Can be specified multiple times in one request, for example, @@ -4911,11 +4806,11 @@ def get_route_range( Default value is None. :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be - used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + used in conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel :keyword windingness: Level of turns for thrilling route. This parameter can only be used in - conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + conjunction with ``routeType``\\ =thrilling. Known values are: "low", "normal", and "high". Default value is None. :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that @@ -4934,33 +4829,27 @@ def get_route_range( vehicle profile is used to check whether a vehicle is allowed on motorways. - * - A value of 0 means that an appropriate value for the vehicle will be determined and applied - during route planning. + * A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. - * - A non-zero value may be overridden during route planning. For example, the current traffic - flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will - consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is - provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will - again use 60 km/hour. Default value is 0. + * A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. :paramtype vehicle_max_speed: int :keyword vehicle_weight: Weight of the vehicle in kilograms. - * - It is mandatory if any of the *Efficiency parameters are set. + * It is mandatory if any of the *Efficiency parameters are set. - * - It must be strictly positive when used in the context of the Consumption Model. Weight - restrictions are considered. + * It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. - * - If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is - non-zero, then weight restrictions are considered. + * If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. - * - In all other cases, this parameter is ignored. + * In all other cases, this parameter is ignored. Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default value is 0. @@ -4990,12 +4879,10 @@ def get_route_range( as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list + * by linear interpolation, if the given speed lies in between two speeds in the list - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by - the nearest two points in the list + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of @@ -5043,7 +4930,7 @@ def get_route_range( Must be paired with **decelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **decelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default value is None. @@ -5055,7 +4942,7 @@ def get_route_range( Must be paired with **accelerationEfficiency**. - The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + The range of values allowed are 0.0 to 1/\\ **accelerationEfficiency**. Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default value is None. @@ -5067,7 +4954,7 @@ def get_route_range( Must be paired with **downhillEfficiency**. - The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **downhillEfficiency**. Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default value is None. @@ -5079,7 +4966,7 @@ def get_route_range( Must be paired with **uphillEfficiency**. - The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + The range of values allowed are 0.0 to 1/\\ **uphillEfficiency**. Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default value is None. @@ -5091,11 +4978,9 @@ def get_route_range( consumption curve. Consumption rates for speeds not in the list are found as follows: - * - by linear interpolation, if the given speed lies in between two speeds in the list + * by linear interpolation, if the given speed lies in between two speeds in the list - * - by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + * by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by the nearest two points in the list The list must contain between 1 and 25 points (inclusive), and may not contain duplicate @@ -5146,7 +5031,7 @@ def get_route_range( :rtype: ~azure.maps.route.models.RouteRangeResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5157,9 +5042,9 @@ def get_route_range( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteRangeResult] + cls: ClsType[_models.RouteRangeResult] = kwargs.pop("cls", None) - request = build_route_get_route_range_request( + _request = build_route_get_route_range_request( format=format, query=query, fuel_budget_in_liters=fuel_budget_in_liters, @@ -5199,10 +5084,11 @@ def get_route_range( headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -5212,20 +5098,20 @@ def get_route_range( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("RouteRangeResult", pipeline_response) + deserialized = self._deserialize("RouteRangeResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore def _request_route_directions_batch_initial( self, - route_directions_batch_queries: Union[_models.BatchRequest, IO], + route_directions_batch_queries: Union[_models.BatchRequest, IO[bytes]], format: Union[str, _models.JsonFormat] = "json", **kwargs: Any - ) -> Optional[_models.RouteDirectionsBatchResult]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5236,18 +5122,18 @@ def _request_route_directions_batch_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteDirectionsBatchResult]] + 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(route_directions_batch_queries, (IO, bytes)): + if isinstance(route_directions_batch_queries, (IOBase, bytes)): _content = route_directions_batch_queries else: _json = self._serialize.body(route_directions_batch_queries, "BatchRequest") - request = build_route_request_route_directions_batch_request( + _request = build_route_request_route_directions_batch_request( format=format, client_id=self._config.client_id, content_type=content_type, @@ -5257,30 +5143,33 @@ def _request_route_directions_batch_initial( headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + deserialized = response.iter_bytes() + if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @overload def begin_request_route_directions_batch( @@ -5293,7 +5182,7 @@ def begin_request_route_directions_batch( ) -> LROPoller[_models.RouteDirectionsBatchResult]: """**Route Directions Batch API** - **Applies to**\ : see pricing `tiers `_. + **Applies to**\\ : see pricing `tiers `_. The Route Directions Batch API sends batches of queries to `Route Directions API `_ using just a single API @@ -5323,25 +5212,23 @@ def begin_request_route_directions_batch( #. Client sends a Route Directions Batch ``POST`` request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Batch request has been accepted. HTTP ``Error`` - There was an error processing your Batch request. This could either be a - ``400 Bad Request`` or any other ``Error`` status code. + ``400 Bad Request`` or any other ``Error`` status code. - #. - If the batch request was accepted successfully, the ``Location`` header in the response - contains the URL to download the results of the batch request. - This status URI looks like following: + #. If the batch request was accepted successfully, the ``Location`` header in the response + contains the URL to download the results of the batch request. + This status URI looks like following: - ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` - Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security - <#security>`_\ ) to the *status URI* before running it. :code:`
` + ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` + Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security + <#security>`_\\ ) to the *status URI* before running it. #. Client issues a ``GET`` request on the *download URL* obtained in Step 3 to download the @@ -5360,10 +5247,10 @@ def begin_request_route_directions_batch( { "batchItems": [ { "query": - "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" - }, + "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + }, { "query": - "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, + "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, { "query": "?query=48.923159,-122.557362:32.621279,-116.840362" } ] } @@ -5393,16 +5280,15 @@ def begin_request_route_directions_batch( #. Client sends a ``GET`` request using the *download URL*. - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please - try again in some time. + try again in some time. HTTP ``200 OK`` - Batch request successfully processed. The response body contains all - the batch results. + the batch results. Batch Response Model @@ -5411,22 +5297,20 @@ def begin_request_route_directions_batch( The returned data content is similar for async and sync requests. When downloading the results of an async batch request, if the batch has finished processing, the response body contains the batch response. This batch response contains a ``summary`` component that indicates the - ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. - queries which were executed successfully. The batch response also includes a ``batchItems`` - array which contains a response for each and every query in the batch request. The - ``batchItems`` will contain the results in the exact same order the original queries were sent - in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\\ + i.e. queries which were executed successfully. The batch response also includes a + ``batchItems`` array which contains a response for each and every query in the batch request. + The ``batchItems`` will contain the results in the exact same order the original queries were + sent in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` fields. Each ``response`` in ``batchItems`` is of one of the following types: - * - `\ ``RouteDirections`` - `_ - If the - query completed successfully. + * `\\ ``RouteDirections`` + `_ - If the + query completed successfully. - * - ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in - this case. + * ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. Here's a sample Batch Response with 1 *successful* and 1 *failed* result: @@ -5494,13 +5378,13 @@ def begin_request_route_directions_batch( "error": { "code": "400 BadRequest", - "message": "Bad request: one or more parameters were incorrectly - specified or are mutually exclusive." + "message": + "Bad request: one or more parameters were incorrectly specified or are mutually exclusive." } } } ] - }. + } :param route_directions_batch_queries: The list of route directions queries/requests to process. The list can contain a max of 700 queries for async and 100 queries for sync version @@ -5512,13 +5396,6 @@ def begin_request_route_directions_batch( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. 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 RouteDirectionsBatchResult :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -5527,7 +5404,7 @@ def begin_request_route_directions_batch( @overload def begin_request_route_directions_batch( self, - route_directions_batch_queries: IO, + route_directions_batch_queries: IO[bytes], format: Union[str, _models.JsonFormat] = "json", *, content_type: str = "application/json", @@ -5535,7 +5412,7 @@ def begin_request_route_directions_batch( ) -> LROPoller[_models.RouteDirectionsBatchResult]: """**Route Directions Batch API** - **Applies to**\ : see pricing `tiers `_. + **Applies to**\\ : see pricing `tiers `_. The Route Directions Batch API sends batches of queries to `Route Directions API `_ using just a single API @@ -5565,25 +5442,23 @@ def begin_request_route_directions_batch( #. Client sends a Route Directions Batch ``POST`` request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Batch request has been accepted. HTTP ``Error`` - There was an error processing your Batch request. This could either be a - ``400 Bad Request`` or any other ``Error`` status code. + ``400 Bad Request`` or any other ``Error`` status code. - #. - If the batch request was accepted successfully, the ``Location`` header in the response - contains the URL to download the results of the batch request. - This status URI looks like following: + #. If the batch request was accepted successfully, the ``Location`` header in the response + contains the URL to download the results of the batch request. + This status URI looks like following: - ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` - Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security - <#security>`_\ ) to the *status URI* before running it. :code:`
` + ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` + Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security + <#security>`_\\ ) to the *status URI* before running it. #. Client issues a ``GET`` request on the *download URL* obtained in Step 3 to download the @@ -5602,10 +5477,10 @@ def begin_request_route_directions_batch( { "batchItems": [ { "query": - "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" - }, + "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + }, { "query": - "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, + "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, { "query": "?query=48.923159,-122.557362:32.621279,-116.840362" } ] } @@ -5635,16 +5510,15 @@ def begin_request_route_directions_batch( #. Client sends a ``GET`` request using the *download URL*. - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please - try again in some time. + try again in some time. HTTP ``200 OK`` - Batch request successfully processed. The response body contains all - the batch results. + the batch results. Batch Response Model @@ -5653,22 +5527,20 @@ def begin_request_route_directions_batch( The returned data content is similar for async and sync requests. When downloading the results of an async batch request, if the batch has finished processing, the response body contains the batch response. This batch response contains a ``summary`` component that indicates the - ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. - queries which were executed successfully. The batch response also includes a ``batchItems`` - array which contains a response for each and every query in the batch request. The - ``batchItems`` will contain the results in the exact same order the original queries were sent - in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\\ + i.e. queries which were executed successfully. The batch response also includes a + ``batchItems`` array which contains a response for each and every query in the batch request. + The ``batchItems`` will contain the results in the exact same order the original queries were + sent in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` fields. Each ``response`` in ``batchItems`` is of one of the following types: - * - `\ ``RouteDirections`` - `_ - If the - query completed successfully. + * `\\ ``RouteDirections`` + `_ - If the + query completed successfully. - * - ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in - this case. + * ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. Here's a sample Batch Response with 1 *successful* and 1 *failed* result: @@ -5736,31 +5608,24 @@ def begin_request_route_directions_batch( "error": { "code": "400 BadRequest", - "message": "Bad request: one or more parameters were incorrectly - specified or are mutually exclusive." + "message": + "Bad request: one or more parameters were incorrectly specified or are mutually exclusive." } } } ] - }. + } :param route_directions_batch_queries: The list of route directions queries/requests to process. The list can contain a max of 700 queries for async and 100 queries for sync version and must contain at least 1 query. Required. - :type route_directions_batch_queries: IO + :type route_directions_batch_queries: IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. 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 RouteDirectionsBatchResult :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -5769,13 +5634,13 @@ def begin_request_route_directions_batch( @distributed_trace def begin_request_route_directions_batch( self, - route_directions_batch_queries: Union[_models.BatchRequest, IO], + route_directions_batch_queries: Union[_models.BatchRequest, IO[bytes]], format: Union[str, _models.JsonFormat] = "json", **kwargs: Any ) -> LROPoller[_models.RouteDirectionsBatchResult]: """**Route Directions Batch API** - **Applies to**\ : see pricing `tiers `_. + **Applies to**\\ : see pricing `tiers `_. The Route Directions Batch API sends batches of queries to `Route Directions API `_ using just a single API @@ -5805,29 +5670,27 @@ def begin_request_route_directions_batch( #. Client sends a Route Directions Batch ``POST`` request to Azure Maps - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Batch request has been accepted. HTTP ``Error`` - There was an error processing your Batch request. This could either be a - ``400 Bad Request`` or any other ``Error`` status code. + ``400 Bad Request`` or any other ``Error`` status code. - #. - If the batch request was accepted successfully, the ``Location`` header in the response - contains the URL to download the results of the batch request. - This status URI looks like following: + #. If the batch request was accepted successfully, the ``Location`` header in the response + contains the URL to download the results of the batch request. + This status URI looks like following: - ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` - Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security - <#security>`_\ ) to the *status URI* before running it. :code:`
` + ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` + Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security + <#security>`_\\ ) to the *status URI* before running it. #. Client issues a ``GET`` request on the *download URL* obtained in Step 3 to download the - batch results. + batch results. POST Body for Batch Request ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -5842,10 +5705,10 @@ def begin_request_route_directions_batch( { "batchItems": [ { "query": - "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" - }, + "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + }, { "query": - "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, + "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, { "query": "?query=48.923159,-122.557362:32.621279,-116.840362" } ] } @@ -5875,16 +5738,15 @@ def begin_request_route_directions_batch( #. Client sends a ``GET`` request using the *download URL*. - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please - try again in some time. + try again in some time. HTTP ``200 OK`` - Batch request successfully processed. The response body contains all - the batch results. + the batch results. Batch Response Model @@ -5893,22 +5755,20 @@ def begin_request_route_directions_batch( The returned data content is similar for async and sync requests. When downloading the results of an async batch request, if the batch has finished processing, the response body contains the batch response. This batch response contains a ``summary`` component that indicates the - ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. - queries which were executed successfully. The batch response also includes a ``batchItems`` - array which contains a response for each and every query in the batch request. The - ``batchItems`` will contain the results in the exact same order the original queries were sent - in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\\ + i.e. queries which were executed successfully. The batch response also includes a + ``batchItems`` array which contains a response for each and every query in the batch request. + The ``batchItems`` will contain the results in the exact same order the original queries were + sent in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` fields. Each ``response`` in ``batchItems`` is of one of the following types: - * - `\ ``RouteDirections`` - `_ - If the - query completed successfully. + * `\\ ``RouteDirections`` + `_ - If the + query completed successfully. - * - ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in - this case. + * ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. Here's a sample Batch Response with 1 *successful* and 1 *failed* result: @@ -5976,31 +5836,21 @@ def begin_request_route_directions_batch( "error": { "code": "400 BadRequest", - "message": "Bad request: one or more parameters were incorrectly - specified or are mutually exclusive." + "message": + "Bad request: one or more parameters were incorrectly specified or are mutually exclusive." } } } ] - }. + } :param route_directions_batch_queries: The list of route directions queries/requests to process. The list can contain a max of 700 queries for async and 100 queries for sync version - and must contain at least 1 query. Is either a model type or a IO type. Required. - :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest or IO + and must contain at least 1 query. Is either a BatchRequest type or a IO[bytes] type. Required. + :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest or IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. 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 RouteDirectionsBatchResult :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -6008,13 +5858,13 @@ def begin_request_route_directions_batch( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirectionsBatchResult] - polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RouteDirectionsBatchResult] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._request_route_directions_batch_initial( # type: ignore + raw_result = self._request_route_directions_batch_initial( route_directions_batch_queries=route_directions_batch_queries, format=format, content_type=content_type, @@ -6023,35 +5873,36 @@ def begin_request_route_directions_batch( 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("RouteDirectionsBatchResult", pipeline_response) + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: - polling_method = cast( + polling_method: PollingMethod = cast( PollingMethod, LROBasePolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) # type: PollingMethod + ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.RouteDirectionsBatchResult].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) + return LROPoller[_models.RouteDirectionsBatchResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - def _get_route_directions_batch_initial( - self, batch_id: str, **kwargs: Any - ) -> Optional[_models.RouteDirectionsBatchResult]: - error_map = { + def _get_route_directions_batch_initial(self, batch_id: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -6062,45 +5913,48 @@ def _get_route_directions_batch_initial( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteDirectionsBatchResult]] + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_route_get_route_directions_batch_request( + _request = build_route_get_route_directions_batch_request( batch_id=batch_id, client_id=self._config.client_id, api_version=self._config.api_version, headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) - if response.status_code == 202: response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + deserialized = response.iter_bytes() + if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace def begin_get_route_directions_batch( self, batch_id: str, **kwargs: Any ) -> LROPoller[_models.RouteDirectionsBatchResult]: - """**Applies to**\ : see pricing `tiers `_. + """**Applies to**\\ : see pricing `tiers `_. Download Asynchronous Batch Results ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -6117,16 +5971,15 @@ def begin_get_route_directions_batch( #. Client sends a ``GET`` request using the *download URL*. - #. - The server will respond with one of the following: + #. The server will respond with one of the following: .. HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please - try again in some time. + try again in some time. HTTP ``200 OK`` - Batch request successfully processed. The response body contains all - the batch results. + the batch results. Batch Response Model @@ -6135,22 +5988,20 @@ def begin_get_route_directions_batch( The returned data content is similar for async and sync requests. When downloading the results of an async batch request, if the batch has finished processing, the response body contains the batch response. This batch response contains a ``summary`` component that indicates the - ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. - queries which were executed successfully. The batch response also includes a ``batchItems`` - array which contains a response for each and every query in the batch request. The - ``batchItems`` will contain the results in the exact same order the original queries were sent - in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\\ + i.e. queries which were executed successfully. The batch response also includes a + ``batchItems`` array which contains a response for each and every query in the batch request. + The ``batchItems`` will contain the results in the exact same order the original queries were + sent in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` fields. Each ``response`` in ``batchItems`` is of one of the following types: - * - `\ ``RouteDirections`` - `_ - If the - query completed successfully. + * `\\ ``RouteDirections`` + `_ - If the + query completed successfully. - * - ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in - this case. + * ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. Here's a sample Batch Response with 1 *successful* and 1 *failed* result: @@ -6218,23 +6069,16 @@ def begin_get_route_directions_batch( "error": { "code": "400 BadRequest", - "message": "Bad request: one or more parameters were incorrectly - specified or are mutually exclusive." + "message": + "Bad request: one or more parameters were incorrectly specified or are mutually exclusive." } } } ] - }. + } :param batch_id: Batch id for querying the operation. Required. :type batch_id: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. 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 RouteDirectionsBatchResult :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] :raises ~azure.core.exceptions.HttpResponseError: @@ -6242,38 +6086,41 @@ def begin_get_route_directions_batch( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirectionsBatchResult] - polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + cls: ClsType[_models.RouteDirectionsBatchResult] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._get_route_directions_batch_initial( # type: ignore + raw_result = self._get_route_directions_batch_initial( batch_id=batch_id, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) + raw_result.http_response.read() # type: ignore kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: - polling_method = cast( + polling_method: PollingMethod = cast( PollingMethod, LROBasePolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs) - ) # type: PollingMethod + ) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.RouteDirectionsBatchResult].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) + return LROPoller[_models.RouteDirectionsBatchResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @overload def request_route_directions_batch_sync( @@ -6286,7 +6133,7 @@ def request_route_directions_batch_sync( ) -> _models.RouteDirectionsBatchResult: """**Route Directions Batch API** - **Applies to**\ : see pricing `tiers `_. + **Applies to**\\ : see pricing `tiers `_. The Route Directions Batch API sends batches of queries to `Route Directions API `_ using just a single API @@ -6306,7 +6153,7 @@ def request_route_directions_batch_sync( .. code-block:: POST - https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} + https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} Batch Response Model ^^^^^^^^^^^^^^^^^^^^ @@ -6314,22 +6161,20 @@ def request_route_directions_batch_sync( The returned data content is similar for async and sync requests. When downloading the results of an async batch request, if the batch has finished processing, the response body contains the batch response. This batch response contains a ``summary`` component that indicates the - ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. - queries which were executed successfully. The batch response also includes a ``batchItems`` - array which contains a response for each and every query in the batch request. The - ``batchItems`` will contain the results in the exact same order the original queries were sent - in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\\ + i.e. queries which were executed successfully. The batch response also includes a + ``batchItems`` array which contains a response for each and every query in the batch request. + The ``batchItems`` will contain the results in the exact same order the original queries were + sent in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` fields. Each ``response`` in ``batchItems`` is of one of the following types: - * - `\ ``RouteDirections`` - `_ - If the - query completed successfully. + * `\\ ``RouteDirections`` + `_ - If the + query completed successfully. - * - ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in - this case. + * ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. Here's a sample Batch Response with 1 *successful* and 1 *failed* result: @@ -6397,13 +6242,13 @@ def request_route_directions_batch_sync( "error": { "code": "400 BadRequest", - "message": "Bad request: one or more parameters were incorrectly - specified or are mutually exclusive." + "message": + "Bad request: one or more parameters were incorrectly specified or are mutually exclusive." } } } ] - }. + } :param route_directions_batch_queries: The list of route directions queries/requests to process. The list can contain a max of 700 queries for async and 100 queries for sync version @@ -6423,7 +6268,7 @@ def request_route_directions_batch_sync( @overload def request_route_directions_batch_sync( self, - route_directions_batch_queries: IO, + route_directions_batch_queries: IO[bytes], format: Union[str, _models.JsonFormat] = "json", *, content_type: str = "application/json", @@ -6431,7 +6276,7 @@ def request_route_directions_batch_sync( ) -> _models.RouteDirectionsBatchResult: """**Route Directions Batch API** - **Applies to**\ : see pricing `tiers `_. + **Applies to**\\ : see pricing `tiers `_. The Route Directions Batch API sends batches of queries to `Route Directions API `_ using just a single API @@ -6451,7 +6296,7 @@ def request_route_directions_batch_sync( .. code-block:: POST - https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} + https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} Batch Response Model ^^^^^^^^^^^^^^^^^^^^ @@ -6459,22 +6304,20 @@ def request_route_directions_batch_sync( The returned data content is similar for async and sync requests. When downloading the results of an async batch request, if the batch has finished processing, the response body contains the batch response. This batch response contains a ``summary`` component that indicates the - ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. - queries which were executed successfully. The batch response also includes a ``batchItems`` - array which contains a response for each and every query in the batch request. The - ``batchItems`` will contain the results in the exact same order the original queries were sent - in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\\ + i.e. queries which were executed successfully. The batch response also includes a + ``batchItems`` array which contains a response for each and every query in the batch request. + The ``batchItems`` will contain the results in the exact same order the original queries were + sent in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` fields. Each ``response`` in ``batchItems`` is of one of the following types: - * - `\ ``RouteDirections`` - `_ - If the - query completed successfully. + * `\\ ``RouteDirections`` + `_ - If the + query completed successfully. - * - ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in - this case. + * ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. Here's a sample Batch Response with 1 *successful* and 1 *failed* result: @@ -6542,18 +6385,18 @@ def request_route_directions_batch_sync( "error": { "code": "400 BadRequest", - "message": "Bad request: one or more parameters were incorrectly - specified or are mutually exclusive." + "message": + "Bad request: one or more parameters were incorrectly specified or are mutually exclusive." } } } ] - }. + } :param route_directions_batch_queries: The list of route directions queries/requests to process. The list can contain a max of 700 queries for async and 100 queries for sync version and must contain at least 1 query. Required. - :type route_directions_batch_queries: IO + :type route_directions_batch_queries: IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat @@ -6568,13 +6411,13 @@ def request_route_directions_batch_sync( @distributed_trace def request_route_directions_batch_sync( self, - route_directions_batch_queries: Union[_models.BatchRequest, IO], + route_directions_batch_queries: Union[_models.BatchRequest, IO[bytes]], format: Union[str, _models.JsonFormat] = "json", **kwargs: Any ) -> _models.RouteDirectionsBatchResult: """**Route Directions Batch API** - **Applies to**\ : see pricing `tiers `_. + **Applies to**\\ : see pricing `tiers `_. The Route Directions Batch API sends batches of queries to `Route Directions API `_ using just a single API @@ -6594,7 +6437,7 @@ def request_route_directions_batch_sync( .. code-block:: POST - https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} + https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} Batch Response Model ^^^^^^^^^^^^^^^^^^^^ @@ -6602,22 +6445,20 @@ def request_route_directions_batch_sync( The returned data content is similar for async and sync requests. When downloading the results of an async batch request, if the batch has finished processing, the response body contains the batch response. This batch response contains a ``summary`` component that indicates the - ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. - queries which were executed successfully. The batch response also includes a ``batchItems`` - array which contains a response for each and every query in the batch request. The - ``batchItems`` will contain the results in the exact same order the original queries were sent - in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\\ + i.e. queries which were executed successfully. The batch response also includes a + ``batchItems`` array which contains a response for each and every query in the batch request. + The ``batchItems`` will contain the results in the exact same order the original queries were + sent in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` fields. Each ``response`` in ``batchItems`` is of one of the following types: - * - `\ ``RouteDirections`` - `_ - If the - query completed successfully. + * `\\ ``RouteDirections`` + `_ - If the + query completed successfully. - * - ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in - this case. + * ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. Here's a sample Batch Response with 1 *successful* and 1 *failed* result: @@ -6685,35 +6526,35 @@ def request_route_directions_batch_sync( "error": { "code": "400 BadRequest", - "message": "Bad request: one or more parameters were incorrectly - specified or are mutually exclusive." + "message": + "Bad request: one or more parameters were incorrectly specified or are mutually exclusive." } } } ] - }. + } :param route_directions_batch_queries: The list of route directions queries/requests to process. The list can contain a max of 700 queries for async and 100 queries for sync version - and must contain at least 1 query. Is either a model type or a IO type. Required. - :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest or IO + and must contain at least 1 query. Is either a BatchRequest type or a IO[bytes] type. Required. + :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest or IO[bytes] :param format: Desired format of the response. Only ``json`` format is supported. "json" Default value is "json". :type format: str or ~azure.maps.route.models.JsonFormat - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str :return: RouteDirectionsBatchResult :rtype: ~azure.maps.route.models.RouteDirectionsBatchResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, - 408: lambda response: HttpResponseError( - response=response, model=self._deserialize(_models.ErrorResponse, response) + 408: cast( + Type[HttpResponseError], + lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.ErrorResponse, response) + ), ), } error_map.update(kwargs.pop("error_map", {}) or {}) @@ -6721,18 +6562,18 @@ def request_route_directions_batch_sync( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirectionsBatchResult] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RouteDirectionsBatchResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(route_directions_batch_queries, (IO, bytes)): + if isinstance(route_directions_batch_queries, (IOBase, bytes)): _content = route_directions_batch_queries else: _json = self._serialize.body(route_directions_batch_queries, "BatchRequest") - request = build_route_request_route_directions_batch_sync_request( + _request = build_route_request_route_directions_batch_sync_request( format=format, client_id=self._config.client_id, content_type=content_type, @@ -6742,10 +6583,11 @@ def request_route_directions_batch_sync( headers=_headers, params=_params, ) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -6755,9 +6597,9 @@ def request_route_directions_batch_sync( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) - deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_route_client.py b/sdk/maps/azure-maps-route/azure/maps/route/operations/_patch.py similarity index 88% rename from sdk/maps/azure-maps-route/azure/maps/route/_route_client.py rename to sdk/maps/azure-maps-route/azure/maps/route/operations/_patch.py index dc2a5c1b947a..8d62a03c8458 100644 --- a/sdk/maps/azure-maps-route/azure/maps/route/_route_client.py +++ b/sdk/maps/azure-maps-route/azure/maps/route/operations/_patch.py @@ -1,83 +1,62 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -# pylint: disable=unused-import,ungrouped-imports, R0904, C0302, W0212 -from typing import Union, Any, List, Tuple, overload +#pylint: disable=W0212, W0221, W0237, C4758 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List, Union, Any, Tuple + from azure.core.tracing.decorator import distributed_trace -from azure.core.credentials import AzureKeyCredential, TokenCredential from azure.core.polling import LROPoller -from ._base_client import MapsRouteClientBase -from .models import ( - RouteDirectionsBatchResult, + +from ..models import ( + ResponseFormat, + LatLongPair, RouteDirections, RouteRangeResult, - RouteMatrixResult, + RouteDirectionsBatchResult, RouteMatrixQuery, - LatLon, - TravelMode + RouteMatrixResult, + BatchRequest, + BatchRequestItem, + RouteDirectionParameters ) +from ._operations import RouteOperations as RouteOperationsGenerated -from ._generated.models import ( - ResponseFormat -) +__all__: List[str] = ["RouteOperations"] # Add all objects you want publicly available to users at this package level -def get_batch_id_from_poller(polling_method): - if hasattr(polling_method, "_operation"): - operation=polling_method._operation - return operation._location_url.split('/')[-1].split('?')[0] - return None - -# By default, use the latest supported API version -class MapsRouteClient(MapsRouteClientBase): - """Azure Maps Route REST APIs. - - :param credential: - Credential needed for the client to connect to Azure. - :type credential: - ~azure.core.credentials.TokenCredential or ~azure.core.credentials.AzureKeyCredential - :keyword str base_url: - Supported Maps Services or Language resource base_url - (protocol and hostname, for example: 'https://us.atlas.microsoft.com'). - :keyword str client_id: - Specifies which account is intended for usage with the Azure AD security model. - It represents a unique ID for the Azure Maps account. - :keyword api_version: - The API version of the service to use for requests. It defaults to the latest service version. - Setting to an older version may result in reduced feature compatibility. - :paramtype api_version: str - """ - def __init__( - self, - credential: Union[AzureKeyCredential, TokenCredential], - **kwargs: Any - )-> None: +def patch_sdk(): + """Do not remove from this file. - super().__init__( - credential=credential, **kwargs - ) + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ +class RouteOperations(RouteOperationsGenerated): # cSpell:disable @distributed_trace - def get_route_directions( + def get_route_directions( # type: ignore self, - route_points: Union[List[LatLon], List[Tuple]], + route_points: Union[List[LatLongPair], List[Tuple]], **kwargs: Any ) -> RouteDirections: - """ - Returns a route between an origin and a destination, passing through waypoints if they are - specified. The route will take into account factors such as current traffic and the typical - road speeds on the requested day of the week and time of day. + """Returns a route between an origin and a destination, passing through + waypoints if they are specified. The route will take into account + factors such as current traffic and the typical road speeds on the + requested day of the week and time of day. Information returned includes the distance, estimated travel time, and a representation of the route geometry. Additional routing information such as optimized waypoint order or turn by turn instructions is also available, depending on the options selected. :param route_points: The Coordinate from which the range calculation should start, coordinates as (lat, lon) - :type route_points: List[LatLon] or List[Tuple] + :type route_points: List[LatLongPair] or List[Tuple] :keyword supporting_points: A GeoJSON Geometry collection representing sequence of coordinates used as input for route reconstruction and for calculating zero or more alternative routes to this reference route. @@ -282,30 +261,37 @@ def get_route_directions( :rtype: ~azure.maps.route.models.RouteDirections :raises ~azure.core.exceptions.HttpResponseError: """ - query_items="" - route_directions_body={} + query_items = "" + route_directions_body = {} + if route_points: - query_items = ":".join([(str(route_point[0])+","+str(route_point[1])) for route_point in route_points]) + coordinates = [] + for route_point in route_points: + if isinstance(route_point, LatLongPair): + coordinates.append(f"{route_point.latitude},{route_point.longitude}") + elif isinstance(route_point, tuple): + coordinates.append(f"{route_point[0]},{route_point[1]}") + query_items = ":".join(coordinates) supporting_points = kwargs.pop('supporting_points', None) avoid_vignette = kwargs.pop('avoid_vignette', None) allow_vignette = kwargs.pop('allow_vignette', None) avoid_areas = kwargs.pop('avoid_areas', None) - if supporting_points or avoid_vignette or allow_vignette or avoid_areas is not None: - route_directions_body['supporting_points'] = supporting_points - route_directions_body['avoid_vignette'] = avoid_vignette - route_directions_body['allow_vignette'] = allow_vignette - route_directions_body['avoid_areas'] = avoid_areas - - if route_directions_body: - # import pdb; pdb.set_trace() - return self._route_client.get_route_directions_with_additional_parameters( + + if supporting_points or avoid_vignette or allow_vignette or avoid_areas: + route_directions_body = RouteDirectionParameters( + supporting_points=supporting_points, + avoid_vignette=avoid_vignette, + allow_vignette=allow_vignette, + avoid_areas=avoid_areas + ) + return super().get_route_directions_with_additional_parameters( format=ResponseFormat.JSON, route_direction_parameters=route_directions_body, route_points=query_items, **kwargs ) - return self._route_client.get_route_directions( + return super().get_route_directions( format=ResponseFormat.JSON, route_points=query_items, **kwargs @@ -313,9 +299,9 @@ def get_route_directions( # cSpell:disable @distributed_trace - def get_route_range( + def get_route_range( # type: ignore self, - coordinates: Union[LatLon, Tuple], + coordinates: Union[LatLongPair, Tuple], **kwargs: Any ) -> RouteRangeResult: @@ -327,28 +313,28 @@ def get_route_range( the result of the origin point. :param coordinates: The Coordinate from which the range calculation should start, coordinates as (lat, lon) - :type coordinates: LatLon or Tuple + :type coordinates: LatLongPair or Tuple :keyword fuel_budget_in_liters: Fuel budget in liters that determines maximal range which can - be travelled using the specified Combustion Consumption Model.:code:`
` When + be travelled using the specified Combustion Consumption Model. When fuelBudgetInLiters is used, it is mandatory to specify a detailed Combustion Consumption - Model.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + Model. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype fuel_budget_in_liters: float :keyword energy_budget_in_kw_h: Electric energy budget in kilowatt hours (kWh) that determines maximal range which can be travelled using the specified Electric Consumption - Model.:code:`
` When energyBudgetInkWh is used, it is mandatory to specify a detailed - Electric Consumption Model.:code:`
` Exactly one budget (fuelBudgetInLiters, + Model. When energyBudgetInkWh is used, it is mandatory to specify a detailed + Electric Consumption Model. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype energy_budget_in_kw_h: float :keyword time_budget_in_sec: Time budget in seconds that determines maximal range which can be travelled using driving time. The Consumption Model will only affect the range when routeType - is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + is eco. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype time_budget_in_sec: float :keyword distance_budget_in_meters: Distance budget in meters that determines maximal range which can be travelled using driving distance. The Consumption Model will only affect the - range when routeType is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, + range when routeType is eco. Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is None. :paramtype distance_budget_in_meters: float @@ -473,15 +459,18 @@ def get_route_range( :rtype: ~azure.maps.route.models.RouteRangeResult :raises ~azure.core.exceptions.HttpResponseError: """ - query = [coordinates[0], coordinates[1]] + query = [] + if isinstance(coordinates, Tuple): + query = [coordinates[0], coordinates[1]] + elif isinstance(coordinates, LatLongPair) and coordinates.latitude and coordinates.longitude: + query = [coordinates.latitude, coordinates.longitude] - return self._route_client.get_route_range( + return super().get_route_range( format=ResponseFormat.JSON, query=query, **kwargs ) - @distributed_trace def get_route_directions_batch_sync( self, @@ -489,50 +478,34 @@ def get_route_directions_batch_sync( **kwargs: Any ) -> RouteDirectionsBatchResult: - """Sends batches of route directions requests. - The method return the result directly. + """Sends batches of route directions requests. The method return the + result directly. :param queries: The list of route directions queries/requests to - process. The list can contain a max of 700 queries for async and 100 queries for sync version - and must contain at least 1 query. Required. + process. The list can contain a max of 700 queries for + async and 100 queries for sync version and must contain at + least 1 query. Required. :type queries: List[str] :return: RouteDirectionsBatchResult - :rtype: RouteDirectionsBatchResult - :raises ~azure.core.exceptions.HttpResponseError: + :rtype: RouteDirectionsBatchResult :raises + ~azure.core.exceptions.HttpResponseError: """ - batch_items = [{"query": f"?query={query}"} for query - in queries] if queries else [] - result = self._route_client.request_route_directions_batch_sync( + return super().request_route_directions_batch_sync( format=ResponseFormat.JSON, - route_directions_batch_queries={"batch_items": batch_items}, + route_directions_batch_queries=BatchRequest( + batch_items=[BatchRequestItem(query=f"?query={query}") for query in queries] if queries else [] + ), **kwargs ) - return RouteDirectionsBatchResult(summary=result.batch_summary, items=result.batch_items) - - @overload - def begin_get_route_directions_batch( - self, - batch_id: str, - **kwargs: Any - ) -> LROPoller[RouteDirectionsBatchResult]: - pass - - @overload - def begin_get_route_directions_batch( - self, - queries: List[str], - **kwargs: Any - ) -> LROPoller[RouteDirectionsBatchResult]: - pass @distributed_trace - def begin_get_route_directions_batch( + def begin_get_route_directions_batch( # type: ignore self, **kwargs: Any ) -> LROPoller[RouteDirectionsBatchResult]: - """Sends batches of route direction queries. - The method returns a poller for retrieving the result later. + """Sends batches of route direction queries. The method returns a + poller for retrieving the result later. :keyword queries: The list of route directions queries/requests to process. The list can contain a max of 700 queries for async and 100 queries for sync version @@ -555,21 +528,21 @@ def begin_get_route_directions_batch( batch_id=kwargs.pop('batch_id', None) if batch_id: - poller = self._route_client.begin_get_route_directions_batch( + poller = super().begin_get_route_directions_batch( format=ResponseFormat.JSON, batch_id=batch_id, **kwargs ) return poller - batch_items = [{"query": f"?query={query}"} for query - in queries] if queries else [] - batch_poller = self._route_client.begin_request_route_directions_batch( + batch_poller = super().begin_request_route_directions_batch( format=ResponseFormat.JSON, - route_directions_batch_queries={"batch_items": batch_items}, + route_directions_batch_queries=BatchRequest( + batch_items=[BatchRequestItem(query=f"?query={query}") for query in queries] if queries else [] + ), **kwargs ) - batch_poller.batch_id = get_batch_id_from_poller(batch_poller.polling_method()) + return batch_poller @distributed_trace @@ -579,9 +552,9 @@ def get_route_matrix( **kwargs: Any ) -> RouteMatrixResult: - """ - Calculates a matrix of route summaries for a set of routes defined by origin and destination locations. - The method return the result directly. + """Calculates a matrix of route summaries for a set of routes defined + by origin and destination locations. The method return the result + directly. The maximum size of a matrix for this method is 100 (the number of origins multiplied by the number of destinations) @@ -683,37 +656,21 @@ def get_route_matrix( :rtype: ~azure.maps.route.models.RouteMatrixResult :raises ~azure.core.exceptions.HttpResponseError: """ - return self._route_client.request_route_matrix_sync( + return super().request_route_matrix_sync( format=ResponseFormat.JSON, route_matrix_query=query, **kwargs ) - @overload - def begin_get_route_matrix_batch( - self, - query: RouteMatrixQuery, - **kwargs: Any - ) -> LROPoller[RouteMatrixResult]: - pass - - @overload - def begin_get_route_matrix_batch( - self, - matrix_id: str, - **kwargs: Any - ) -> LROPoller[RouteMatrixResult]: - pass - @distributed_trace def begin_get_route_matrix_batch( self, **kwargs: Any ) -> LROPoller[RouteMatrixResult]: - """ - Calculates a matrix of route summaries for a set of routes defined by origin and destination locations. - The method returns a poller for retrieving the result later. + """Calculates a matrix of route summaries for a set of routes defined + by origin and destination locations. The method returns a poller for + retrieving the result later. The maximum size of a matrix for this method is 700 (the number of origins multiplied by the number of destinations) @@ -724,6 +681,7 @@ def begin_get_route_matrix_batch( **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 origins and 25 destinations for async API. Required. :paramtype query: ~azure.maps.route.models.RouteMatrixQuery + :keyword matrix_id: Matrix id received after the Matrix Route request was accepted successfully. Required. :paramtype matrix_id: str @@ -829,12 +787,12 @@ def begin_get_route_matrix_batch( matrix_id = kwargs.pop('matrix_id', None) if matrix_id: - return self._route_client.begin_get_route_matrix( + return super().begin_get_route_matrix( matrix_id=matrix_id, **kwargs ) - poller = self._route_client.begin_request_route_matrix( + poller = super().begin_request_route_matrix( format=ResponseFormat.JSON, route_matrix_query=query, **kwargs diff --git a/sdk/maps/azure-maps-route/samples/async_samples/sample_authentication_async.py b/sdk/maps/azure-maps-route/samples/async_samples/sample_authentication_async.py index a301f83df817..8cb9d2215bfd 100644 --- a/sdk/maps/azure-maps-route/samples/async_samples/sample_authentication_async.py +++ b/sdk/maps/azure-maps-route/samples/async_samples/sample_authentication_async.py @@ -31,7 +31,7 @@ async def authentication_maps_service_client_with_subscription_key_credential_as from azure.core.credentials import AzureKeyCredential from azure.maps.route.aio import MapsRouteClient - subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") + subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key") maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) # [END create_maps_route_service_client_with_key_async] @@ -51,7 +51,7 @@ async def authentication_maps_service_client_with_aad_credential_async(): from azure.maps.route.aio import MapsRouteClient credential = DefaultAzureCredential() - maps_client_id = os.getenv("AZURE_MAPS_CLIENT_ID") + maps_client_id = os.getenv("AZURE_MAPS_CLIENT_ID", "your maps client id") maps_route_client = MapsRouteClient(client_id=maps_client_id, credential=credential) # [END create_maps_route_service_client_with_aad_async] diff --git a/sdk/maps/azure-maps-route/samples/async_samples/sample_begin_get_route_directions_batch_async.py b/sdk/maps/azure-maps-route/samples/async_samples/sample_begin_get_route_directions_batch_async.py index 18dac1530f85..7b3976b7bb65 100644 --- a/sdk/maps/azure-maps-route/samples/async_samples/sample_begin_get_route_directions_batch_async.py +++ b/sdk/maps/azure-maps-route/samples/async_samples/sample_begin_get_route_directions_batch_async.py @@ -19,7 +19,7 @@ import asyncio import os -subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key") async def begin_get_route_directions_batch_async(): from azure.core.credentials import AzureKeyCredential @@ -34,8 +34,8 @@ async def begin_get_route_directions_batch_async(): polling=True, ) - print("Get route directions batch batch_id to fetch the result later") - print(result.batch_id) + print("Get route directions batch continuation_token to fetch the result later") + print(result.continuation_token()) if __name__ == '__main__': asyncio.run(begin_get_route_directions_batch_async()) \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_async.py b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_async.py index 836cad354de8..de8efd0345db 100644 --- a/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_async.py +++ b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_async.py @@ -19,8 +19,7 @@ import asyncio import os -subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") - +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key") async def get_route_directions(): # [START get_route_directions_async] @@ -34,9 +33,10 @@ async def get_route_directions(): route_points=[(52.50931,13.42936), (52.50274,13.43872)] ) - print("Get Route Directions with list of coordinates:") - print(result.routes[0].summary) - print(result.routes[0].sections[0]) + if result.routes is not None: + print("Get Route Directions with list of coordinates:") + print(result.routes[0].summary) + print(result.routes[0].sections[0]) # [END get_route_directions_async] if __name__ == '__main__': diff --git a/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_batch_sync_async.py b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_batch_sync_async.py index 4cd079eb3089..4dd1eaf3ab0b 100644 --- a/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_batch_sync_async.py +++ b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_batch_sync_async.py @@ -20,7 +20,7 @@ import os from re import M -subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key") async def get_route_directions_batch_sync_async(): # [START get_route_directions_batch_sync_async] @@ -36,9 +36,11 @@ async def get_route_directions_batch_sync_async(): ] ) - print("Get route directions batch sync") - print(result.summary.total_requests) - print(result.items[0].response.routes[0].sections[0]) + if result.batch_summary is not None and result.batch_items is not None: + print("Get route directions batch sync") + print(result.batch_summary.total_requests) + print(result.batch_items[0].response.routes[0].summary.departure_time) + print(result.batch_items[0].response.routes[0].summary.arrival_time) # [END get_route_directions_batch_sync] if __name__ == '__main__': diff --git a/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_matrix_async.py b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_matrix_async.py index 2ce89e02eb03..41dec5161ff5 100644 --- a/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_matrix_async.py +++ b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_matrix_async.py @@ -19,51 +19,28 @@ import asyncio import os -subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") - +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key") async def get_route_matrix_async(): # [START get_route_matrix_async] from azure.core.credentials import AzureKeyCredential from azure.maps.route.aio import MapsRouteClient + from azure.maps.route.models import RouteMatrixQuery, GeoJsonMultiPoint maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) - request_obj = { - "origins": { - "type": "MultiPoint", - "coordinates": [ - [ - 4.85106, - 52.36006 - ], - [ - 4.85056, - 52.36187 - ] - ] - }, - "destinations": { - "type": "MultiPoint", - "coordinates": [ - [ - 4.85003, - 52.36241 - ], - [ - 13.42937, - 52.50931 - ] - ] - } - } + route_matrix_query = RouteMatrixQuery( + origins=GeoJsonMultiPoint(coordinates=[[4.85106, 52.36006], [4.85056, 52.36187]]), + destinations=GeoJsonMultiPoint(coordinates=[[4.85003, 52.36241], [13.42937, 52.50931]]) + ) async with maps_route_client: - result = await maps_route_client.get_route_matrix(query=request_obj) + result = await maps_route_client.get_route_matrix(query=route_matrix_query) - print("Get Route Matrix with given request object:") - print(result.matrix[0][0].response.summary.length_in_meters) - print(result.summary) + if result.matrix is not None: + print("Get Route Matrix with given request object:") + print(result.matrix[0][0].response.summary.length_in_meters) + print(result.summary) # [END get_route_matrix_async] if __name__ == '__main__': diff --git a/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_range_async.py b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_range_async.py index 84d712485fbf..dab9fb9dc872 100644 --- a/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_range_async.py +++ b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_range_async.py @@ -19,26 +19,26 @@ import asyncio import os -subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") - +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key") async def get_route_range(): # [START get_route_range_async] from azure.core.credentials import AzureKeyCredential from azure.maps.route.aio import MapsRouteClient - from azure.maps.route.models import LatLon + from azure.maps.route.models import LatLongPair maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) async with maps_route_client: result = await maps_route_client.get_route_range( - coordinates=LatLon(52.50931,13.42936), + coordinates=LatLongPair(latitude=52.50931, longitude=13.42936), time_budget_in_sec=6000 ) - print("Get Route Range with coordinates and time budget:") - print(result.reachable_range.center) - print(result.reachable_range.boundary[0]) + if result.reachable_range is not None and result.reachable_range.boundary is not None: + print("Get Route Range with coordinates and time budget:") + print(result.reachable_range.center) + print(result.reachable_range.boundary[0]) # [END get_route_range_async] if __name__ == '__main__': diff --git a/sdk/maps/azure-maps-route/samples/sample_authentication.py b/sdk/maps/azure-maps-route/samples/sample_authentication.py index ca76405d96cb..3d210e91bd78 100644 --- a/sdk/maps/azure-maps-route/samples/sample_authentication.py +++ b/sdk/maps/azure-maps-route/samples/sample_authentication.py @@ -29,7 +29,7 @@ def authentication_maps_service_client_with_subscription_key_credential(): from azure.core.credentials import AzureKeyCredential from azure.maps.route import MapsRouteClient - subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") + subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key") maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) # [END create_maps_route_service_client_with_key] diff --git a/sdk/maps/azure-maps-route/samples/sample_begin_get_route_directions_batch.py b/sdk/maps/azure-maps-route/samples/sample_begin_get_route_directions_batch.py index 08e21b6f79c8..93e4bcce6a6f 100644 --- a/sdk/maps/azure-maps-route/samples/sample_begin_get_route_directions_batch.py +++ b/sdk/maps/azure-maps-route/samples/sample_begin_get_route_directions_batch.py @@ -18,7 +18,7 @@ """ import os -subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key") def begin_get_route_directions_batch(): from azure.core.credentials import AzureKeyCredential @@ -32,8 +32,8 @@ def begin_get_route_directions_batch(): ] ) - print("Get route directions batch batch_id to fetch the result later") - print(result.batch_id) + print("Get route directions batch continuation_token to fetch the result later") + print(result.continuation_token()) if __name__ == '__main__': begin_get_route_directions_batch() \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/samples/sample_get_route_directions.py b/sdk/maps/azure-maps-route/samples/sample_get_route_directions.py index 3fbf8b1e7108..a76f574307a7 100644 --- a/sdk/maps/azure-maps-route/samples/sample_get_route_directions.py +++ b/sdk/maps/azure-maps-route/samples/sample_get_route_directions.py @@ -18,7 +18,7 @@ """ import os -subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key") def get_route_directions(): @@ -29,13 +29,14 @@ def get_route_directions(): maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) result = maps_route_client.get_route_directions( - route_points=[(52.50931,13.42936), (52.50274,13.43872)], + route_points=[(52.50931, 13.42936), (52.50274, 13.43872)], avoid_vignette=["AUS", "CHE"] ) - print("Get Route Directions with list of coordinates:") - print(result.routes[0].summary) - print(result.routes[0].sections[0]) + if result.routes is not None: + print("Get Route Directions with list of coordinates:") + print(result.routes[0].summary) + print(result.routes[0].sections[0]) # [END get_route_directions] if __name__ == '__main__': diff --git a/sdk/maps/azure-maps-route/samples/sample_get_route_directions_batch_sync.py b/sdk/maps/azure-maps-route/samples/sample_get_route_directions_batch_sync.py index 5896e3e387c1..b64a0c94f4dd 100644 --- a/sdk/maps/azure-maps-route/samples/sample_get_route_directions_batch_sync.py +++ b/sdk/maps/azure-maps-route/samples/sample_get_route_directions_batch_sync.py @@ -18,7 +18,7 @@ """ import os -subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key") def get_route_directions_batch_sync(): # [START get_route_directions_batch_sync] @@ -33,9 +33,11 @@ def get_route_directions_batch_sync(): ] ) - print("Get route directions batch sync") - print(result.summary.total_requests) - print(result.items[0].response.routes[0].sections[0]) + if result.batch_summary is not None and result.batch_items is not None: + print("Get route directions batch sync") + print(result.batch_summary.total_requests) + print(result.batch_items[0].response.routes[0].summary.departure_time) + print(result.batch_items[0].response.routes[0].summary.arrival_time) # [END get_route_directions_batch_sync] if __name__ == '__main__': diff --git a/sdk/maps/azure-maps-route/samples/sample_get_route_matrix.py b/sdk/maps/azure-maps-route/samples/sample_get_route_matrix.py index 496456b4a84b..4bb53b92e0fd 100644 --- a/sdk/maps/azure-maps-route/samples/sample_get_route_matrix.py +++ b/sdk/maps/azure-maps-route/samples/sample_get_route_matrix.py @@ -18,46 +18,23 @@ """ import os -subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key") def get_route_matrix(): # [START get_route_matrix] from azure.core.credentials import AzureKeyCredential from azure.maps.route import MapsRouteClient + from azure.maps.route.models import RouteMatrixQuery, GeoJsonMultiPoint maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) - request_obj = { - "origins": { - "type": "MultiPoint", - "coordinates": [ - [ - 4.85106, - 52.36006 - ], - [ - 4.85056, - 52.36187 - ] - ] - }, - "destinations": { - "type": "MultiPoint", - "coordinates": [ - [ - 4.85003, - 52.36241 - ], - [ - 13.42937, - 52.50931 - ] - ] - } - } + route_matrix_query = RouteMatrixQuery( + origins=GeoJsonMultiPoint(coordinates=[[4.85106, 52.36006], [4.85056, 52.36187]]), + destinations=GeoJsonMultiPoint(coordinates=[[4.85003, 52.36241], [13.42937, 52.50931]]) + ) - result = maps_route_client.get_route_matrix(query=request_obj) + result = maps_route_client.get_route_matrix(query=route_matrix_query) print("Get Route Matrix with given request object:") print(result.summary) diff --git a/sdk/maps/azure-maps-route/samples/sample_get_route_range.py b/sdk/maps/azure-maps-route/samples/sample_get_route_range.py index 43dc3872ed68..1f7c83f41de5 100644 --- a/sdk/maps/azure-maps-route/samples/sample_get_route_range.py +++ b/sdk/maps/azure-maps-route/samples/sample_get_route_range.py @@ -18,7 +18,7 @@ """ import os -subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key") def get_route_range(): # [START get_route_range] @@ -29,9 +29,10 @@ def get_route_range(): result = maps_route_client.get_route_range(coordinates=(52.50931,13.42936), time_budget_in_sec=6000) - print("Get Route Range with coordinates and time budget:") - print(result.reachable_range.center) - print(result.reachable_range.boundary[0]) + if result.reachable_range is not None and result.reachable_range.boundary is not None: + print("Get Route Range with coordinates and time budget:") + print(result.reachable_range.center) + print(result.reachable_range.boundary[0]) # [END get_route_range] if __name__ == '__main__': diff --git a/sdk/maps/azure-maps-route/tests/test_route_client.py b/sdk/maps/azure-maps-route/tests/test_route_client.py index f936e203162c..054595f915e7 100644 --- a/sdk/maps/azure-maps-route/tests/test_route_client.py +++ b/sdk/maps/azure-maps-route/tests/test_route_client.py @@ -6,6 +6,7 @@ import os from azure.core.credentials import AccessToken, AzureKeyCredential from azure.maps.route import MapsRouteClient +from azure.maps.route.models import RouteMatrixQuery, GeoJsonMultiPoint from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, is_live from route_preparer import MapsRoutePreparer @@ -40,36 +41,12 @@ def test_get_route_range(self): @MapsRoutePreparer() @recorded_by_proxy - def get_route_matrix(self): - request_obj = { - "origins": { - "type": "MultiPoint", - "coordinates": [ - [ - 4.85106, - 52.36006 - ], - [ - 4.85056, - 52.36187 - ] - ] - }, - "destinations": { - "type": "MultiPoint", - "coordinates": [ - [ - 4.85003, - 52.36241 - ], - [ - 13.42937, - 52.50931 - ] - ] - } - } - result = self.client.get_route_matrix(request_obj) + def test_get_route_matrix(self): + route_matrix_query = RouteMatrixQuery( + origins=GeoJsonMultiPoint(coordinates=[[4.85106, 52.36006], [4.85056, 52.36187]]), + destinations=GeoJsonMultiPoint(coordinates=[[4.85003, 52.36241], [13.42937, 52.50931]]) + ) + result = self.client.get_route_matrix(route_matrix_query) assert len(result.matrix) > 0 top_answer = result.matrix[0][0] - assert top_answer.response.summary.length_in_meters == 495 + assert top_answer.response.summary.length_in_meters == 494