如何使用 IAM Auth 在 SQLAlchemy 中使用 pg8000 强制实施 SSL 模式以进行 Cloud SQL 连接

问题描述 投票:0回答:1

我正在尝试利用 pg8000 和 IAM 身份验证建立与 Google Cloud SQL 实例的连接。我的目标是创建一个连接池并对数据库执行查询。这是我正在使用的代码片段:


def test_iam_connection():
    connector = Connector()

    # Function to get connection using IAM auth, no password required
    def getconn():
        conn = connector.connect(
            INSTANCE_CONNECTION_NAME,
            "pg8000",
            user=IAM_USER,
            db=DB_NAME,
            enable_iam_auth=True,
            ip_type=IPTypes.PRIVATE,
        )
        return conn

    # Establishing connection pool
    pool = sqlalchemy.create_engine(
        "postgresql+pg8000://",
        creator=getconn
    )

    # Initiating connection to pool
    with pool.connect() as db_conn:
        # Retrieving current datetime from the database
        results = db_conn.execute(sqlalchemy.text("SELECT NOW()")).fetchone()
        results2 = db_conn.execute(sqlalchemy.text("SELECT * from public.test")).fetchone()

        # Displaying results
        print("Current time: ", results[0])
        print("results: ", results2[0])

    # Connector cleanup
    connector.close()

if __name__ == "__main__":
    test_iam_connection()

我的问题是:如何将 sslmode=require 合并到此设置中以强制实施 SSL 连接?我正在寻找有关正确方法的指导,以确保我通过 pg8000 与 Cloud SQL 的连接使用 SSL。

在我尝试使用 SQLAlchemy 和 pg8000 强制连接到 Google Cloud SQL 实例的 SSL 模式时,我希望在连接字符串中或在创建 SQLAlchemy 引擎时通过 connect_args 参数轻松指定 sslmode=require 参数。我的目标是确保所有数据库连接都经过加密以确保安全合规性。

但是,我在直接应用 sslmode=require 参数时遇到了困难。尽管有以下示例和文档,但我无法找到直接在 pg8000 连接设置中集成此 SSL 强制执行的明确方法,尤其是在对 Google Cloud SQL 使用 IAM 身份验证时。

postgresql google-cloud-sql pg8000
1个回答
0
投票

Cloud SQL Python 连接器为数据库驱动程序创建 mTLS 连接。因此,即使您的连接字符串可能具有

sslmode=disable
sslmode=prefer
(这是默认值),您在使用 Python 连接器时始终使用加密连接。

因此,简短的回答是,Python 连接器会为您处理加密连接,并且您的应用程序可以像数据库在本地主机上运行一样进行连接。

© www.soinside.com 2019 - 2024. All rights reserved.