Advertisement
Guest User

Untitled

a guest
May 24th, 2015
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. import MySQLdb
  2. import time
  3. import sys
  4. import logging
  5.  
  6. class MySQLdbSession:
  7.  
  8. def __init__(self, mysqldb_connect_params, max_reconnect_attempts=5, pause_between_attempts=1, is_ss=False):
  9. self.mysqldb_connect_params = mysqldb_connect_params
  10. self.reconnect_attempts = 0
  11. self.wait_time = pause_between_attempts #in seconds
  12. self.max_reconnect_attempts = max_reconnect_attempts
  13. if is_ss:
  14. raise NotImplemented
  15. self._refresh_cursor()
  16.  
  17. def _refresh_cursor(self):
  18. self.db_conn = MySQLdb.connect(**self.mysqldb_connect_params)
  19. self.cursor = self.db_conn.cursor()
  20.  
  21. def _try_func(self, func, args):
  22. '''
  23. :param func: function - the function to try
  24. :param args: tuple - args to be tried with the function
  25. '''
  26. try:
  27. retval = func(*args)
  28. except Exception as e:
  29. logging.warning("There was an exception...")
  30. logging.warning(sys.exc_info())
  31. is_server_restart_exception = e.message == "MySQL server has gone away"
  32. too_many_reconnects = self.reconnect_attempts >= self.max_reconnect_attempts
  33. if is_server_restart_exception and not too_many_reconnects:
  34. self.reconnect_attempts += 1
  35. logging.info("Sleeping...")
  36. time.sleep(self.wait_time)
  37. logging.info("Trying to reconnect...")
  38. self._refresh_cursor()
  39. retval = self._try_func(func, args)
  40. else:
  41. raise e
  42. self.reconnect_attempts = 0
  43. return retval
  44.  
  45. def execute(self, *args):
  46. return self._try_func(self.cursor.execute, args)
  47.  
  48. def executemany(self, *args):
  49. return self._try_func(self.cursor.executemany, args)
  50.  
  51. def fetchall(self, *args):
  52. return self._try_func(self.cursor.fetchall, args)
  53.  
  54. def commit(self, *args):
  55. return self._try_func(self.db_conn.commit, args)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement