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

PostgreSQL 14通过Python连接字符串认证失败问题求助

PostgreSQL 14与Python脚本(psycopg2/sqlalchemy)SCRAM认证失败解决思路
  • 检查psycopg2版本兼容性
    SCRAM-SHA-256认证要求psycopg2版本≥2.8,老版本不支持该协议。执行pip show psycopg2或pip show psycopg2-binary查看当前版本,低于2.8则升级:

    pip install --upgrade psycopg2-binary
    

    注:psycopg2和psycopg2-binary二选一,推荐使用binary包避免编译问题。

  • 显式指定SCRAM认证参数
    在SQLAlchemy连接字符串中明确指定SCRAM认证方式,或通过connect_args传递参数:
    方式1:连接字符串直接附加参数

    from sqlalchemy import create_engine
    engine = create_engine("postgresql+psycopg2://user:password@host:port/dbname?options=-c%20password_encryption%3Dscram-sha-256")
    

    方式2:通过connect_args设置

    engine = create_engine(
        "postgresql+psycopg2://user:password@host:port/dbname",
        connect_args={"options": "-c password_encryption=scram-sha-256"}
    )
    
  • 验证pg_hba.conf配置
    检查PostgreSQL的pg_hba.conf文件,确保对应客户端的认证规则设置为scram-sha-256,例如:

    host    all             all             0.0.0.0/0               scram-sha-256
    

    修改后重启PostgreSQL服务生效:

    sudo systemctl restart postgresql  # Linux环境
    # Windows环境可通过服务管理器重启PostgreSQL服务
    
  • 确认用户认证方式为SCRAM
    登录PostgreSQL终端,执行以下命令检查用户密码存储格式:

    SELECT usename, passwd FROM pg_shadow WHERE usename = 'user';
    

    若结果未以SCRAM-SHA-256$开头,需重置用户密码(PostgreSQL 14默认使用SCRAM,重置后会自动应用该协议):

    ALTER USER user WITH PASSWORD 'your_password';
    
  • 处理密码中的特殊字符
    若密码包含@、#、&等URL特殊字符,需进行URL编码后再放入连接字符串:

    from urllib.parse import quote_plus
    from sqlalchemy import create_engine
    
    encoded_password = quote_plus("your_password_with_special_chars")
    engine = create_engine(f"postgresql+psycopg2://user:{encoded_password}@host:port/dbname")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:25:18