朋友们,
我正在尝试从 EC2 计算机中运行的 python 脚本连接到 AWS RDS 中的 Postgres 实例。它与 psycopg2/sqlalchemy 配合良好
from sqlalchemy import create_engine
import psycopg2
db_string = 'postgresql+psycopg2://{user}:{password}@{host}:5432/{database}'.format(
user=DB_USER,
password=DB_PASS,
host=DB_HOST,
database=DB_NAME)
engine = create_engine(db_string, echo=True)
conn = engine.connect()
但是当我使用 pg8000/sqlalchemy 作为时失败了
from sqlalchemy import create_engine
import pg8000
db_string = 'postgresql+pg8000://{user}:{password}@{host}:5432/{database}'.format(
user=DB_USER,
password=DB_PASS,
host=DB_HOST,
database=DB_NAME)
engine = create_engine(db_string, echo=True)
conn = engine.connect()
错误信息是
InterfaceError: (pg8000.exceptions.InterfaceError) {'S': 'FATAL', 'V': 'FATAL', 'C': '28000', 'M': 'no pg_hba.conf entry for host "*.*.*.*", user "*", database "*", SSL off', 'F': 'auth.c', 'L': '513', 'R': 'ClientAuthentication'}
(Background on this error at: http://sqlalche.me/e/14/rvf5)
我也尝试设置
connect_args={'ssl_context': True}
但仍然连接失败。有人有什么想法吗?我正在使用 python v3.6、sqlalchemy v1.4.15 和 pg8000 v1.19.4。
谢谢你。
ssl_context
键的值通常使用 ssl.create_default_context()
创建。
默认使用信任系统默认的CA证书。您还可以下载 AWS 的证书捆绑包(全局证书捆绑包或区域特定变体之一)。请参阅 https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/UsingWithRDS.SSL.html#UsingWithRDS.SSL。证书所有地区)。然后设置参数
cafile
。例如。像这样的东西:
import ssl
from os import path
# This snippet uses sqlmodel's create_engine which uses sqlalchemy under the hood.
from sqlmodel import Session, create_engine
# assume that the PEM file is in the same directory as current python script file.
ssl_server_certs_path = path.join(path.dirname(__file__), "global-bundle.pem")
engine = create_engine(
config_uri,
connect_args={"ssl_context": ssl.create_default_context(cafile=ssl_server_certs_path)})