Код: Выделить всё
import redshift_connector
def _ensure_valid_connection(self):
log = logger.get_logger()
# If no connection object exists, create one
if not self.connection:
log.debug("No active Redshift connection. Establishing new connection...")
self.get_connection()
return
< /code>
Даже если у нас есть объект подключения, есть вероятность, что соединение является несвежим (не живым), поэтому я подумал о том, что мы просто выполняем простой запрос, когда мы пытаемся сделать общение БД. Я понимаю, что это было не правильное решение, просто обходной путь. Кроме того, это немного замедлило услугу, как и ожидалось из -за этой накладной расходы.
Это то, что я добавил к функции выше: < /p>
# Test if the existing connection is still valid
try:
cursor = self.connection.cursor()
cursor.execute("SELECT 1")
cursor.close()
log.debug("Existing Redshift connection is valid.")
except Exception as e:
# For any validation error, attempt reconnection (known or unknown error types)
is_known_error = self._is_connection_error(e)
error_type = "recoverable" if is_known_error else "unrecognized"
log.warning(f"Connection validation failed with {error_type} error: {e}")
log.debug("Attempting reconnection...")
try:
self.close_connection()
self.get_connection()
# Test the new connection to ensure it works
cursor = self.connection.cursor()
cursor.execute("SELECT 1")
cursor.close()
success_msg = "Connection restored successfully after reconnection."
if not is_known_error:
success_msg += f" Consider adding '{str(e)}' to connection error patterns."
log.info(success_msg)
except Exception as retry_e:
# If retry also fails, this is likely not a connection issue
log.error(f"Reconnection attempt failed: {retry_e}")
log.error(f"Original error was likely not connection-related: {e}")
raise e
Спасибо за какие -либо предложения или отзывы!>
Подробнее здесь: https://stackoverflow.com/questions/796 ... -connector