【问题标题】:How do I connect to Postgresql using SSL from SqlAchemy+pg8000?如何使用来自 SqlAchemy+pg8000 的 SSL 连接到 Postgresql?
【发布时间】:2014-09-25 13:32:02
【问题描述】:

从 SqlAlchemy 通过 pg8000 连接到 postgres 工作正常,直到我在 postgres 上启用 SSL。

db = create_engine('postgresql+pg8000://user:pass@hostname/dbname', echo=True).connect()

现在它似乎失败了:

File "/Library/Python/2.7/site-packages/pg8000/core.py", line 872, in __init__
raise InterfaceError("communication error", exc_info()[1])
sqlalchemy.exc.InterfaceError: (InterfaceError) ('communication error', error(61, 'Connection refused')) None None

【问题讨论】:

    标签: python sqlalchemy pg8000


    【解决方案1】:

    可能你需要添加connect_args dict:

    db = create_engine('postgresql+pg8000://user:pass@hostname/dbname', connect_args={'sslmode':'require'}, echo=True).connect()
    

    【讨论】:

    • 事实上,它似乎能够自行破坏 sslmode,因为我连接到错误的主机。尽管如此,知道如何执行 SSL 模式还是很好的。谢谢。
    • 请注意,这可以更容易地内联声明:create_engine('postgresql+pg8000://user:pass@hostname/dbname?sslmode=require')
    【解决方案2】:

    接受的答案不再有效,至少在这些版本中:

    Python                   3.9
    pg8000                   1.19.5
    SQLAlchemy               1.4.12
    

    pg8000 docs 描述了您必须做什么。使用

    engine = create_engine('postgresql+pg8000://user:password@host/db', 
                           connect_args={'ssl_context': True})
    

    将ssl.create_default_context() 的结果传递给连接创建者。如果需要自定义 SSL 上下文,请将其作为值而不是 True 传递:

    import ssl
    
    ssl_context = ssl.SSLContext()
    # Set attributes as required  ...
    
    engine = create_engine('postgresql+pg8000://user:password@host/db', 
                           connect_args={'ssl_context': ssl_context})
    

    【讨论】:

      【解决方案3】:

      对我没用...我用过:

      engine = create_engine('postgresql+pg8000://user:password@host/db', connect_args={'ssl': {'ssl-mode': 'required'}})
      

      【讨论】:

        猜你喜欢
        • 2014-09-07
        • 2016-12-24
        • 1970-01-01
        • 2023-02-02
        • 2019-06-12
        • 1970-01-01
        • 2023-01-29
        • 2019-12-30
        • 1970-01-01
        相关资源
        最近更新 更多