

# 适用于 Python 的 Aurora DSQL 连接器
<a name="SECTION_program-with-dsql-connector-for-python"></a>

 [Aurora DSQL Connector for Python](https://github.com/awslabs/aurora-dsql-connectors/tree/main/python/connector) 集成了 IAM 身份验证，用于将 Python 应用程序连接到 Amazon Aurora DSQL 集群。其内部采用 [psycopg](https://github.com/psycopg/psycopg)、[psycopg2](https://github.com/psycopg/psycopg2) 和 [asyncpg](https://github.com/MagicStack/asyncpg) 客户端库。

 经设计，适用于 Python 的 Aurora DSQL 连接器可作为身份验证插件，对 psycopg、psycopg2 和 asyncpg 客户端库的功能进行扩展，使应用程序能够使用 IAM 凭证与 Amazon Aurora DSQL 进行身份验证。该连接器不直接连接到数据库，而是在底层客户端库之上，提供无缝的 IAM 身份验证。

## 关于连接器
<a name="about-the-connector"></a>

 Amazon Aurora DSQL 是一种分布式 SQL 数据库服务，面向兼容 PostgreSQL 的应用程序提供高可用性和可扩展性。Aurora DSQL 要求使用基于 IAM 的身份验证以及限时令牌，而现有 Python 库本身不支持这种方法。

 设计适用于 Python 的 Aurora DSQL 连接器的理念是，在 psycopg、psycopg2 和 asyncpg 客户端库之上添加一个身份验证层来处理 IAM 令牌生成，使得用户无需更改现有工作流即可连接到 Aurora DSQL。

### 什么是 Aurora DSQL 身份验证？
<a name="what-is-aurora-dsql-authentication"></a>

 在 Aurora DSQL 中，身份验证包括：
+  **IAM 身份验证**：所有连接都使用基于 IAM 的身份验证和限时令牌 
+  **令牌生成：**使用 AWS 凭证生成身份验证令牌，其生命周期可配置 

 适用于 Python 的 Aurora DSQL 连接器针对这些要求而设计，在建立连接时自动生成 IAM 身份验证令牌。

### 功能
<a name="features"></a>
+  **自动 IAM 身份验证**：通过 AWS 凭证自动生成 IAM 令牌 
+  **基于 psycopg、psycopg2 和 asyncpg 构建**：借助 psycopg、psycopg2 和 asyncpg 客户端库 
+  **无缝集成**：适用于现有的 psycopg、psycopg2 和 asyncpg 连接模式，而无需更改工作流 
+  **区域自动发现**：从 DSQL 集群主机名中提取 AWS 区域 
+  **AWS 凭证支持**：支持各种 AWS 凭证提供者（默认、基于配置文件、自定义） 
+  **连接池兼容性**：适用于 psycopg、psycopg2 和 asyncpg 内置连接池 

## 快速入门指南
<a name="quick-start-guide"></a>

### 要求
<a name="requirements"></a>
+  Python 3.10 或更高版本 
+  [有权访问 Aurora DSQL 集群](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/getting-started.html) 
+  设置适当的 IAM 权限，以允许应用程序连接到 Aurora DSQL。
+  已配置 AWS 凭证（通过 AWS CLI、环境变量或 IAM 角色）。

### 安装
<a name="installation"></a>

```
pip install aurora-dsql-python-connector
```

#### 单独安装 psycopg、psycopg2 或 asyncpg
<a name="install-psycopg-or-psycopg2-or-asyncpg-separately"></a>

 适用于 Python 的 Aurora DSQL 连接器安装程序不会安装底层库。这些库需要单独安装，例如：

```
# Install psycopg and psycopg pool
pip install "psycopg[binary,pool]"
```

```
# Install psycopg2
pip install psycopg2-binary
```

```
# Install asyncpg
pip install asyncpg
```

 **注意。**

 只需安装所需的库。因此，如果客户端将使用 psycopg，则只需安装 psycopg。如果客户端将使用 psycopg2，则只需安装 psycopg2。如果客户端将使用 asyncpg，则只需安装 asyncpg。

 如果客户端需要使用多个库，则需安装全部所需的库。

### 基本用法
<a name="basic-usage"></a>

#### psycopg
<a name="psycopg"></a>

```
    import aurora_dsql_psycopg as dsql

    config = {
        'host': "your-cluster.dsql.us-east-1.on.aws",
        'region': "us-east-1",
        'user': "admin",
    }
        
    conn = dsql.connect(**config)
    with conn.cursor() as cur:
        cur.execute("SELECT 1")
        result = cur.fetchone()
        print(result)
```

#### psycopg2
<a name="psycopg2"></a>

```
    import aurora_dsql_psycopg2 as dsql

    config = {
        'host': "your-cluster.dsql.us-east-1.on.aws",
        'region': "us-east-1",
        'user': "admin",
    }
        
    conn = dsql.connect(**config)
    with conn.cursor() as cur:
        cur.execute("SELECT 1")
        result = cur.fetchone()
        print(result)
```

#### asyncpg
<a name="asyncpg"></a>

```
    import asyncio 
    import aurora_dsql_asyncpg as dsql 

    config = {
        'host': "your-cluster.dsql.us-east-1.on.aws",
        'region': "us-east-1",
        'user': "admin",
    }

    conn = await dsql.connect(**config)
    result = await conn.fetchrow("SELECT 1")
    await conn.close()
    print(result)
```

#### 仅使用主机
<a name="using-just-host"></a>

##### psycopg
<a name="psycopg-1"></a>

```
    import aurora_dsql_psycopg as dsql

    conn = dsql.connect("your-cluster.dsql.us-east-1.on.aws")
```

##### psycopg2
<a name="psycopg2-1"></a>

```
    import aurora_dsql_psycopg2 as dsql

    conn = dsql.connect("your-cluster.dsql.us-east-1.on.aws")
```

##### asyncpg
<a name="asyncpg-1"></a>

```
    import asyncio 
    import aurora_dsql_asyncpg as dsql 

    conn = await dsql.connect("your-cluster.dsql.us-east-1.on.aws")
```

#### 仅使用集群 ID
<a name="using-just-cluster-id"></a>

##### psycopg
<a name="psycopg-2"></a>

```
    import aurora_dsql_psycopg as dsql

    conn = dsql.connect("your-cluster")
```

##### psycopg2
<a name="psycopg2-2"></a>

```
    import aurora_dsql_psycopg2 as dsql

    conn = dsql.connect("your-cluster")
```

##### asyncpg
<a name="asyncpg-2"></a>

```
    import asyncio 
    import aurora_dsql_asyncpg as dsql 

    conn = await dsql.connect("your-cluster")
```

 **注意。**

 在“仅使用集群 ID”场景中，将使用之前在机器上设置的区域，例如：

```
aws configure set region us-east-1
```

 如果尚未设置区域，或给定的集群 ID 位于其他区域，则连接将失败。如需正常连接，请将区域作为参数提供，如以下示例中所示：

##### psycopg
<a name="psycopg-3"></a>

```
    import aurora_dsql_psycopg as dsql

    config = {
            "region": "us-east-1",
    }

    conn = dsql.connect("your-cluster", **config)
```

##### psycopg2
<a name="psycopg2-3"></a>

```
    import aurora_dsql_psycopg2 as dsql

    config = {
            "region": "us-east-1",
    }

    conn = dsql.connect("your-cluster", **config)
```

##### asyncpg
<a name="asyncpg-3"></a>

```
    import asyncio 
    import aurora_dsql_asyncpg as dsql 

    config = {
            "region": "us-east-1",
    }

    conn = await dsql.connect("your-cluster", **config)
```

### 连接字符串
<a name="connection-string"></a>

#### psycopg
<a name="psycopg-4"></a>

```
    import aurora_dsql_psycopg as dsql

    conn = dsql.connect("postgresql://your-cluster.dsql.us-east-1.on.aws/postgres?user=admin&token_duration_secs=15")
```

#### psycopg2
<a name="psycopg2-4"></a>

```
    import aurora_dsql_psycopg2 as dsql

    conn = dsql.connect("postgresql://your-cluster.dsql.us-east-1.on.aws/postgres?user=admin&token_duration_secs=15")
```

#### asyncpg
<a name="asyncpg-4"></a>

```
    import asyncio 
    import aurora_dsql_asyncpg as dsql 

    conn = await dsql.connect("postgresql://your-cluster.dsql.us-east-1.on.aws/postgres?user=admin&token_duration_secs=15")
```

### 高级配置
<a name="advanced-configuration"></a>

#### psycopg
<a name="psycopg-5"></a>

```
    import aurora_dsql_psycopg as dsql

    config = {
        'host': "your-cluster.dsql.us-east-1.on.aws",
        'region': "us-east-1",
        'user': "admin",
        "profile": "default",
        "token_duration_secs": "15",
    }
        
    conn = dsql.connect(**config)
    with conn.cursor() as cur:
        cur.execute("SELECT 1")
        result = cur.fetchone()
        print(result)
```

#### psycopg2
<a name="psycopg2-5"></a>

```
    import aurora_dsql_psycopg2 as dsql

    config = {
        'host': "your-cluster.dsql.us-east-1.on.aws",
        'region': "us-east-1",
        'user': "admin",
        "profile": "default",
        "token_duration_secs": "15",
    }
        
    conn = dsql.connect(**config)
    with conn.cursor() as cur:
        cur.execute("SELECT 1")
        result = cur.fetchone()
        print(result)
```

#### asyncpg
<a name="asyncpg-5"></a>

```
    import asyncio 
    import aurora_dsql_asyncpg as dsql 

    config = {
        'host': "your-cluster.dsql.us-east-1.on.aws",
        'region': "us-east-1",
        'user': "admin",
        "profile": "default",
        "token_duration_secs": "15",
    }

    conn = await dsql.connect(**config)
    result = await conn.fetchrow("SELECT 1")
    await conn.close()
    print(result)
```

### 配置选项
<a name="configuration-options"></a>


|  Option  |  类型  |  必需  |  描述  | 
| --- | --- | --- | --- | 
|  host  |  string  |  是  |  DSQL 集群主机名或集群 ID  | 
|  user  |  string  |  否  |  DSQL 用户名。默认值：admin  | 
|  dbname  |  string  |  否  |  数据库名称。默认值：postgres  | 
|  region  |  string  |  否  |  AWS 区域（如果未提供，则自动从主机名中检测）  | 
|  port  |  int  |  否  |  默认值为 5432  | 
|  custom\_credentials\_provider  |  CredentialProvider  |  否  |  自定义 AWS 凭证提供者  | 
|  profile  |  string  |  否  |  IAM 配置文件名称。默认值：default。 | 
|  token\_duration\_secs  |  int  |  否  |  令牌过期时间（以秒为单位）  | 

 此外，底层 psycopg、psycopg2 及 asyncpg 库的所有标准连接选项均受支持，但 DSQL 不支持的 asyncpg 参数 **krbsrvname** 和 **gsslib** 例外。

### 将适用于 Python 的 Aurora DSQL 连接器与连接池结合使用
<a name="using-the-aurora-dsql-connector-for-python-with-connection-pooling"></a>

 适用于 Python 的 Aurora DSQL 连接器可与 psycopg、psycopg2 和 asyncpg 内置连接池结合使用。连接器在建立连接期间处理 IAM 令牌生成，使得连接池可以正常操作。

#### psycopg
<a name="psycopg-6"></a>

 对于 psycopg，该连接器实现了一个名为 DSQLConnection 的连接类，该类可以直接传递给 psycopg\_pool.ConnectionPool 构造函数。对于异步操作，还提供了该类的异步版本 DSQLAsyncConnection。

```
    from psycopg_pool import ConnectionPool as PsycopgPool
    
    ...
    pool = PsycopgPool(
        "",  
        connection_class=dsql.DSQLConnection,
        kwargs=conn_params,
        min_size=2,
        max_size=8,
        max_lifetime=3300
    )
```

 **注意：连接 max\_Lifetime 配置** 

 max\_lifetime 参数应设置为小于 3600 秒（1 小时），因为这是 Aurora DSQL 数据库允许的最大连接持续时间。通过将 max\_lifetime 设置为更低的值，可让连接池主动管理连接回收，这比处理数据库引发的连接超时错误更高效。

#### psycopg2
<a name="psycopg2-6"></a>

 对于 psycopg2，该连接器提供了一个名为 AuroraDSQLThreadedConnectionPool 的类，此类继承自 psycopg2.pool.ThreadedConnectionPool。AuroraDSQLThreadedConnectionPool 类只能覆盖内部 \_connect 方法。实施的其余部分由 psycopg2.pool.ThreadedConnectionPool 提供，保持不变。

```
    import aurora_dsql_psycopg2 as dsql

    pool = dsql.AuroraDSQLThreadedConnectionPool(
            minconn=2,
            maxconn=8,
            **conn_params,
    )
```

#### asyncpg
<a name="asyncpg-6"></a>

 对于 asyncpg，该连接器提供了一个 create\_pool 函数，该函数可返回 asyncpg.Pool 的实例。

```
    import asyncio
    import os

    import aurora_dsql_asyncpg as dsql

    pool_params = {
        'host': "your-cluster.dsql.us-east-1.on.aws",
        'user': "admin",
        "min_size": 2,
        "max_size": 5,
    }

    pool = await dsql.create_pool(**pool_params)
```

## 身份验证
<a name="authentication"></a>

 该连接器通过使用 DSQL 客户端令牌生成器生成令牌来自动处理 DSQL 身份验证。如果未提供 AWS 区域，系统会自动从提供的主机名中解析该区域。

 有关 Aurora DSQL 中的身份验证的更多信息，请参阅[用户指南](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/authentication-authorization.html)。

### 管理员用户与普通用户
<a name="admin-vs-regular-users"></a>
+  名为 `"admin"` 的用户会自动使用管理员身份验证令牌 
+  所有其他用户都使用非管理员身份验证令牌 
+  令牌将为每个连接动态生成 

## 示例
<a name="examples"></a>

 有关完整示例代码，请参阅以下各部分中所示的示例。有关如何运行示例的说明，请参阅示例 READMDE 文件。

### psycopg
<a name="psycopg-7"></a>

 [示例 README](https://github.com/awslabs/aurora-dsql-connectors/blob/main/python/connector/examples/psycopg/README.md) 


|  说明  |  示例  | 
| --- | --- | 
|  使用适用于 Python 的 Aurora DSQL 连接器进行基本连接  |  [基本连接示例](https://github.com/awslabs/aurora-dsql-connectors/tree/main/python/connector/examples/psycopg/src/example_preferred.py)  | 
|  使用适用于 Python 的 Aurora DSQL 连接器进行基本异步连接  |  [基本异步连接示例](https://github.com/awslabs/aurora-dsql-connectors/tree/main/python/connector/examples/psycopg/src/alternatives/no_connection_pool/example_async_with_no_connection_pool.py)  | 
|  将适用于 Python 的 Aurora DSQL 连接器与连接池结合使用  |  [带连接池的基本连接示例](https://github.com/awslabs/aurora-dsql-connectors/tree/main/python/connector/examples/psycopg/src/alternatives/pool/example_with_nonconcurrent_connection_pool.py)  | 
|   |  [带连接池的并发连接示例](https://github.com/awslabs/aurora-dsql-connectors/tree/main/python/connector/examples/psycopg/src/example_preferred.py)  | 
|  将适用于 Python 的 Aurora DSQL 连接器与异步连接池结合使用  |  [带异步连接池的基本连接示例](https://github.com/awslabs/aurora-dsql-connectors/tree/main/python/connector/examples/psycopg/src/alternatives/pool/example_with_async_connection_pool.py)  | 

### psycopg2
<a name="psycopg2-7"></a>

 [示例 README](https://github.com/awslabs/aurora-dsql-connectors/blob/main/python/connector/examples/psycopg2/README.md) 


|  说明  |  示例  | 
| --- | --- | 
|  使用适用于 Python 的 Aurora DSQL 连接器进行基本连接  |  [基本连接示例](https://github.com/awslabs/aurora-dsql-connectors/tree/main/python/connector/examples/psycopg2/src/example_preferred.py)  | 
|  将适用于 Python 的 Aurora DSQL 连接器与连接池结合使用  |  [带连接池的基本连接示例](https://github.com/awslabs/aurora-dsql-connectors/tree/main/python/connector/examples/psycopg2/src/alternatives/pool/example_with_nonconcurrent_connection_pool.py)  | 
|   |  [带连接池的并发连接示例](https://github.com/awslabs/aurora-dsql-connectors/tree/main/python/connector/examples/psycopg2/src/example_preferred.py)  | 

### asyncpg
<a name="asyncpg-7"></a>

 [示例 README](https://github.com/awslabs/aurora-dsql-connectors/blob/main/python/connector/examples/asyncpg/README.md) 


|  说明  |  示例  | 
| --- | --- | 
|  使用适用于 Python 的 Aurora DSQL 连接器进行基本连接  |  [基本连接示例](https://github.com/awslabs/aurora-dsql-connectors/tree/main/python/connector/examples/asyncpg/src/example_preferred.py)  | 
|  将适用于 Python 的 Aurora DSQL 连接器与连接池结合使用  |  [带连接池的基本连接示例](https://github.com/awslabs/aurora-dsql-connectors/tree/main/python/connector/examples/asyncpg/src/alternatives/pool/example_with_nonconcurrent_connection_pool.py)  | 
|   |  [带连接池的并发连接示例](https://github.com/awslabs/aurora-dsql-connectors/tree/main/python/connector/examples/asyncpg/src/example_preferred.py)  | 