Can not connect to Postgresql running at different port using Python

1

I have Postgres up and running on one of my machines. Its pg_hba.conf contains this string:

host    all             all             0.0.0.0/0               md5

And postgresql.conf contains these lines:

listen_addresses = '*'
port = 5433

The machine on my local network has this IP address 192.168.234.137. I try to connect to Postgres from another machine. If I use for example Navicat, then I can easily establish connection, so Postgres running at port 5433 is reachable. When, however, I try to connect to it using Python, I get an error message

Is the server running on host "192.168.234.137" and accepting
TCP/IP connections on port 5433?

If I switch back to port 5432 - fix postgresql.conf and restart Postgres - then my Python script starts working. So it seems like Python (I tried psycopg2 and sqlalchemy) for some reason is bound by this 5432 port number and does not accept other port numbers. What is wrong with that and how can I fix it? I guess, simply changing postgresql.conf and restarting Postgres is not enough.

PS.

The code, I run, looks like so:

>>> connection = psycopg2.connect(user = "postgres",
...                                   password = "postgres",
...                                   host = "192.168.234.137",
...                                   port = "5433",
...                                   database = "test")
Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
  File "C:\Python34\lib\site-packages\psycopg2-2.6.1-py3.4-win-amd64.egg   \psycopg2\__init__.py", line 164, in connect
    conn = _connect(dsn, connection_factory=connection_factory, async=async)
psycopg2.OperationalError: could not connect to server: Connection timed out (0x0000274C/10060)
    Is the server running on host "192.168.234.137" and accepting
    TCP/IP connections on port 5433?
python
postgresql
asked on Stack Overflow Feb 22, 2020 by Jacobian • edited Feb 22, 2020 by Jacobian

2 Answers

2

The port needs to be specified as an integer, not a string. When the connect() method was changed to the following, it worked.

>>> connection = psycopg2.connect(user = "postgres",
...                                   password = "postgres",
...                                   host = "192.168.234.137",
...                                   port = 5433,
...                                   database = "test")
answered on Stack Overflow Feb 22, 2020 by Steven Graham
0

What is your statement in Python?

You should be able to specify the port:

con = psycopg2.connect(database="postgres", user="postgres", password="", host="127.0.0.1", port="5433")
answered on Stack Overflow Feb 22, 2020 by yohann

User contributions licensed under CC BY-SA 3.0