django mysql 自定义数据库及配置

Django 在创建项目的时候,会自动生成配置,不过默认数据库不是我们想要的,现在贴一下 自定义数据库:

DATABASES = {
    'default': {
        # 'ENGINE': 'django.db.backends.mysql',#默认写这个,先修改了
        'ENGINE': 'mysql',
        'POOL_SIZE': 20,  # 每个进程的连接池的大小,总连接数=20*总进程数
        'STORAGE_ENGINE': 'INNODB',  # 存储引擎
        'CHARSET': 'utf-8',  # 字符集
        'CONN_MAX_AGE': 28790,  # 比mysql默认的wait_timeout小10秒
        'NAME': "mysystem",
        'USER': 'root',
        'PORT': 3306,
        'PASSWORD': "123456",
        'HOST': "127.0.0.1",
        "OPTIONS": {"init_command": "SET default_storage_engine=INNODB;"}
    }
}

  在这里 ENGINE被我替换改写了,创建一个包,如图:

 

 

base.py 代码:

# -*- coding: utf-8 -*-
import random
from django.core.exceptions import ImproperlyConfigured

try:
    import MySQLdb as Database
except ImportError as err:
    raise ImproperlyConfigured(
        'Error loading MySQLdb module.\n'
        'Did you install mysqlclient?'
    ) from err

from django.db.backends.mysql.base import DatabaseWrapper as _DatabaseWrapper


class DatabaseWrapper(_DatabaseWrapper):
    def get_new_connection(self, conn_params):
        pool_size = self.settings_dict.get('POOL_SIZE') or 1
        # 1/0
        # print(pool_size,'error')
        return ConnectPool.instance(conn_params, pool_size).get_connection()

    def _close(self):
        return None  # 覆盖掉原来的close方法,查询结束后连接不会自动关闭


class ConnectPool(object):
    def __init__(self, conn_params, pool_size):
        self.conn_params = conn_params
        self.pool_size = pool_size
        self.connects = []

    # 实现连接池的单例
    @staticmethod
    def instance(conn_params, pool_size):
        if not hasattr(ConnectPool, '_instance'):
            ConnectPool._instance = ConnectPool(conn_params, pool_size)
        return ConnectPool._instance

    def get_connection(self):
        if len(self.connects) < self.pool_size:
            new_connect = Database.connect(**self.conn_params)
            self.connects.append(new_connect)
            return new_connect
        index = random.randint(0, self.pool_size - 1)  # 注意这里和range不一样,要减1
        try:
            self.connects[index].ping()
        except:
            self.connects[index] = Database.connect(**self.conn_params)
        return self.connects[index]

  整完之后,你就可以验证一下是否是你自定义的引擎。

posted @ 2021-01-28 09:25  青春叛逆者  阅读(211)  评论(0编辑  收藏  举报