You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用SQLAlchemy结合AAD认证,通过用户名密码连接PostgreSQL

使用SQLAlchemy通过Azure AD认证连接PostgreSQL

前提准备

确保你的PostgreSQL服务器已启用Azure AD认证,且你的AD组对应的PostgreSQL角色已配置好连接、查询权限。


1. 安装依赖

先安装必要的Python包:

pip install sqlalchemy psycopg2-binary azure-identity

2. 方法一:Azure AD密码认证

直接在SQLAlchemy连接URL中指定authentication=azure_ad_password参数,使用你的AAD用户邮箱和密码认证:

from sqlalchemy import create_engine

# 替换为实际信息
server = "your-postgres-server.postgres.database.azure.com"
database = "your-db-name"
aad_user = "your-aad-email@domain.com"
aad_password = "your-aad-password"

# 构建连接URL
conn_url = f"postgresql+psycopg2://{aad_user}:{aad_password}@{server}:5432/{database}?authentication=azure_ad_password"

engine = create_engine(conn_url)

# 测试连接
with engine.connect() as conn:
    print(conn.execute("SELECT 1").fetchone())

3. 方法二:Azure AD托管身份认证(适合Azure部署场景)

如果应用部署在Azure VM、App Service等支持托管身份的服务上,可使用托管身份免密码认证:

from sqlalchemy import create_engine
from azure.identity import DefaultAzureCredential
import psycopg2

# 替换为实际信息
server = "your-postgres-server.postgres.database.azure.com"
database = "your-db-name"
aad_principal = "your-ad-group-or-user-upn"  # 例如AD组名称或用户UPN

# 获取AAD令牌
credential = DefaultAzureCredential()
token = credential.get_token("https://ossrdbms-aad.database.windows.net/.default")

# 建立底层连接
conn = psycopg2.connect(
    host=server,
    database=database,
    user=aad_principal,
    password=token.token,
    port=5432,
    sslmode="require"
)

# 用SQLAlchemy包装连接
engine = create_engine("postgresql+psycopg2://", creator=lambda: conn)

# 测试连接
with engine.connect() as conn:
    print(conn.execute("SELECT 1").fetchone())

关键注意事项

  • 确认PostgreSQL服务器防火墙已放行客户端IP。
  • 确保AD组对应的PostgreSQL角色已被授予必要权限,例如:
    GRANT CONNECT ON DATABASE your-db TO your-ad-role;
    GRANT SELECT ON ALL TABLES IN SCHEMA public TO your-ad-role;
    
  • 密码认证场景下,避免硬编码密码,建议用环境变量或密钥管理工具存储。

内容的提问来源于stack exchange,提问作者David Schuler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 17:17:25