기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
Python을 사용한 IAM 인증을 사용하여 Amazon Neptune 데이터베이스에 연결
boto3 neptunedata 클라이언트는 Python에서 IAM 지원 Neptune 데이터베이스에 연결하는 가장 간단한 방법을 제공합니다. 클라이언트는 서명 버전 4 서명을 자동으로 처리하므로 요청에 직접 서명할 필요가 없습니다.
사전 조건
Python 3.x
boto3라이브러리:pip install boto3AWS 표준 메서드(환경 변수, AWS 구성 파일, 인스턴스 프로파일 또는 Lambda 실행 역할)를 통해 구성된 자격 증명
Neptune 클러스터에서
neptune-db:*작업을 허용하는 IAM 정책
기본 자격 증명으로 연결
이 접근 방식은 boto3가 인스턴스 프로파일, AWS Lambda 함수 또는 구성된 프로파일이 있는 Amazon Elastic Compute Cloud 인스턴스에서와 같이 자격 증명을 자동으로 확인할 수 있는 경우에 작동합니다 AWS .
엔드포인트 URL을 Neptune 클러스터 엔드포인트로 바꿉니다.
Gremlin 및 openCypher
import boto3 from botocore.config import Config cfg = Config(retries={"total_max_attempts": 1, "mode": "standard"}, read_timeout=None) neptune = boto3.client('neptunedata', config=cfg, region_name='us-east-1', endpoint_url='https://your-neptune-endpoint:8182') # Gremlin resp = neptune.execute_gremlin_query(gremlinQuery='g.V().limit(1)') print(resp['result']) # openCypher resp = neptune.execute_open_cypher_query(openCypherQuery='MATCH (n) RETURN n LIMIT 1') print(resp['results'])
SPARQL
boto3 neptunedata 클라이언트는 현재 SPARQL을 지원하지 않습니다. IAM 지원 Neptune 데이터베이스에 SPARQL 쿼리를 보내려면 요청 서명 유틸리티 및 requests 라이브러리()와 함께 서명 버전 4를 사용하여 botocore 요청에 수동으로 서명합니다pip install boto3 requests.
import requests from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest from botocore.session import Session endpoint = 'https://your-neptune-endpoint:8182' region = 'us-east-1' query = 'SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 1' request = AWSRequest(method='POST', url=f'{endpoint}/sparql/', data={'query': query}) SigV4Auth(Session().get_credentials(), 'neptune-db', region).add_auth(request) resp = requests.post(f'{endpoint}/sparql/', headers=request.headers, data={'query': query}) print(resp.json())
참고
이 예제에서는 botocore.session.Session를 사용하여 환경 변수, AWS 구성 파일, 인스턴스 프로파일 또는 Lambda 실행 역할에서 자격 AWS 증명을 자동으로 확인합니다. 자격 증명을 명시적으로 설정할 필요는 없습니다.
임시 자격 증명 사용
계정 간 액세스, 시간 제한 세션 또는 수명이 긴 자격 증명을 방지하기 위한 보안 모범 사례로 AWS STS 를 사용하여 임시 자격 증명을 얻고를 생성합니다boto3.Session.
Gremlin 및 openCypher
import boto3 from botocore.config import Config sts = boto3.client('sts') creds = sts.assume_role( RoleArn='arn:aws:iam::123456789012:role/NeptuneRole', RoleSessionName='neptune-session' )['Credentials'] session = boto3.Session( aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken'], region_name='us-east-1' ) cfg = Config(retries={"total_max_attempts": 1, "mode": "standard"}, read_timeout=None) neptune = session.client('neptunedata', config=cfg, endpoint_url='https://your-neptune-endpoint:8182') # Gremlin resp = neptune.execute_gremlin_query(gremlinQuery='g.V().limit(1)') print(resp['result']) # openCypher resp = neptune.execute_open_cypher_query(openCypherQuery='MATCH (n) RETURN n LIMIT 1') print(resp['results'])
참고
임시 자격 증명은 지정된 간격(기본값은 1시간) 후에 만료되며 클라이언트에 의해 자동으로 새로 고쳐지지 않습니다. 장기 실행 애플리케이션의 경우 프로파일 기반 자격 증명 또는 인스턴스 프로파일을 대신 사용합니다.
SPARQL
boto3 neptunedata 클라이언트는 현재 SPARQL을 지원하지 않으므로 임시 자격 증명을 사용하여 요청에 수동으로 서명해야 합니다.
import boto3 import requests from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest from botocore.credentials import ReadOnlyCredentials sts = boto3.client('sts') creds = sts.assume_role( RoleArn='arn:aws:iam::123456789012:role/NeptuneRole', RoleSessionName='neptune-session' )['Credentials'] endpoint = 'https://your-neptune-endpoint:8182' region = 'us-east-1' query = 'SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 1' request = AWSRequest(method='POST', url=f'{endpoint}/sparql/', data={'query': query}) SigV4Auth(ReadOnlyCredentials( creds['AccessKeyId'], creds['SecretAccessKey'], creds['SessionToken'] ), 'neptune-db', region).add_auth(request) resp = requests.post(f'{endpoint}/sparql/', headers=request.headers, data={'query': query}) print(resp.json())
와 함께 AWS Lambda사용
Lambda에서 실행 역할은를 통해 자격 증명을 자동으로 제공합니다boto3. 기본 자격 증명 예제는 수정 없이 작동합니다.
연결 관리 및 재시도 로직이 포함된 전체 Lambda 예제는 섹션을 참조하세요AWS Lambda Amazon Neptune의 함수 예제.