Skip to main content

Microsoft Azure Maps Geolocation Client Library for Python

Project description

Azure Maps Geolocation Package client library for Python

This package contains a Python SDK for Azure Maps Services for Geolocation. Read more about Azure Maps Services here

Source code | API reference documentation | Product documentation

Disclaimer

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

Getting started

Prerequisites

If you use Azure CLI, replace <resource-group-name> and <account-name> of your choice, and select a proper pricing tier based on your needs via the <sku-name> parameter. Please refer to this page for more details.

az maps account create --resource-group <resource-group-name> --account-name <account-name> --sku <sku-name>

Install the package

Install the Azure Maps Service Geolocation SDK.

pip install azure-maps-geolocation

Create and Authenticate the MapsGeolocationClient

To create a client object to access the Azure Maps Geolocation API, you will need a credential object. Azure Maps Geolocation client also support three ways to authenticate.

1. Authenticate with a Subscription Key Credential

You can authenticate with your Azure Maps Subscription Key. Once the Azure Maps Subscription Key is created, set the value of the key as environment variable: AZURE_SUBSCRIPTION_KEY. Then pass an AZURE_SUBSCRIPTION_KEY as the credential parameter into an instance of AzureKeyCredential.

from azure.core.credentials import AzureKeyCredential
from azure.maps.geolocation import MapsGeolocationClient

credential = AzureKeyCredential(os.environ.get("AZURE_SUBSCRIPTION_KEY"))

geolocation_client = MapsGeolocationClient(
    credential=credential,
)

2. Authenticate with a SAS Credential

Shared access signature (SAS) tokens are authentication tokens created using the JSON Web token (JWT) format and are cryptographically signed to prove authentication for an application to the Azure Maps REST API.

To authenticate with a SAS token in Python, you'll need to generate one using the azure-mgmt-maps package.

We need to tell user to install azure-mgmt-maps: pip install azure-mgmt-maps

Here's how you can generate the SAS token using the list_sas method from azure-mgmt-maps:

from azure.identity import DefaultAzureCredential
from azure.mgmt.maps import AzureMapsManagementClient

"""
# PREREQUISITES
    pip install azure-identity
    pip install azure-mgmt-maps
# USAGE
    python account_list_sas.py
    Before run the sample, please set the values of the client ID, tenant ID and client secret
    of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
    AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
    https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""


def main():
    client = AzureMapsManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id="your-subscription-id",
    )

    response = client.accounts.list_sas(
        resource_group_name="myResourceGroup",
        account_name="myMapsAccount",
        maps_account_sas_parameters={
            "expiry": "2017-05-24T11:42:03.1567373Z",
            "maxRatePerSecond": 500,
            "principalId": "your-principal-id",
            "regions": ["eastus"],
            "signingKey": "primaryKey",
            "start": "2017-05-24T10:42:03.1567373Z",
        },
    )
    print(response)

Once the SAS token is created, set the value of the token as environment variable: AZURE_SAS_TOKEN. Then pass an AZURE_SAS_TOKEN as the credential parameter into an instance of AzureSasCredential.

import os

from azure.core.credentials import AzureSASCredential
from azure.maps.geolocation import MapsGeolocationClient

credential = AzureSASCredential(os.environ.get("AZURE_SAS_TOKEN"))

geolocation_client = MapsGeolocationClient(
    credential=credential,
)

3. Authenticate with an Microsoft Entra ID credential

You can authenticate with Microsoft Entra ID token credential using the Azure Identity library. Authentication by using Microsoft Entra ID requires some initial setup:

After setup, you can choose which type of credential from azure.identity to use. As an example, DefaultAzureCredential can be used to authenticate the client:

Next, set the values of the client ID, tenant ID, and client secret of the Microsoft Entra ID application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET

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 on how to find it.

from azure.maps.geolocation import MapsGeolocationClient
from azure.identity import DefaultAzureCredential

credential = DefaultAzureCredential()
geolocation_client = MapsGeolocationClient(
    client_id="<Azure Maps Client ID>",
    credential=credential
)

Key concepts

The Azure Maps Geolocation client library for Python allows you to interact with each of the components through the use of a dedicated client object.

Sync Clients

MapsGeolocationClient is the primary client for developers using the Azure Maps Geolocation client library for Python. Once you initialized a MapsGeolocationClient class, you can explore the methods on this client object to understand the different features of the Azure Maps Geolocation service that you can access.

Async Clients

This library includes a complete async API supported on Python 3.8+. To use it, you must first install an async transport, such as aiohttp. See azure-core documentation for more information.

Async clients and credentials should be closed when they're no longer needed. These objects are async context managers and define async close methods.

Examples

The following sections provide several code snippets covering some of the most common Azure Maps Geolocation tasks, including:

Get Geolocation

This service will return the ISO country code for the provided IP address. Developers can use this information to block or alter certain content based on geographical locations where the application is being viewed from.

from azure.maps.geolocation import MapsGeolocationClient

BLOCK_COUNTRY_LIST = ['US', 'TW', 'AF', 'AX', 'DL']
INCOME_IP_ADDRESS = "2001:4898:80e8:b::189"
geolocation_result = client.get_country_code(ip_address=INCOME_IP_ADDRESS)

result_country_code = geolocation_result.iso_code

if result_country_code in BLOCK_COUNTRY_LIST:
    raise Exception("These IP address is from forebiden country")

Troubleshooting

General

Maps Geolocation clients raise exceptions defined in Azure Core.

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.

Logging

This library uses the standard logging library for logging. Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO level.

Detailed DEBUG level logging, including request/response bodies and unredacted headers, can be enabled on a client with the logging_enable argument:

import sys
import logging
from azure.maps.geolocation import MapsGeolocationClient

# Create a logger for the 'azure.maps.geolocation' SDK
logger = logging.getLogger('azure.maps.geolocation')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

Additional

Still running into issues? If you encounter any bugs or have suggestions, please file an issue in the Issues section of the project.

Next steps

More sample code

Get started with our Maps Geolocation samples (Async Version samples).

Several Azure Maps Geolocation 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 Geolocation

set AZURE_SUBSCRIPTION_KEY="<RealSubscriptionKey>"

pip install azure-maps-geolocation --pre

python samples/sample_authentication.py
python sample/sample_get_country_code.py

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.

Further detail please refer to Samples Introduction

Additional documentation

For more extensive documentation on Azure Maps Geolocation, see the Azure Maps Geolocation documentation on docs.microsoft.com.

Contributing

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.

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.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Release History

1.0.0b3 (2024-12-12)

Features Added

  • Integrated support for SAS-based authentication

1.0.0b2 (2024-11-11)

Other Changes

  • Remove python 3.6 support
  • Fix API version error
  • Fix Sphinx errors
  • Fix mypy typing errors for mypy version 1.6.1

1.0.0b1 (2022-10-11)

Features Added

  • Initial release

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

azure_maps_geolocation-1.0.0b3.tar.gz (42.1 kB view details)

Uploaded Source

Built Distribution

azure_maps_geolocation-1.0.0b3-py3-none-any.whl (49.9 kB view details)

Uploaded Python 3

File details

Details for the file azure_maps_geolocation-1.0.0b3.tar.gz.

File metadata

File hashes

Hashes for azure_maps_geolocation-1.0.0b3.tar.gz
Algorithm Hash digest
SHA256 2591834766425956477e36983de6cc883589da3b024ee917f6c7bc20947ea8ea
MD5 dfd8e23e1a0c362e3f023873a44be298
BLAKE2b-256 cdb6c882c41c1fed864072b755028bd5fbc6ad32d0c04812f03a085e0ffeee0f

See more details on using hashes here.

File details

Details for the file azure_maps_geolocation-1.0.0b3-py3-none-any.whl.

File metadata

File hashes

Hashes for azure_maps_geolocation-1.0.0b3-py3-none-any.whl
Algorithm Hash digest
SHA256 825cfcb2fb785ac6163ea57682cf16d249b96b460150d1618e7769ede7806c28
MD5 89b7e71f47711e3be5c9ee20d8a08867
BLAKE2b-256 b780e7d8a12588914d4f94265a0ad2ff60706cbb1850be249a0c7771b665f1e9

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page