Db connection in python

I am writing code in python in which I have established a database connection. I have requests in a loop. Although the requests run in a loop, if I unplug the network cable it should stop with an exception. But this doesn't happen.When I reconnect the network device after 2 minutes, it starts again from where it ends. I am using linux and psycopg2. It doesn't show an exception

0


a source to share


3 answers


The database connection will almost certainly be TCP socket based. TCP sockets will for a long time depend on retrying before failing and (in python) throwing an exception. Not to mention trying to reconnect / auto-reconnect in the database layer.



+2


a source


As Douglas' answer said, it will not raise the exception due to TCP.

You can try using socket.setdefaulttimeout () to set a smaller timeout value.



setdefaulttimeout (...)

   setdefaulttimeout(timeout)

   Set the default timeout in floating seconds for new socket objects.
   A value of None indicates that new socket objects have no timeout.
   When the socket module is first imported, the default is None.

      

However, this may not work if the database connection is not made using a python socket, such as a native socket.

+2


a source


If you want to use timeouts that work regardless of how the client library connects to the server, your best bet is to try to perform DB operations in a separate thread, or better, a separate process that "controls" the thread / process can kill if necessary; see the multiprocessing module in the Python 2.6 standard library (if you need a backported version for 2.5). The process is better because when it is killed, the operating system will take care of freeing and cleaning up resources, while killing a thread is always a pretty dangerous and messy business.

+1


a source







All Articles