Beispiel #1
0
    def __init__(self, host, port, database,
                 user, passwd):
        # Connect to mysql.
        # dbc = pymysql.connect(
        #     host=Config.MYSQL_HOST, user=Config.MYSQL_USER,
        #     password=Config.MYSQL_PASSWORD, database=Config.MYSQL_DATABASE,
        #     port=Config.MYSQL_PORT,
        #     charset='utf8mb4',
        #     use_unicode=True,
        #     cursorclass=pymysql.cursors.DictCursor
        # )
        """
        SteadyDB
        DBUtils.SteadyDB基于兼容DB-API 2接口的数据库模块创建的普通连接,
        实现了"加强"连接。具体指当数据库连接关闭、丢失或使用频率超出限制时,将自动重新获取连接。

        典型的应用场景如下:在某个维持了某些数据库连接的程序运行时重启了数据库,
        或在某个防火墙隔离的网络中访问远程数据库时重启了防火墙。
        """

        import pymysql
        from DBUtils import SteadyDB
        self.dbc = SteadyDB.connect(
            creator=pymysql,
            host=host, user=user,
            passwd=passwd,
            database=database if database else None,
            port=port,
            charset='utf8mb4',
            use_unicode=True,
            autocommit=False,
            # 流式、字典访问
            cursorclass=pymysql.cursors.SSDictCursor)
Beispiel #2
0
  def __init__(self):
    """ Consruct an instance. The instance's open() method must be
    called to make it ready for acquireConnection() calls.
    """
    self._logger = _getLogger(self.__class__)

    self._conn = SteadyDB.connect(** _getCommonSteadyDBArgsDict())

    self._logger.debug("Created %s", self.__class__.__name__)
    return
Beispiel #3
0
    def __init__(self):
        """ Consruct an instance. The instance's open() method must be
    called to make it ready for acquireConnection() calls.
    """
        self._logger = _getLogger(self.__class__)

        self._conn = SteadyDB.connect(**_getCommonSteadyDBArgsDict())

        self._logger.debug("Created %s", self.__class__.__name__)
        return
Beispiel #4
0
def connect(url, setsession=None):
    """
    Return connection to database specified by `url`.
    """
    scheme, username, password, hostname, port, database = parse_db_url(url)

    conn = None

    if scheme == "postgresql":
        psycopg2 = __import__("psycopg2")

        expected_exceptions = (psycopg2.InterfaceError, psycopg2.InternalError,
                               psycopg2.OperationalError)

        try:
            if database:
                conn = SteadyDB.connect(psycopg2, setsession=setsession,
                                        failures=expected_exceptions,
                                        database=database, user=username,
                                        password=password, host=hostname,
                                        port=port)
            else:
                conn = SteadyDB.connect(psycopg2, setsession=setsession,
                                        failures=expected_exceptions,
                                        user=username, password=password,
                                        host=hostname, port=port)
        except psycopg2.OperationalError as exc:
            raise OperationalError(str(exc))
    elif scheme == "mysql":
        db_api2_mod = __import__("MySQLdb")

        try:
            conn = SteadyDB.connect(db_api2_mod, setsession=setsession,
                                    db=database, user=username,
                                    passwd=password, host=hostname, port=port)
        except db_api2_mod.OperationalError as exc:
            raise OperationalError(str(exc))

    return conn
Beispiel #5
0
    def acquireConnection(self):
        """ Create a Connection instance.

    Parameters:
    ----------------------------------------------------------------
    retval:       A ConnectionWrapper instance. NOTE: Caller
                    is responsible for calling the  ConnectionWrapper
                    instance's release() method or use it in a context manager
                    expression (with ... as:) to release resources.
    """
        self._logger.debug("Acquiring connection")

        dbConn = SteadyDB.connect(**_getCommonSteadyDBArgsDict())
        connWrap = ConnectionWrapper(
            dbConn=dbConn, cursor=dbConn.cursor(), releaser=self._releaseConnection, logger=self._logger
        )
        return connWrap
Beispiel #6
0
    def acquireConnection(self):
        """ Create a Connection instance.

    Parameters:
    ----------------------------------------------------------------
    retval:       A ConnectionWrapper instance. NOTE: Caller
                    is responsible for calling the  ConnectionWrapper
                    instance's release() method or use it in a context manager
                    expression (with ... as:) to release resources.
    """
        self._logger.debug("Acquiring connection")

        dbConn = SteadyDB.connect(**_getCommonSteadyDBArgsDict())
        connWrap = ConnectionWrapper(dbConn=dbConn,
                                     cursor=dbConn.cursor(),
                                     releaser=self._releaseConnection,
                                     logger=self._logger)
        return connWrap
Beispiel #7
0
    def connect_ro(self, **kwargs):
        """
        Return new read-only database connection.

        The kwargs are merged with the read-only database configuration of the
        instance and passed directly to the psycopg2 connect function.
        """
        db_conf = self.config["database_ro"]

        merged_kwargs = {
            "failures": EXPECTED_EXCEPTIONS,
            "database": db_conf.get("name"),
            "host": db_conf.get("host"),
            "port": db_conf.get("port")}

        merged_kwargs.update(kwargs)

        return SteadyDB.connect(psycopg2, **merged_kwargs)