

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 通过 Python 使用 IAM 身份验证连接到 Amazon Neptune 数据库
<a name="iam-auth-connecting-python"></a>

`boto3``neptunedata`客户端提供了从 Python 连接到 IAM-enabled Neptune 数据库的最简单方法。客户端会自动处理签名版本 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`可以自动解析凭证的情况，例如在具有实例配置文件、 AWS Lambda 函数或配置 AWS 配置文件的 Amazon Elastic Compute Cloud 实例上。

将终端节点 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 查询发送到 Nep IAM-enabled tune 数据库，请使用带有请求签名实用程序和`requests`库 () `botocore` 的签名版本 4 来手动签署请求。`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 证书。您无需明确设置凭证。

## 使用临时凭证
<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 亚马逊 Neptune 的函数示例](lambda-functions-examples.md)