如何通过SqlAlchemy+pg8000使用SSL连接Postgresql?

14 投票
2 回答
26489 浏览
提问于 2025-04-18 15:44

通过pg8000从SqlAlchemy连接到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

2 个回答

6

这个被接受的答案现在不再有效,至少在这些版本上是这样:

Python                   3.9
pg8000                   1.19.5
SQLAlchemy               1.4.12

pg8000 的文档里说明了你需要做什么。使用

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})
18

你需要添加一个 connect_args 字典:

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

撰写回答