Python REST SDK 개발자 가이드(미리 보기)
Azure Maps Python SDK를 Python 애플리케이션 및 라이브러리와 통합하여 지도 관련 및 위치 인식 애플리케이션을 빌드할 수 있습니다. Azure Maps Python SDK에는 검색, 경로, 렌더링 및 지리적 위치용 API가 포함되어 있습니다. 이러한 API는 주소 검색, 서로 다른 좌표 간 라우팅, 특정 IP 주소의 지리적 위치 가져오기와 같은 작업을 지원합니다.
필수 조건
- Azure Maps 계정.
- 구독 키 또는 다른 형태의 Azure Maps 인증.
- Python 3.7 이상. 최신 릴리스를 사용하는 것이 좋습니다. 자세한 내용은 Python용 Azure SDK 버전 지원 정책을 참조하세요.
팁
프로그래밍 방식으로 Azure Maps 계정을 만들 수 있습니다. 다음은 Azure CLI를 사용하는 예입니다.
az maps account create --kind "Gen2" --account-name "myMapAccountName" --resource-group "<resource group>" --sku "G2"
Python 프로젝트 만들기
다음 예제에서는 Python을 사용하여 demo
라는 콘솔 프로그램을 만드는 방법을 보여 줍니다.
mkdir mapsDemo
cd mapsDemo
New-Item demo.py
필요한 Python 패키지 설치
Azure Maps의 각 서비스는 자체 패키지에 포함되어 있습니다. Azure Maps Python SDK를 사용하는 경우 필요한 서비스의 패키지만 설치할 수 있습니다.
여기서는 Azure Maps Search 패키지를 설치합니다. 아직 공개 미리 보기 상태이므로 --pre
플래그를 추가해야 합니다.
pip install azure-maps-search --pre
Azure Maps 서비스
Azure Maps Python SDK는 Python 버전 3.7 이상을 지원합니다. 향후 Python 버전에 대한 자세한 내용은 Python용 Azure SDK 버전 지원 정책을 참조하세요.
서비스 이름 | PyPi 패키지 | 샘플 |
---|---|---|
Search | azure-maps-search | 검색 샘플 |
Route | azure-maps-route | 경로 샘플 |
렌더링 | azure-maps-render | 렌더링 샘플 |
지리적 위치 | azure-maps-geolocation | 지리적 위치 샘플 |
MapsSearchClient 만들기 및 인증
Azure Maps 검색 API에 액세스하는 데 사용되는 MapsSearchClient
개체를 만들 때 인증을 위해 credential
개체가 필요합니다. Microsoft Entra 자격 증명 또는 Azure 구독 키를 사용하여 인증할 수 있습니다. 자세한 내용은 Azure Maps로 인증을 참조하세요.
팁
MapsSearchClient
는 Azure Maps 검색 라이브러리를 사용하는 개발자를 위한 기본 인터페이스입니다. 사용 가능한 검색 방법에 대한 자세한 내용은 Azure Maps Search 패키지 클라이언트 라이브러리를 참조하세요.
Microsoft Entra 자격 증명 사용
Azure ID 패키지를 사용하여 Microsoft Entra ID로 인증을 받을 수 있습니다. DefaultAzureCredential 공급자를 사용하려면 Azure ID 클라이언트 패키지를 설치해야 합니다.
pip install azure-identity
새 Microsoft Entra 애플리케이션을 등록하고 필요한 역할을 서비스 주체에 할당하여 Azure Maps에 대한 액세스 권한을 부여해야 합니다. 자세한 내용은 비 Azure 리소스의 디먼 호스트를 참조하세요. 애플리케이션(클라이언트) ID, 디렉터리(테넌트) ID 및 클라이언트 암호가 반환됩니다. 이 값을 복사하여 안전한 장소에 저장합니다. 다음 단계에서 필요합니다.
다음으로 맵의 클라이언트 ID를 지정하여 사용하려는 Azure Maps 계정을 지정해야 합니다. Azure Maps 계정 클라이언트 ID는 Azure Maps 계정의 인증 섹션에서 찾을 수 있습니다. 자세한 내용은 인증 세부 정보 보기를 참조하세요.
애플리케이션(클라이언트) ID, 디렉터리(테넌트) ID, Microsoft Entra 애플리케이션의 클라이언트 암호 및 맵 리소스의 클라이언트 ID 값을 환경 변수로 설정합니다.
환경 변수 | 설명 |
---|---|
AZURE_CLIENT_ID | 등록된 애플리케이션의 애플리케이션(클라이언트) ID |
AZURE_CLIENT_SECRET | 등록된 애플리케이션의 클라이언트 암호 값 |
AZURE_TENANT_ID | 등록된 애플리케이션의 디렉터리(테넌트) ID |
MAPS_CLIENT_ID | Azure Maps 계정의 클라이언트 ID |
이제 PowerShell에서 환경 변수를 만들어 다음 값을 저장할 수 있습니다.
$Env:AZURE_CLIENT_ID="Application (client) ID"
$Env:AZURE_CLIENT_SECRET="your client secret"
$Env:AZURE_TENANT_ID="your Directory (tenant) ID"
$Env:MAPS_CLIENT_ID="your Azure Maps client ID"
환경 변수를 설정한 후 프로그램에서 AzureMapsSearch
클라이언트를 인스턴스화하는 데 사용할 수 있습니다. demo.py라는 파일을 만들고 다음 코드를 추가합니다.
import os
from azure.identity import DefaultAzureCredential
from azure.maps.search import MapsSearchClient
credential = DefaultAzureCredential()
maps_client_id = os.getenv("MAPS_CLIENT_ID")
maps_search_client = MapsSearchClient(
client_id=maps_client_id,
credential=credential
)
Important
이전 코드 조각에서 만든 다른 환경 변수는 코드 샘플에서는 사용되지 않지만 DefaultAzureCredential()
에서 필요합니다. 동일한 명명 규칙을 사용하여 이러한 환경 변수를 올바르게 설정하지 않으면 런타임 오류가 발생합니다. 예를 들어 AZURE_CLIENT_ID
가 누락되었거나 잘못된 경우 InvalidAuthenticationTokenTenant
오류가 발생합니다.
구독 키 자격 증명 사용
Azure Maps 구독 키로 인증할 수 있습니다. 구독 키는 다음 스크린샷과 같이 Azure Maps 계정의 인증 섹션에서 찾을 수 있습니다.
이제 PowerShell에서 환경 변수를 만들어 구독 키를 저장할 수 있습니다.
$Env:SUBSCRIPTION_KEY="your subscription key"
환경 변수가 만들어지면 코드에서 액세스할 수 있습니다. demo.py라는 파일을 만들고 다음 코드를 추가합니다.
import os
from azure.core.credentials import AzureKeyCredential
from azure.maps.search import MapsSearchClient
# Use Azure Maps subscription key authentication
subscription_key = os.getenv("SUBSCRIPTION_KEY")
maps_search_client = MapsSearchClient(
credential=AzureKeyCredential(subscription_key)
)
엔터티 유사 항목 검색
다음 코드 조각은 간단한 콘솔 애플리케이션에서 Azure.Maps.Search
패키지를 가져오고 시애틀 근처의 "스타벅스"에 대해 퍼지 검색을 수행하는 방법을 보여 줍니다. 이 예제에서는 구독 키 자격 증명을 사용하여 MapsSearchClient를 인증합니다. demo.py
의 경우
import os
from azure.core.credentials import AzureKeyCredential
from azure.maps.search import MapsSearchClient
def fuzzy_search():
# Use Azure Maps subscription key authentication
subscription_key = os.getenv("SUBSCRIPTION_KEY")
maps_search_client = MapsSearchClient(
credential=AzureKeyCredential(subscription_key)
)
result = maps_search_client.fuzzy_search(
query="Starbucks",
coordinates=(47.61010, -122.34255)
)
# Print the search results
if len(result.results) > 0:
print("Starbucks search result nearby Seattle:")
for result_item in result.results:
print(f"* {result_item.address.street_number } {result_item.address.street_name }")
print(f" {result_item.address.municipality } {result_item.address.country_code } {result_item.address.postal_code }")
print(f" Coordinate: {result_item.position.lat}, {result_item.position.lon}")
if __name__ == '__main__':
fuzzy_search()
이 샘플 코드는 Azure Maps 구독 키로 AzureKeyCredential
을 인스턴스화한 다음, MapsSearchClient
개체를 인스턴스화하는 데 사용합니다. MapsSearchClient
에서 제공하는 메서드는 요청을 Azure Maps REST 엔드포인트로 전달합니다. 결국 프로그램은 결과를 반복하고 각 결과에 대한 주소와 좌표를 출력합니다.
프로그램을 완료한 후 PowerShell의 프로젝트 폴더에서 python demo.py
를 실행합니다.
python demo.py
스타벅스 주소 목록과 좌표 결과가 표시됩니다.
* 1912 Pike Place
Seattle US 98101
Coordinate: 47.61016, -122.34248
* 2118 Westlake Avenue
Seattle US 98121
Coordinate: 47.61731, -122.33782
* 2601 Elliott Avenue
Seattle US 98121
Coordinate: 47.61426, -122.35261
* 1730 Howell Street
Seattle US 98101
Coordinate: 47.61716, -122.3298
* 220 1st Avenue South
Seattle US 98104
Coordinate: 47.60027, -122.3338
* 400 Occidental Avenue South
Seattle US 98104
Coordinate: 47.5991, -122.33278
* 1600 East Olive Way
Seattle US 98102
Coordinate: 47.61948, -122.32505
* 500 Mercer Street
Seattle US 98109
Coordinate: 47.62501, -122.34687
* 505 5Th Ave S
Seattle US 98104
Coordinate: 47.59768, -122.32849
* 425 Queen Anne Avenue North
Seattle US 98109
Coordinate: 47.62301, -122.3571
주소 검색
SearchAddress
메서드를 호출하여 주소의 좌표를 가져옵니다. 다음과 같이 샘플에서 Main 프로그램을 수정합니다.
import os
from azure.core.credentials import AzureKeyCredential
from azure.maps.search import MapsSearchClient
def search_address():
subscription_key = os.getenv("SUBSCRIPTION_KEY")
maps_search_client = MapsSearchClient(
credential=AzureKeyCredential(subscription_key)
)
result = maps_search_client.search_address(
query="1301 Alaskan Way, Seattle, WA 98101, US"
)
# Print reuslts if any
if len(result.results) > 0:
print(f"Coordinate: {result.results[0].position.lat}, {result.results[0].position.lon}")
else:
print("No address found")
if __name__ == '__main__':
search_address()
SearchAddress
메서드는 신뢰도 점수로 정렬된 결과를 반환하고 첫 번째 결과의 좌표를 출력합니다.
일괄 처리 역방향 검색
Azure Maps Search는 일부 일괄 처리 쿼리 방법도 제공합니다. 이러한 메서드는 LRO(장기 실행 작업) 개체를 반환합니다. 요청이 모든 결과를 즉시 반환하지 않을 수 있으므로 완료될 때까지 기다리거나 주기적으로 결과를 쿼리하도록 선택할 수 있습니다. 다음 예제에서는 일괄 처리된 역방향 검색 메서드를 호출하는 방법을 보여 줍니다.
LRO 개체를 반환하므로 aiohttp
패키지에 포함된 asyncio
메서드가 필요합니다.
pip install aiohttp
import asyncio
import os
from azure.core.credentials import AzureKeyCredential
from azure.maps.search.aio import MapsSearchClient
async def begin_reverse_search_address_batch():
subscription_key = os.getenv("SUBSCRIPTION_KEY")
maps_search_client = MapsSearchClient(AzureKeyCredential(subscription_key))
async with maps_search_client:
result = await maps_search_client.begin_reverse_search_address_batch(
search_queries = [
"148.858561,2.294911",
"47.639765,-122.127896&radius=5000",
"47.61559,-122.33817&radius=5000",
]
)
print(f"Batch_id: {result.batch_id}")
if __name__ == '__main__':
# Special handle for Windows platform
if os.name == 'nt':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(begin_reverse_search_address_batch())
위의 예제에서는 3개의 쿼리가 일괄 처리된 역방향 검색 요청에 전달됩니다. LRO 결과를 가져오기 위해 요청은 일괄 처리 ID가 있는 일괄 처리 요청을 나중에 일괄 처리 응답을 가져오는 데 사용할 수 있는 결과로 만듭니다. LRO 결과는 14일 동안 서버 쪽에 캐시됩니다.
다음 예제에서는 일괄 처리 ID를 호출하고 일괄 처리 요청의 작업 결과를 검색하는 프로세스를 보여 줍니다.
import asyncio
import os
from azure.core.credentials import AzureKeyCredential
from azure.maps.search.aio import MapsSearchClient
async def begin_reverse_search_address_batch():
subscription_key = os.getenv("SUBSCRIPTION_KEY")
maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
async with maps_search_client:
result = await maps_search_client.begin_reverse_search_address_batch(
search_queries = [
"148.858561,2.294911",
"47.639765,-122.127896&radius=5000",
"47.61559,-122.33817&radius=5000",
]
)
return result
async def begin_reverse_search_address_batch_with_id(batch_id):
subscription_key = os.getenv("SUBSCRIPTION_KEY")
maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
async with maps_search_client:
result = await maps_search_client.begin_reverse_search_address_batch(
batch_id=batch_id,
)
responses = result._polling_method._initial_response.context.get('deserialized_data')
summary = responses['summary']
# Print Batch results
idx = 1
print(f"Total Batch Requests: {summary['totalRequests']}, Total Successful Results: {summary['successfulRequests']}")
for items in responses.get('batchItems'):
if items['statusCode'] == 200:
print(f"Request {idx} result:")
for address in items['response']['addresses']:
print(f" {address['address']['freeformAddress']}")
else:
print(f"Error in request {idx}: {items['response']['error']['message']}")
idx += 1
async def main():
result = await begin_reverse_search_address_batch()
await begin_reverse_search_address_batch_with_id(result.batch_id)
if __name__ == '__main__':
# Special handle for Windows platform
if os.name == 'nt':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
추가 정보
Python용 Azure SDK 미리 보기 설명서의 Azure Maps Search 패키지 클라이언트 라이브러리