如何使用 OAuth2 将 SQLAlchemy 连接到 Snowflake 数据库?

How to connect SQLAlchemy to Snowflake database using OAuth2?

我需要使用 SQLAlchemy 连接到 Snowflake,但诀窍是,我需要使用 OAuth2 进行身份验证。 Snowflake 文档仅描述了使用用户名和密码进行连接,这不能用于我正在构建的解决方案。我可以使用 Snowflake 的 python 连接器进行身份验证,但我看不到如何将它与 SQLAlchemy 粘合的简单路径。在为此编写自定义接口之前,我想知道是否有现成的解决方案。

使用 snowflake.connector.connect 创建到数据库的 PEP-249 连接 - see documentation. Then use param creator of create_engine (docs) - 它需要一个可调用的 returns PEP-249 连接。如果您使用它,那么 URL 参数将被忽略。

示例代码:

def get_connection():
    return snowflake.connector.connect(
        user="<username>",
        host="<hostname>",
        account="<account_identifier>",
        authenticator="oauth",
        token="<oauth_access_token>",
        warehouse="test_warehouse",
        database="test_db",
        schema="test_schema"
    )
engine = create_engine("snowflake://not@used/db", creator=get_connection)