

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 IAM 身分驗證搭配 Python 連線至 Amazon Neptune 資料庫
<a name="iam-auth-connecting-python"></a>

`boto3` `neptunedata` 用戶端提供從 Python 連線至已啟用 IAM 的 Neptune 資料庫的最簡單方法。用戶端會自動處理 Signature 第 4 版簽署，因此您不需要自行簽署請求。

## 先決條件
<a name="iam-auth-connecting-python-prereqs"></a>
+ Python 3.x
+ `boto3` 程式庫： `pip install boto3`
+ AWS 透過任何標準方法設定的登入資料 （環境變數、 AWS 組態檔案、執行個體描述檔或 Lambda 執行角色）
+ 允許 Neptune 叢集上`neptune-db:*`動作的 IAM 政策

## 使用預設登入資料連線
<a name="iam-auth-connecting-python-default"></a>

此方法`boto3`可在 自動解析登入資料時運作，例如在具有執行個體描述檔的 Amazon Elastic Compute Cloud 執行個體上、 AWS Lambda 函數中或已設定的 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。若要將 SPARQL 查詢傳送至啟用 IAM 的 Neptune 資料庫，請使用 Signature 第 4 版搭配請求簽署公用程式和程式`requests`庫 () 手動簽署`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())
```

**注意**  
此範例使用 從環境變數、 AWS 組態檔案、執行個體描述檔或 Lambda 執行角色自動`botocore.session.Session`解析 AWS 登入資料。您不需要明確設定登入資料。

## 使用暫時登入資料
<a name="iam-auth-connecting-python-temp-creds"></a>

對於跨帳戶存取、有時間限制的工作階段，或作為避免長期憑證的安全最佳實務，請使用 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
<a name="iam-auth-connecting-python-lambda"></a>

在 Lambda 中，執行角色會透過 自動提供登入資料`boto3`。預設登入資料範例可在不修改的情況下運作。

如需連線管理和重試邏輯的完整 Lambda 範例，請參閱 [AWS Lambda Amazon Neptune 的 函數範例](lambda-functions-examples.md)。