Skip to content

Commit 7b3dfdc

Browse files
authored
[Azure Maps] - Onboarding for Route SDKs (#25101)
* init * Update client, add samples * Update and expose models * Minor Update/clean up Update samples and tests Modify docstring * Delete and update uplicated intro in README * Update - Combine get route directions methods and post route directions methods - Minor update according to feedback * Update docstring * update test with test_proxy * update according to feedback * update to new autorest generated files * update exposed models * update according to feedback * update release date & minor naming & clean up` * Add overload methodst * fix pylint
1 parent b515775 commit 7b3dfdc

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

61 files changed

+22641
-3
lines changed
+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Release History
2+
3+
## 1.0.0b1 (2022-10-13)
4+
5+
* Initial Release

sdk/maps/azure-maps-route/MANIFEST.in

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
recursive-include tests *.py *.yaml
2+
recursive-include samples *.py *.md
3+
include *.md
4+
include azure/__init__.py
5+
include azure/maps/__init__.py
6+
include azure/maps/route/py.typed

sdk/maps/azure-maps-route/README.md

+238
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,238 @@
1+
# Azure Maps Route Package client library for Python
2+
3+
This package contains a Python SDK for Azure Maps Services for Route.
4+
Read more about Azure Maps Services [here](https://docs.microsoft.com/azure/azure-maps/)
5+
6+
[Source code](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-route) | [API reference documentation](https://docs.microsoft.com/rest/api/maps/route) | [Product documentation](https://docs.microsoft.com/azure/azure-maps/)
7+
8+
## _Disclaimer_
9+
10+
_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to <https://github.com/Azure/azure-sdk-for-python/issues/20691>_
11+
12+
## Getting started
13+
14+
### Prerequisites
15+
16+
- Python 3.6 or later is required to use this package.
17+
- An [Azure subscription][azure_subscription] and an [Azure Maps account](https://docs.microsoft.com/azure/azure-maps/how-to-manage-account-keys).
18+
- A deployed Maps Services resource. You can create the resource via [Azure Portal][azure_portal] or [Azure CLI][azure_cli].
19+
20+
If you use Azure CLI, replace `<resource-group-name>` and `<account-name>` of your choice, and select a proper [pricing tier](https://docs.microsoft.com/azure/azure-maps/choose-pricing-tier) based on your needs via the `<sku-name>` parameter. Please refer to [this page](https://docs.microsoft.com/cli/azure/maps/account?view=azure-cli-latest#az_maps_account_create) for more details.
21+
22+
```bash
23+
az maps account create --resource-group <resource-group-name> --account-name <account-name> --sku <sku-name>
24+
```
25+
26+
### Install the package
27+
28+
Install the Azure Maps Service Route SDK.
29+
30+
```bash
31+
pip install azure-maps-route
32+
```
33+
34+
### Create and Authenticate the MapsRouteClient
35+
36+
To create a client object to access the Azure Maps Route API, you will need a **credential** object. Azure Maps Route client also support two ways to authenticate.
37+
38+
#### 1. Authenticate with a Subscription Key Credential
39+
40+
You can authenticate with your Azure Maps Subscription Key.
41+
Once the Azure Maps Subscription Key is created, set the value of the key as environment variable: `AZURE_SUBSCRIPTION_KEY`.
42+
Then pass an `AZURE_SUBSCRIPTION_KEY` as the `credential` parameter into an instance of [AzureKeyCredential][azure-key-credential].
43+
44+
```python
45+
from azure.core.credentials import AzureKeyCredential
46+
from azure.maps.route import MapsRouteClient
47+
48+
credential = AzureKeyCredential(os.environ.get("AZURE_SUBSCRIPTION_KEY"))
49+
50+
route_client = MapsRouteClient(
51+
credential=credential,
52+
)
53+
```
54+
55+
#### 2. Authenticate with an Azure Active Directory credential
56+
57+
You can authenticate with [Azure Active Directory (AAD) token credential][maps_authentication_aad] using the [Azure Identity library][azure_identity].
58+
Authentication by using AAD requires some initial setup:
59+
60+
- Install [azure-identity][azure-key-credential]
61+
- Register a [new AAD application][register_aad_app]
62+
- Grant access to Azure Maps by assigning the suitable role to your service principal. Please refer to the [Manage authentication page][manage_aad_auth_page].
63+
64+
After setup, you can choose which type of [credential][azure-key-credential] from `azure.identity` to use.
65+
As an example, [DefaultAzureCredential][default_azure_credential]
66+
can be used to authenticate the client:
67+
68+
Next, set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables:
69+
`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET`
70+
71+
You will also need to specify the Azure Maps resource you intend to use by specifying the `clientId` in the client options. The Azure Maps resource client id can be found in the Authentication sections in the Azure Maps resource. Please refer to the [documentation][how_to_manage_authentication] on how to find it.
72+
73+
```python
74+
from azure.maps.route import MapsRouteClient
75+
from azure.identity import DefaultAzureCredential
76+
77+
credential = DefaultAzureCredential()
78+
route_client = MapsRouteClient(
79+
client_id="<Azure Maps Client ID>",
80+
credential=credential
81+
)
82+
```
83+
84+
## Key concepts
85+
86+
The Azure Maps Route client library for Python allows you to interact with each of the components through the use of a dedicated client object.
87+
88+
### Sync Clients
89+
90+
`MapsRouteClient` is the primary client for developers using the Azure Maps Route client library for Python.
91+
Once you initialized a `MapsRouteClient` class, you can explore the methods on this client object to understand the different features of the Azure Maps Route service that you can access.
92+
93+
### Async Clients
94+
95+
This library includes a complete async API supported on Python 3.5+. To use it, you must first install an async transport, such as [aiohttp](https://pypi.org/project/aiohttp/).
96+
See [azure-core documentation](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/CLIENT_LIBRARY_DEVELOPER.md#transport) for more information.
97+
98+
Async clients and credentials should be closed when they're no longer needed. These
99+
objects are async context managers and define async `close` methods.
100+
101+
## Examples
102+
103+
The following sections provide several code snippets covering some of the most common Azure Maps Route tasks, including:
104+
105+
- [Request and Get Route Directions](#request-and-get-route-directions)
106+
- [Request and Get Route Range](#reqest-and-get-route-range)
107+
- [Get Route Matrix](#get-route-matrix)
108+
- [Get Route Directions Batch](#get-route-directions-batch)
109+
110+
### Request and Get Route Directions
111+
112+
This service request 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.
113+
114+
```python
115+
from azure.maps.route import MapsRouteClient
116+
117+
route_directions_result = client.get_route_directions(route_points=[LatLon(47.60323, -122.33028), LatLon(53.2, -106)]);
118+
```
119+
120+
### Request and Get Route Range
121+
122+
This service will calculate a set of locations that can be reached from the origin point by given coordinates and based on fuel, energy, time or distance budget that is specified.
123+
124+
```python
125+
from azure.maps.route import MapsRouteClient
126+
127+
route_range_result = client.get_route_range(coordinates=LatLon(47.60323, -122.33028), time_budget_in_sec=6000);
128+
```
129+
130+
### Get Route Matrix
131+
132+
If the Matrix Route request was accepted successfully, the Location header in the response contains the URL to download the results of the request.
133+
134+
Retrieves the result of a previous route matrix request.
135+
The method returns a poller for retrieving the result.
136+
137+
```python
138+
from azure.maps.route import MapsRouteClient
139+
140+
route_matrix_result = client.begin_get_route_matrix_result(matrix_id="11111111-2222-3333-4444-555555555555");
141+
```
142+
143+
### Get Route Directions Batch
144+
145+
Retrieves the result of a previous route direction batch request.
146+
The method returns a poller for retrieving the result.
147+
148+
```python
149+
from azure.maps.route import MapsRouteClient
150+
151+
route_directions_batch_poller_result = client.begin_get_route_directions_batch_result(batch_id="11111111-2222-3333-4444-555555555555");
152+
```
153+
154+
## Troubleshooting
155+
156+
### General
157+
158+
Maps Route clients raise exceptions defined in [Azure Core](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/README.md).
159+
160+
This list can be used for reference to catch thrown exceptions. To get the specific error code of the exception, use the `error_code` attribute, i.e, `exception.error_code`.
161+
162+
### Logging
163+
164+
This library uses the standard [logging](https://docs.python.org/3/library/logging.html) library for logging.
165+
Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO level.
166+
167+
Detailed DEBUG level logging, including request/response bodies and unredacted headers, can be enabled on a client with the `logging_enable` argument:
168+
169+
```python
170+
import sys
171+
import logging
172+
from azure.maps.route import MapsRouteClient
173+
174+
# Create a logger for the 'azure.maps.route' SDK
175+
logger = logging.getLogger('azure.maps.route')
176+
logger.setLevel(logging.DEBUG)
177+
178+
# Configure a console output
179+
handler = logging.StreamHandler(stream=sys.stdout)
180+
logger.addHandler(handler)
181+
182+
```
183+
184+
### Additional
185+
186+
Still running into issues? If you encounter any bugs or have suggestions, please file an issue in the [Issues](<https://github.com/Azure/azure-sdk-for-python/issues>) section of the project.
187+
188+
## Next steps
189+
190+
### More sample code
191+
192+
Get started with our [Maps Route samples](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-route/samples) ([Async Version samples](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-route/samples/async_samples)).
193+
194+
Several Azure Maps Route Python SDK samples are available to you in the SDK's GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Maps Route
195+
196+
```bash
197+
set AZURE_SUBSCRIPTION_KEY="<RealSubscriptionKey>"
198+
199+
pip install azure-maps-route --pre
200+
201+
python samples/sample_authentication.py
202+
python sample/sample_get_route_range.py
203+
python samples/sample_get_route_directions.py
204+
python samples/sample_request_route_matrix.py
205+
python samples/async_samples/sample_authentication_async.py
206+
python samples/async_samples/sample_get_route_range_async.py
207+
python samples/async_samples/sample_request_route_matrix_async.py
208+
python samples/async_samples/sample_get_route_directions_async.py
209+
```
210+
211+
> Notes: `--pre` flag can be optionally added, it is to include pre-release and development versions for `pip install`. By default, `pip` only finds stable versions.
212+
213+
Further detail please refer to [Samples Introduction](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-route/samples/README.md)
214+
215+
### Additional documentation
216+
217+
For more extensive documentation on Azure Maps Route, see the [Azure Maps Route documentation](https://docs.microsoft.com/rest/api/maps/route) on docs.microsoft.com.
218+
219+
## Contributing
220+
221+
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit <https://cla.microsoft.com>.
222+
223+
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.
224+
225+
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments.
226+
227+
<!-- LINKS -->
228+
[azure_subscription]: https://azure.microsoft.com/free/
229+
[azure_identity]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/identity/azure-identity
230+
[azure_portal]: https://portal.azure.com
231+
[azure_cli]: https://docs.microsoft.com/cli/azure
232+
[azure-key-credential]: https://aka.ms/azsdk/python/core/azurekeycredential
233+
[default_azure_credential]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#defaultazurecredential
234+
[register_aad_app]: https://docs.microsoft.com/powershell/module/Az.Resources/New-AzADApplication?view=azps-8.0.0
235+
[maps_authentication_aad]: https://docs.microsoft.com/azure/azure-maps/how-to-manage-authentication
236+
[create_new_application_registration]: https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/applicationsListBlade/quickStartType/AspNetWebAppQuickstartPage/sourceType/docs
237+
[manage_aad_auth_page]: https://docs.microsoft.com/azure/azure-maps/how-to-manage-authentication
238+
[how_to_manage_authentication]: https://docs.microsoft.com/azure/azure-maps/how-to-manage-authentication#view-authentication-details
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# coding=utf-8
2+
# --------------------------------------------------------------------------
3+
# Copyright (c) Microsoft Corporation. All rights reserved.
4+
# Licensed under the MIT License. See License.txt in the project root for license information.
5+
# Code generated by Microsoft (R) AutoRest Code Generator.
6+
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
7+
# --------------------------------------------------------------------------
8+
9+
from ._version import VERSION
10+
from ._route_client import MapsRouteClient
11+
12+
__all__ = [
13+
'MapsRouteClient'
14+
]
15+
__version__ = VERSION
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# ------------------------------------
2+
# Copyright (c) Microsoft Corporation.
3+
# Licensed under the MIT License.
4+
# ------------------------------------
5+
6+
from typing import Union, Any
7+
from azure.core.pipeline.policies import AzureKeyCredentialPolicy
8+
from azure.core.credentials import AzureKeyCredential, TokenCredential
9+
from ._generated import MapsRouteClient as _MapsRouteClient
10+
from ._version import VERSION
11+
12+
# To check the credential is either AzureKeyCredential or TokenCredential
13+
def _authentication_policy(credential):
14+
authentication_policy = None
15+
if credential is None:
16+
raise ValueError("Parameter 'credential' must not be None.")
17+
if isinstance(credential, AzureKeyCredential):
18+
authentication_policy = AzureKeyCredentialPolicy(
19+
name="subscription-key", credential=credential
20+
)
21+
elif credential is not None and not hasattr(credential, "get_token"):
22+
raise TypeError(
23+
"Unsupported credential: {}. Use an instance of AzureKeyCredential "
24+
"or a token credential from azure.identity".format(type(credential))
25+
)
26+
return authentication_policy
27+
28+
class MapsRouteClientBase:
29+
def __init__(
30+
self,
31+
credential: Union[AzureKeyCredential, TokenCredential],
32+
**kwargs: Any
33+
) -> None:
34+
35+
self._maps_client = _MapsRouteClient(
36+
credential=credential, # type: ignore
37+
api_version=kwargs.pop("api_version", VERSION),
38+
authentication_policy=kwargs.pop("authentication_policy", _authentication_policy(credential)),
39+
**kwargs
40+
)
41+
self._route_client = self._maps_client.route
42+
43+
def __enter__(self):
44+
self._maps_client.__enter__() # pylint:disable=no-member
45+
return self
46+
47+
def __exit__(self, *args):
48+
self._maps_client.__exit__(*args) # pylint:disable=no-member
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# coding=utf-8
2+
# --------------------------------------------------------------------------
3+
# Copyright (c) Microsoft Corporation. All rights reserved.
4+
# Licensed under the MIT License. See License.txt in the project root for license information.
5+
# Code generated by Microsoft (R) AutoRest Code Generator.
6+
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
7+
# --------------------------------------------------------------------------
8+
9+
from ._client import MapsRouteClient
10+
from ._version import VERSION
11+
12+
__version__ = VERSION
13+
14+
try:
15+
from ._patch import __all__ as _patch_all
16+
from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import
17+
except ImportError:
18+
_patch_all = []
19+
from ._patch import patch_sdk as _patch_sdk
20+
21+
__all__ = ["MapsRouteClient"]
22+
__all__.extend([p for p in _patch_all if p not in __all__])
23+
24+
_patch_sdk()

0 commit comments

Comments
 (0)