使用 psycopg2 与 postgresql 连接被拒绝 - 连接到服务器“127.0.0.1”,端口 5432 失败:连接被拒绝

问题描述 投票:0回答:1

我正在使用 python fastAPI 框架来创建虚拟 API。我正在运行 PostgresSQL Server。

app = FastAPI()

try:
    connection = psycopg2.connect(host="127.0.0.1", database="fastapi", user="postgres", password="postgres", cursor_factory=RealDictCursor)
    cursor = connection.cursor()
    print("Connected to the database")
except Exception as e:
    print(e)
    # If the connection fails, the program will exit
    exit()
C:\Users\vanshmittal>pg_ctl start -D "C:\Program Files\PostgreSQL\16\data"
waiting for server to start....2024-02-17 12:16:22.273 IST [28300] LOG:  redirecting log output to logging collector process
2024-02-17 12:16:22.273 IST [28300] HINT:  Future log output will appear in directory "log".
 done
server started

C:\Users\vanshmittal>netstat -ano | findstr :5432
  TCP    127.0.0.1:5432         0.0.0.0:0              LISTENING       28300

当我在

uvicorn
启动我的
 uvicorn app.main:app --reload
网络服务器时,我得到了这个

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [7007] using statreload
**connection to server at "127.0.0.1", port 5432 failed: Connection refused
        Is the server running on that host and accepting TCP/IP connections?**

我尝试使用 Tableplus 连接 PostgreSQL 数据库,并使用与 psycopg2 相同的凭据,并且能够建立连接。

postgresql.conf
文件看起来像这样:-

listen_addresses = '127.0.0.1'      # what IP address(es) to listen on;
                    # comma-separated list of addresses;
                    # defaults to 'localhost'; use '*' for all
                    # (change requires restart)
port = 5432             # (change requires restart)
max_connections = 100           # (change requires restart)

pg_hba.conf
看起来像这样:-

# 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
# IPv6 local connections:
host    all             all             ::1/128                 scram-sha-256
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     scram-sha-256
host    replication     all             127.0.0.1/32            scram-sha-256
host    replication     all             ::1/128                 scram-sha-256
host    all             all             0.0.0.0/0               trust

我无法弄清楚为什么使用 psycopg2 的 fastAPI Web 服务器无法连接 PostgresSql 服务器?

python-3.x postgresql fastapi psycopg2
1个回答
0
投票

正如蒂姆在评论部分正确指出的那样。这篇文章帮助我解决了这个问题。

如何从 WSL 连接到 windows postgres 数据库

我没有使用

host="localhost"
,而是使用了主机 ip
host="172.25.0.1"
,这是我通过运行
grep nameserver /etc/resolv.conf | awk '{print $2}'

获得的
© www.soinside.com 2019 - 2024. All rights reserved.