单例的应用---mysql数据库连接

import pymysql
from DBUtils.PooledDB import PooledDB
from .tools import *
from django.conf import settings
from functools import wraps
conf = settings.DBPOOL_CONFIG

#DBUtils是一套Python数据库连接池包,并允许对非线程安全的数据库接口进行线程安全包装


# 单例
def singleton(cls):
    instances = {}

    @wraps(cls)
    def get_instance(*args, **kw):
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]
    return get_instance


@singleton
class DBPool(object):
    __pool = None

    def __init__(self):
        # 构造函数,创建数据库连接、游标
        self.coon = DBPool.getmysqlconn(self)
        self.cur = self.coon.cursor(cursor=pymysql.cursors.DictCursor)

    # 数据库连接池连接
    # @staticmethod
    def getmysqlconn(self):
        if DBPool.__pool is None:
            DBPool.__pool = PooledDB(creator=pymysql, mincached=conf['db_pool']['mincached'],
                              maxcached=conf['db_pool']['maxcached'],
                              maxshared=conf['db_pool']['maxshared'],
                              maxconnections=conf['db_pool']['maxconnections'],
                              blocking=conf['db_pool']['blocking'],
                              maxusage=conf['db_pool']['maxusage'], setsession=None,
                              host=conf['db']['host'], port=conf['db']['port'],
                              user=conf['db']['user'], passwd=conf['db']['password'],
                              db=conf['db']['database'], charset=conf['db']['charset'])
        return DBPool.__pool.connection()

    # 插入\更新\删除 sql
    def op_modify(self, sql):
        insert_num = self.cur.execute(sql)  # 执行sql
        self.coon.commit()
        return insert_num

 

你可能感兴趣的:(单例的应用---mysql数据库连接)