I have a huge problem: There seems to be some hardware problems on the router of the server my python software runs on. The connection to the database only is successfull about every third time. So a psycopg2.connect() can take up to 5 minutes before I get an timeout exception.
2014-12-23 15:03:12,461 - ERROR - could not connect to server: Connection timed out Is the server running on host "172.20.19.1" and accepting
That's the code I'm using.
# Connection to the DB try: db = psycopg2.connect(host=dhost, database=ddatabase, user=duser, password=dpassword) cursor = db.cursor(cursor_factory=psycopg2.extras.DictCursor) except psycopg2.DatabaseError, err: print(str(err)) logging.error(str(err)) logging.info('program terminated') sys.exit(1)
I tried some timeout additions for the query, but that didn't helped, since the connection didn't got established at all.
Is there a way, I can stop the program immediately, when the connection couldn't be established?
If Django/psycopg2 have the correct domain name or IP address for the PostgreSQL server, and the correct port, the most common explanation for "Connection timed out" is that a firewall (typically on the PostgreSQL server) is filtering that traffic.
The current psycopg2 implementation supports: Python 2 versions from 2.6 to 2.7. Python 3 versions from 3.2 to 3.6. PostgreSQL server versions from 7.4 to 9.6.
Thread and process safetyThe Psycopg module and the connection objects are thread-safe: many threads can access the same database either using separate sessions and creating a connection per thread or using the same connection and creating separate cursors.
The psycopg2-binary package is meant for beginners to start playing with Python and PostgreSQL without the need to meet the build requirements. If you are the maintainer of a published package depending on psycopg2 you shouldn't use psycopg2-binary as a module dependency.
When using the keyword arguments syntax to the connect
function it is possible to use any of the libpd
supported connection parameters. Among those there is connect_timeout
in seconds:
db = psycopg2.connect ( host=dhost, database=ddatabase, user=duser, password=dpassword, connect_timeout=3 )
http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS
http://initd.org/psycopg/docs/module.html
A connection time out raises an OperationalError
exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With