View a markdown version of this page

Connessione ai database Amazon Neptune tramite l'autenticazione IAM con Python - Amazon Neptune

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Connessione ai database Amazon Neptune tramite l'autenticazione IAM con Python

Il boto3 neptunedata il client fornisce il modo più semplice per connettersi a un IAM-enabled Database Neptune di Python. Il client gestisce automaticamente la firma di Signature Version 4, quindi non è necessario firmare personalmente le richieste.

Prerequisiti

  • Python 3.x

  • Il boto3 biblioteca: pip install boto3

  • AWS credenziali configurate tramite qualsiasi metodo standard (variabili di ambiente, AWS file di configurazione, profilo di istanza o ruolo di esecuzione Lambda)

  • Una policy IAM che consente neptune-db:* azioni sul tuo cluster Neptune

Connessione con credenziali predefinite

Questo approccio funziona quando boto3 può risolvere automaticamente le credenziali, ad esempio nelle istanze Amazon Elastic Compute Cloud con profili di istanza, in AWS Lambda funzioni o con configurato AWS profili.

Sostituisci l'URL dell'endpoint con l'endpoint del tuo cluster Neptune.

Gremlin e 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

Il boto3 neptunedata il client attualmente non supporta SPARQL. Per inviare interrogazioni SPARQL a un IAM-enabled Database Neptune, firma le richieste manualmente utilizzando Signature Version 4 con botocore utilità per la firma delle richieste e requests libreria (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())
Nota

Questo esempio utilizza botocore.session.Session da risolvere AWS credenziali automaticamente dalle variabili di ambiente, AWS file di configurazione, profili di istanza o ruoli di esecuzione Lambda. Non è necessario impostare le credenziali in modo esplicito.

Utilizzo di credenziali temporanee

Per l'accesso tra più account, sessioni limitate nel tempo o come best practice di sicurezza per evitare credenziali di lunga durata, utilizza AWS STS per ottenere credenziali temporanee e creare un boto3.Session.

Gremlin e 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'])
Nota

Le credenziali temporanee scadono dopo un intervallo specificato (il valore predefinito è 1 ora) e non vengono aggiornate automaticamente dal client. Per le applicazioni a lunga durata, utilizza invece credenziali o profili di istanza basati sul profilo.

SPARQL

Perché boto3 neptunedata il client attualmente non supporta SPARQL, è necessario firmare le richieste manualmente con le credenziali temporanee.

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())

Usando con AWS Lambda

In Lambda, il ruolo di esecuzione fornisce automaticamente le credenziali tramite boto3. L'esempio delle credenziali predefinite funziona senza modifiche.

Per un esempio completo di Lambda con gestione delle connessioni e logica dei tentativi, vedi AWS Lambda esempi di funzioni per Amazon Neptune.