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.
source share