我正在尝试使用 python 构建 API(使用 FastAPI)。我已经在 Windows WSL(ubuntu) 上安装了 python 我在 Windows 上有 postgress。现在我尝试通过如下所示的 python 代码连接到 Postgresssql。但连接失败,并显示 Connection returned error
代码:
try:
conn = psycopg2.connect(host='localhost',database='fastapi',password='xxxx',cursor_factory=RealDictCursor)
cursor = conn.cursor()
print("Database connection was successfull")
except Exception as error:
print("Connetion to database has failed")
print("Error", error)
错误
Connetion to database has failed
Error connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
我已经浏览了 Stackoverflow 上的以下链接,但幸运的是,您能否建议可能出现的问题。
如何从 WSL 连接到 windows postgres 数据库
按照上述链接执行的步骤
为 WSL2 IP 地址添加 Windows 防火墙入站端口规则:
配置 Postgres 以接受来自 WSL2 IP 地址的连接
假设默认安装/设置 Windows 版 Postgresql,以下文件位于
C:\Program Files\PostgresSQL\$VERSION\data
验证 postgresql.conf 是否有以下设置:
listen_addresses = '*'
这应该已经设置为“*”,所以这里什么也不做。
更新 pg_hba.conf 以允许来自 WSL2 范围的连接,例如对于 Postgresl 15:
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all scram-sha-256
# IPv4 local connections:
host all all 127.0.0.1/32 scram-sha-256
host all all 172.0.0.0/8 scram-sha-256
host all all 192.0.0.0/8 scram-sha-256
对于 Postgresql 13+,您应该使用 scram-sha-256 作为方法。
重新启动 Postgres 以使更改生效。这可以通过 Windows 服务应用程序或具有管理员权限的 cmd 来完成,例如对于 Postgresql 15:
net stop postgresql-x64-12
net start postgresql-x64-12
WSL Shell 便利
在 WSL 中,将以下内容添加到您的 ~/.bashrc 或类似内容:
# Add DNS entry for Windows host
if ! $(cat /etc/hosts | grep -q 'winhost'); then
echo 'Adding DNS entry for Windows host in /etc/hosts'
echo '\n# Windows host - added via ~/.bashhrc' | sudo tee -a /etc/hosts
echo -e "$(grep nameserver /etc/resolv.conf | awk '{print $2, " winhost"}')" | sudo tee -a /etc/hosts
fi
然后重新加载 .bashrc 更改:source ~/.bashrc
我已经安装了 psycopg2 并将其导入到代码中。
pip install psycopg2-binary
谢谢 K