Azure Maps Python용 Search 패키지 클라이언트 라이브러리 - 버전 1.0.0b2

이 패키지에는 Azure Maps Services for Search용 Python SDK가 포함되어 있습니다. Azure Maps 서비스에 대한 자세한 내용은 여기를 참조하세요.

소스 코드 | API 참조 설명서 | 제품 설명서

고지 사항

Python 2.7에 대한 Azure SDK Python 패키지 지원은 2022년 1월 1일에 종료되었습니다. 자세한 내용과 질문은 을 참조하세요. https://github.com/Azure/azure-sdk-for-python/issues/20691

시작

필수 조건

Azure CLI <resource-group-name> 를 사용하는 경우 및 <account-name> 를 선택하고 매개 변수를 통해 요구 사항에 따라 적절한 가격 책정 계층<sku-name> 선택합니다. 자세한 내용은 이 페이지를 참조하세요.

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

패키지 설치

Azure Maps Service Search SDK를 설치합니다.

pip install azure-maps-search

MapsSearchClient 만들기 및 인증

Azure Maps Search API에 액세스할 클라이언트 개체를 만들려면 자격 증명 개체가 필요합니다. Azure Maps Search 클라이언트는 인증하는 두 가지 방법도 지원합니다.

1. 구독 키 자격 증명으로 인증

Azure Maps 구독 키로 인증할 수 있습니다. Azure Maps 구독 키가 만들어지면 키 값을 환경 변수AZURE_SUBSCRIPTION_KEY로 설정합니다. 그런 다음 을 AZURE_SUBSCRIPTION_KEY 매개 변수로 credentialAzureKeyCredential 인스턴스에 전달합니다.

from azure.core.credentials import AzureKeyCredential
from azure.maps.search import MapsSearchClient

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

search_client = MapsSearchClient(
    credential=credential,
)

2. Azure Active Directory 자격 증명으로 인증

Azure ID 라이브러리를 사용하여 AAD(Azure Active Directory) 토큰 자격 증명으로 인증할 수 있습니다. AAD를 사용하여 인증하려면 몇 가지 초기 설정이 필요합니다.

설치 후 사용할 자격 증명azure.identity 유형을 선택할 수 있습니다. 예를 들어 DefaultAzureCredential을 사용하여 클라이언트를 인증할 수 있습니다.

다음으로 AAD 애플리케이션의 클라이언트 ID, 테넌트 ID 및 클라이언트 암호 값을 환경 변수로 설정합니다. AZURE_CLIENT_ID, , AZURE_TENANT_IDAZURE_CLIENT_SECRET

또한 클라이언트 옵션에서 를 지정하여 사용하려는 Azure Maps 리소스를 clientId 지정해야 합니다. Azure Maps 리소스 클라이언트 ID는 Azure Maps 리소스의 인증 섹션에서 찾을 수 있습니다. 찾는 방법에 대한 설명서를 참조하세요.

from azure.maps.search import MapsSearchClient
from azure.identity import DefaultAzureCredential

credential = DefaultAzureCredential()
search_client = MapsSearchClient(credential=credential)

주요 개념

Python용 Azure Maps Search 클라이언트 라이브러리를 사용하면 전용 클라이언트 개체를 사용하여 각 구성 요소와 상호 작용할 수 있습니다.

동기화 클라이언트

MapsSearchClient는 Python용 Azure Maps Search 클라이언트 라이브러리를 사용하는 개발자를 위한 기본 클라이언트입니다. 클래스를 MapsSearchClient 초기화한 후에는 이 클라이언트 개체의 메서드를 탐색하여 액세스할 수 있는 Azure Maps Search Service 다양한 기능을 이해할 수 있습니다.

비동기 클라이언트

이 라이브러리에는 Python 3.5 이상에서 지원되는 완전한 비동기 API가 포함되어 있습니다. 이를 사용하려면 먼저 aiohttp와 같은 비동기 전송을 설치해야 합니다. 자세한 내용은 azure-core 설명서를 참조하세요.

비동기 클라이언트 및 자격 증명은 더 이상 필요하지 않은 경우 닫아야 합니다. 이러한 개체는 비동기 컨텍스트 관리자이며 비동기 close 메서드를 정의합니다.

예제

다음 섹션에서는 다음과 같은 가장 일반적인 Azure Maps Search 작업을 다루는 몇 가지 코드 조각을 제공합니다.

주소에 대한 요청 위도 및 경도 좌표

인증된 클라이언트를 사용하여 주소를 위도 및 경도 좌표로 변환할 수 있습니다. 이 프로세스를 ‘지오코딩’이라고도 합니다. 응답은 좌표뿐만 아니라 거리, 우편 번호, 시, 국가/지역 정보와 같은 자세한 주소 속성까지 반환합니다.

from azure.maps.search import MapsSearchClient

search_result = client.search_address("400 Broad, Seattle");

주소 또는 관심 지점 검색

유사 항목 검색을 사용하여 주소 또는 POI(관심 지점)를 검색할 수 있습니다. 다음 예제에서는 특정 국가의 범위에 대해 pizza 검색하는 방법을 강등합니다(France이 예제에서는).

from azure.maps.search import MapsSearchClient

fuzzy_search_result = client.fuzzy_search(query: "pizza", country_filter: "fr" );

result_address = fuzzy_search_result.results[0].address

역방향 주소 검색을 만들어 좌표 위치를 거리 주소로 변환

좌표를 사람이 읽을 수 있는 거리 주소로 변환할 수 있습니다. 이 프로세스를 역방향 지오코딩이라고도 합니다. 이는 GPS 피드를 사용하고 특정 좌표점에서 주소를 검색하려는 애플리케이션에 자주 사용됩니다.

from azure.maps.search import MapsSearchClient

coordinates=(47.60323, -122.33028)

reverse_search_result = client.reverse_search_address(coordinates=coordinates);

result_summary = reverse_search_result.summary

좌표 위치를 사람이 이해할 수 있는 교차로로 변환

Search Address Reverse Cross Street API를 사용하여 좌표 위치를 사람이 이해할 수 있는 교차로로 변환합니다. 대부분의 경우 이는 디바이스나 자산에서 GPS 피드를 수신하고 좌표의 위치를 알고자 하는 추적 애플리케이션에 필요합니다.

from azure.maps.search import MapsSearchClient

coordinates=(47.60323, -122.33028)

reverse_search_result = client.reverse_search_cross_street_address(coordinates=coordinates);

result_address = reverse_search_result.results[0].address

param 및 batchid를 사용하여 비동기 유사 항목 검색 일괄 처리 가져오기

이 샘플에서는 비동기 일괄 처리 메서드를 사용하여 위치 및 위도/lon별로 유사 항목 검색을 수행하는 방법을 보여 줍니다. 이 함수는 및 batch_id 를 모두 search_queries 수락하고 개체를 AsyncLRO 반환합니다. 여기서 를 batch_id 사용하여 나중에 지난 14일 동안 LRO 개체를 검색할 수 있습니다.

maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))

async with maps_search_client:
    result = await maps_search_client.begin_fuzzy_search_batch(
        search_queries=[
            "350 5th Ave, New York, NY 10118&limit=1",
            "400 Broad St, Seattle, WA 98109&limit=6"
        ]
    )

batch_id = result.batch_id

메서드 begin_fuzzy_search_batch() 는 매개 변수로도 허용합니다 batch_id . 여기서 를 batch_id 사용하여 나중에 지난 14일 동안 LRO 개체를 검색할 수 있습니다.

maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))

async with maps_search_client:
    result = await maps_search_client.begin_fuzzy_search_batch(
        batch_id=batch_id
    )

result = result.response

유사 항목 검색 일괄 동기화를 가져오는 데 실패

이 샘플에서는 fuzzy_search_batch 검색하는 데 오류가 있는지 확인하는 방법을 보여 줍니다.

maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))

result = maps_search_client.fuzzy_search_batch(
    search_queries=[
        "350 5th Ave, New York, NY 10118&limit=1",
        "400 Broad St, Seattle, WA 98109&lim"
    ]
)
for item in result.items:
    count = 0
    if item.response.error is not None:
        count = count+1
        print(f"Error: {item.response.error.message}")
print(f"There are total of {count} search queries failed.")

기하 도형 내부 검색

이 샘플에서는 GeoJson 개체를 사용하여 입력과 같은 pizza 지정된 대상 및 여러 다른 기하 도형을 사용하여 기하 도형 내에서 검색을 수행하는 방법을 보여 줍니다.

maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))

geo_json_obj1 = {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Polygon",
                "coordinates": [[
                    [-122.143035,47.653536],
                    [-122.187164,47.617556],
                    [-122.114981,47.570599],
                    [-122.132756,47.654009],
                    [-122.143035,47.653536]
                    ]]
            },
            "properties": {}
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [-122.126986,47.639754]
            },
            "properties": {
                "subType": "Circle",
                "radius": 100
            }
        }
    ]
}
result1 = maps_search_client.search_inside_geometry(
    query="pizza",
    geometry=geo_json_obj1
)
print("Search inside geometry with standard GeoJson object as input, FeatureCollection:")
print(result1)

이 샘플에서는 와 같은 shapely 지정된 대상 pizza에 의해 기하 도형 내에서 검색을 수행하는 등의 다른 기존 패키지로 작업하는 방법을 보여 줍니다.

maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))

from shapely.geometry import Polygon

geo_interface_obj = Polygon([
    [-122.43576049804686, 37.7524152343544],
    [-122.43301391601562, 37.70660472542312],
    [-122.36434936523438, 37.712059855877314],
    [-122.43576049804686, 37.7524152343544]
])

result3 = maps_search_client.search_inside_geometry(
    query="pizza",
    geometry=geo_interface_obj
)
print("Search inside geometry with Polygon from third party library `shapely` with geo_interface as result 3:")
print(result2)

문제 해결

일반

Maps Search 클라이언트는 Azure Core에 정의된 예외를 발생합니다.

이 목록은 throw된 예외를 catch하는 참조에 사용할 수 있습니다. 예외의 특정 오류 코드를 얻으려면 특성(예exception.error_code: )을 사용합니다error_code.

로깅

이 라이브러리는 로깅에 표준 로깅 라이브러리를 사용합니다. HTTP 세션(URL, 헤더 등)에 대한 기본 정보는 INFO 수준에서 기록됩니다.

요청/응답 본문 및 수정되지 않은 헤더를 포함한 자세한 DEBUG 수준 로깅은 인수가 있는 클라이언트 logging_enable 에서 사용하도록 설정할 수 있습니다.

import sys
import logging
from azure.maps.search import MapsSearchClient

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

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

마찬가지로 logging_enable은 클라이언트에 대해 상세 로깅을 사용하지 않는 경우에도 한 작업에만 사용하게 설정할 수 있습니다.

service_client.get_service_stats(logging_enable=True)

추가

여전히 문제가 있습니까? 버그가 발생하거나 제안이 있는 경우 프로젝트의 문제 섹션에 문제를 제출하세요.

다음 단계

추가 샘플 코드

지도 검색 샘플(비동기 버전 샘플)을 시작합니다.

SDK의 GitHub 리포지토리에서 몇 가지 Azure Maps Python SDK 검색 샘플을 사용할 수 있습니다. 이러한 샘플은 지도 검색을 사용하는 동안 일반적으로 발생하는 추가 시나리오에 대한 예제 코드를 제공합니다.

set AZURE_SUBSCRIPTION_KEY="<RealSubscriptionKey>"

pip install azure-maps-search --pre

python samples/sample_authentication.py
python sample/sample_fuzzy_search.py
python samples/sample_get_point_of_interest_categories.py
python samples/sample_reverse_search_address.py
python samples/sample_reverse_search_cross_street_address.py
python samples/sample_search_nearby_point_of_interest.py
python samples/sample_search_point_of_interest_category.py
python samples/sample_search_point_of_interest.py
python samples/sample_search_structured_address.py

참고: --pre 플래그는 필요에 따라 추가할 수 있으며, 에 대한 시험판 및 개발 버전을 포함해야 합니다 pip install. 기본적으로 는 pip 안정적인 버전만 찾습니다.

자세한 내용은 샘플 소개를 참조하세요.

추가 설명서

Azure Maps Search에 대한 자세한 설명서는 docs.microsoft.com Azure Maps Search 설명서를 참조하세요.

참여

이 프로젝트에 대한 기여와 제안을 환영합니다. 대부분의 경우 기여하려면 권한을 부여하며 실제로 기여를 사용할 권한을 당사에 부여한다고 선언하는 CLA(기여자 라이선스 계약)에 동의해야 합니다. 자세한 내용은 https://cla.microsoft.com 을 참조하세요.

끌어오기 요청을 제출하면 CLA-bot은 CLA를 제공하고 PR을 적절하게 데코레이팅해야 하는지 여부를 자동으로 결정합니다(예: 레이블, 설명). 봇에서 제공하는 지침을 따르기만 하면 됩니다. 이 작업은 CLA를 사용하여 모든 리포지토리에서 한 번만 수행하면 됩니다.

이 프로젝트에는 Microsoft Open Source Code of Conduct(Microsoft 오픈 소스 준수 사항)가 적용됩니다. 자세한 내용은 Code of Conduct FAQ(규정 FAQ)를 참조하세요. 또는 추가 질문이나 의견은 opencode@microsoft.com으로 문의하세요.