python - Psycopg2 db connection hangs on lost network connection -
Problem Description
I use psycopg2 to connect to your PostgreSQL database on a remote host I am I open a connection and wait for the requests, then for each request, I run a query on connection and return data.
But when the network connection is lost after connection, the next DB query is already hanging and I
details:
- This less
- I can not use the asynchronous connection because I need a transaction
- Python 2.6
- psycopg 2.2.1
- Debian Linux 6 and 7, 64bit
- Postgresclines 8.4 and 9.1
What do I need
I need reliable way to detect some unsuccessful connections before running a query, so my program will not hang, or cursor.exact (..) make way
failed to raise an exception on connection
example :.
import psycopg2 import time Conn = psycopg2.connect ( "host = ' DBS 'dBNAME =' foo 'user =' joe 'password =' x '") time.sleep (10) # I manually switch off VPN during this sleep Vendor am .. cu = conn.cursor () cu.execute ( 'SELECT 1') # & lt; -
What I have tried (and what has not worked):
-
Before importing Psycopg2, I said:
import socket .setdefaulttimeout (10)
TCP timeout "globally" TCP timeout set to
psycopg.connection
socket:.. Conn = psycopg2.connect (... S = socket.fromfd (conn.fileno (), socket.AF_INET, socket.SOCK_STREAM) s.settimeout (5).
To enable the keepalive forpsycopg.connection
socket:... Conn = psycopg2.connect (... s = socket.fromfd (conn.fileno (), socket.AF_INE T Soketksok_strym) Sksettimut (5) Sksetsocopt (Soketksol_soket, Soketkso_keeplive 1) Sksetsocopt (Soketkipproto_tkp, Soketktkp_keapidle 1) Sksetsocopt (Soketkipproto_tkp, socket. TCP_KEEPINT VL, 3) s.setsockopt (socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5) ...
Comments
Post a Comment