How to use the pymysql.OperationalError function in PyMySQL

To help you get started, we’ve selected a few PyMySQL examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github twindb / proxysql-tools / tests / unit / galera / test_galera_node.py View on Github external
def test_wsrep_local_state_if_can_not_execute(mock_execute, galera_node):
    """
    :param galera_node: GaleraNode instance
    :type galera_node: GaleraNode
    """
    mock_execute.side_effect = OperationalError
    assert galera_node.wsrep_local_state == None
github magneticstain / Inquisition / lib / destiny / Sage.py View on Github external
:return: void
        """

        # check if this is a test run
        testRun = self.getCfgValue(section='cli', name='test_run', defaultVal=False, dataType=bool)

        newTrainerPID = 0
        if not testRun:
            # fork process before beginning analysis
            self.lgr.debug('forking off engine to child process')
            newTrainerPID = fork()
        if newTrainerPID == 0 or testRun:
            # in child process, bounce inquisition DB handle (see issue #66)
            try:
                self.bounceInquisitionDbConnection()
            except OperationalError as e:
                self.lgr.critical('could not create database connection :: [ ' + str(e) + ' ]')
                if self.sentryClient:
                    self.sentryClient.captureException()

                exit(1)

            # create model
            self.lgr.debug('initializing classifier')
            self.initClassifier()

            # train and predict model after every $sleepTime seconds
            sleepTime = self.getCfgValue('learning', 'networkThreatDetectionSleepTime', defaultVal=30, dataType=int)

            while True:
                # fetch all needed data
                self.gatherAllData()
github paepcke / json_to_relation / json_to_relation / mysqldb.py View on Github external
'''
        
        # If all arguments are set to None, we are unittesting:
        if all(arg is None for arg in (host,port,user,passwd,db)):
            return
        
        self.user = user
        self.pwd  = passwd
        self.db   = db
        self.cursors = []
        try:
            self.connection = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db)
            #self.connection = MySQLdb.connect(host=host, port=port, user=user, passwd=passwd, db=db, local_infile=1)
        
        #except MySQLdb.OperationalError:
        except pymysql.OperationalError:
            pwd = '...............' if len(passwd) > 0 else ''
            raise ValueError('Cannot reach MySQL server with host:%s, port:%s, user:%s, pwd:%s, db:%s' %
                             (host, port, user, pwd, db))
github netdata / netdata / python.d / python_modules / bases / FrameworkServices / MySQLService.py View on Github external
def __is_error_critical(err_class, err_text):
        return err_class == MySQLdb.OperationalError and all(['denied' not in err_text,
                                                              'Unknown column' not in err_text])
github noplay / python-mysql-replication / pymysqlreplication / binlogstream.py View on Github external
def fetchone(self):
        while True:
            if not self.__connected_stream:
                self.__connect_to_stream()

            if not self.__connected_ctl:
                self.__connect_to_ctl()

            try:
                if pymysql.__version__ < "0.6":
                    pkt = self._stream_connection.read_packet()
                else:
                    pkt = self._stream_connection._read_packet()
            except pymysql.OperationalError as error:
                code, message = error.args
                if code in MYSQL_EXPECTED_ERROR_CODES:
                    self._stream_connection.close()
                    self.__connected_stream = False
                    continue
                raise

            if pkt.is_eof_packet():
                self.close()
                return None

            if not pkt.is_ok_packet():
                continue

            binlog_event = BinLogPacketWrapper(pkt, self.table_map,
                                               self._ctl_connection,
github aws-samples / aws-secrets-manager-rotation-lambdas / SecretsManagerRDSMariaDBRotationSingleUser / lambda_function.py View on Github external
Returns:
        Connection: The pymysql.connections.Connection object if successful. None otherwise

    Raises:
        KeyError: If the secret json does not contain the expected keys

    """
    # Parse and validate the secret JSON string
    port = int(secret_dict['port']) if 'port' in secret_dict else 3306
    dbname = secret_dict['dbname'] if 'dbname' in secret_dict else None

    # Try to obtain a connection to the db
    try:
        conn = pymysql.connect(secret_dict['host'], user=secret_dict['username'], passwd=secret_dict['password'], port=port, db=dbname, connect_timeout=5)
        return conn
    except pymysql.OperationalError:
        return None
github Teradata / stacki / common / src / stack / ws / restapi / views.py View on Github external
j = {"Output": output}

							return HttpResponse(
								str(json.dumps(j)),
								content_type="application/json",
								status=200,
							)
				# If it's not the sync command, run the
				# command module wrapper directly.
				else:
					try:
						rc = command.runWrapper(cmd_module, cmd_arg_list)
					# If we hit a database error, check if it's an access
					# denied error. If so, sanitize the error message, and
					# don't expose database access.
					except pymysql.OperationalError as e:
						errortext = str(sys.exc_info()[1])
						log.error(errortext)
						if int(e.args[0]) in MYSQL_EX:
							errortext = "Database Permission Denied. Admin privileges required"
							status_code = 403
						else:
							status_code = 500
						return HttpResponse(
							json.dumps({'API Error': errortext}),
							content_type='application/json',
							status=status_code,
						)
					except CommandError as e:
						# Get output from command
						text = command.getText()
github datajoint / datajoint-python / datajoint / autopopulate.py View on Github external
if not reserve_jobs or jobs.reserve(self.target.table_name, self._job_key(key)):
                self.connection.start_transaction()
                if key in self.target:  # already populated
                    self.connection.cancel_transaction()
                    if reserve_jobs:
                        jobs.complete(self.target.table_name, self._job_key(key))
                else:
                    logger.info('Populating: ' + str(key))
                    call_count += 1
                    self.__class__._allow_insert = True
                    try:
                        make(dict(key))
                    except (KeyboardInterrupt, SystemExit, Exception) as error:
                        try:
                            self.connection.cancel_transaction()
                        except OperationalError:
                            pass
                        error_message = '{exception}{msg}'.format(
                            exception=error.__class__.__name__,
                            msg=': ' + str(error) if str(error) else '')
                        if reserve_jobs:
                            # show error name and error message (if any)
                            jobs.error(
                                self.target.table_name, self._job_key(key),
                                error_message=error_message, error_stack=traceback.format_exc())
                        if not suppress_errors or isinstance(error, SystemExit):
                            raise
                        else:
                            logger.error(error)
                            error_list.append((key, error if return_exception_objects else error_message))
                    else:
                        self.connection.commit_transaction()
github holland-backup / holland / plugins / holland.lib.mysql / holland / lib / mysql / client / base.py View on Github external
"""pymysql.Connection wrappers"""

import re
import logging
from textwrap import dedent
from warnings import filterwarnings
import pymysql
import pymysql.connections

MySQLError = pymysql.MySQLError  # pylint: disable=C0103
ProgrammingError = pymysql.ProgrammingError  # pylint: disable=C0103
OperationalError = pymysql.OperationalError  # pylint: disable=C0103

LOG = logging.getLogger(__name__)

filterwarnings("ignore", category=pymysql.Warning)

__all__ = [
    "connect",
    "MySQLClient",
    "AutoMySQLClient",
    "MySQLError",
    "ProgrammingError",
    "OperationalError",
]

MYSQL_CLIENT_CONFIG_STRING = """
[mysql:client]