Pymysql lost connection after a long period

using pymysql, connect to mysql, leave the program to work for a long time, for example, leave the office at night and return the next morning. During this period, no operation was performed with this application. this mistake.

File "/usr/local/lib/python3.3/site-packages/pymysql/cursors.py", line 117, in execute self.errorhandler(self, exc, value) File "/usr/local/lib/python3.3/site-packages/pymysql/connections.py", line 189, in defaulterrorhandler raise errorclass(errorvalue) pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query') 

restart the web server (tornado), this is normal. Why not leave it a long time to get this error?

+4
source share
1 answer

Waiting for wait_timeout exists for some reason: long idle connections waste server resources. You are right: this is not the right approach.

Fortunately, this is Python, which has a robust exception mechanism. I am not familiar with pymysql , but presumably you have an open_connection method that allows

 try: cursor.do_something() except pymysql.err.OperationalError as e: if e[0] == 2013: # Lost connection to server # redo open_connection and do_something else: raise 

Since you did not send the calling code, I cannot structure this example according to your application. It is worth noting the except clause: first, they should always be as narrow as possible, in this case there are (presumably) a lot of OperationalErrors, and you only know how to deal with the β€œLost Connection”.

In case this is not a lost connection, you must re-lift it so that it does not swallow. If you do not know how to handle other OperationalErrors, this will be pushed onto the stack and will result in an informative error message, which is wise to do since your cursor is probably useless anyway by then.

Restarting the web server only captures the lost connection as a random side effect of reinitializing everything; handling exception in code is a much milder way to achieve your goal.

+4
source

Source: https://habr.com/ru/post/1495487/


All Articles