使django与数据库保持长连接

        目前遇上一个很蛋疼的题材,写了一个后台管理系列,
由于是后台管理系列,所以利用功用不是很高,当django程序在闲置一段时间后,再次打开后台系统,就变得很慢,然后又好了。查了好多下边,从沙盘引擎到请求(request),再到django配置,nginx等等,都没有摸清原因。即使也查过是不是数据库的来由,但都因为查的不够深切,没有查出所以然。

sqlite,       
有一次在处理权限问题时,不断地追朔源代码,由于自己利用的是dbroute来控制权限,最后稳定到了这一个db(具体目录:/usr/local/lib/python2.7/dist-packages/django/db/__init__.py),里面的代码有关于连接的,不看不晓得,看了后菊花一紧。我去!原来django每一回查询的时候就连两遍数据库,而且查询完成之后就即刻关掉,真搞不懂作者是怎么想的。每便查询建两遍连续不是很耗时间吗?源代码如下:

from django.conf import settings
from django.core import signals
from django.core.exceptions import ImproperlyConfigured
from django.db.utils import (ConnectionHandler, ConnectionRouter,
    load_backend, DEFAULT_DB_ALIAS, DatabaseError, IntegrityError)

__all__ = ('backend', 'connection', 'connections', 'router', 'DatabaseError',
    'IntegrityError', 'DEFAULT_DB_ALIAS')


if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
    raise ImproperlyConfigured("You must define a '%s' database" % DEFAULT_DB_ALIAS)

connections = ConnectionHandler(settings.DATABASES)

router = ConnectionRouter(settings.DATABASE_ROUTERS)

# `connection`, `DatabaseError` and `IntegrityError` are convenient aliases
# for backend bits.

# DatabaseWrapper.__init__() takes a dictionary, not a settings module, so
# we manually create the dictionary from the settings, passing only the
# settings that the database backends care about. Note that TIME_ZONE is used
# by the PostgreSQL backends.
# We load all these up for backwards compatibility, you should use
# connections['default'] instead.
class DefaultConnectionProxy(object):
    """
    Proxy for accessing the default DatabaseWrapper object's attributes. If you
    need to access the DatabaseWrapper object itself, use
    connections[DEFAULT_DB_ALIAS] instead.
    """
    def __getattr__(self, item):
        return getattr(connections[DEFAULT_DB_ALIAS], item)

    def __setattr__(self, name, value):
        return setattr(connections[DEFAULT_DB_ALIAS], name, value)

connection = DefaultConnectionProxy()
backend = load_backend(connection.settings_dict['ENGINE'])

# Register an event that closes the database connection
# when a Django request is finished.
def close_connection(**kwargs):
    # Avoid circular imports
    from django.db import transaction
    for conn in connections:
        # If an error happens here the connection will be left in broken
        # state. Once a good db connection is again available, the
        # connection state will be cleaned up.
        transaction.abort(conn)
        connections[conn].close()
signals.request_finished.connect(close_connection)

# Register an event that resets connection.queries
# when a Django request is started.
def reset_queries(**kwargs):
    for conn in connections.all():
        conn.queries = []
signals.request_started.connect(reset_queries)

# Register an event that rolls back the connections
# when a Django request has an exception.
def _rollback_on_exception(**kwargs):
    from django.db import transaction
    for conn in connections:
        try:
            transaction.rollback_unless_managed(using=conn)
        except DatabaseError:
            pass
signals.got_request_exception.connect(_rollback_on_exception)

发现它是收到到了一个闭馆信号后就及时关闭,其实也就是每两遍django请求,它就接连三次和询问两次。网上查了下资料,有私房是如此解决的:

在django项目中的__init__.py文件中出席如下代码来落实:

from django.core import signals  
from django.db import close_connection  

# 取消信号关联,实现数据库长连接  
signals.request_finished.disconnect(close_connection) 

它使用的规律是最终一行代码相关的Signal对象,其中还有一个disconnect方法,对应贯彻撤消信号关联。

     
 我照着她的贯彻来做,发现这个,在闲置几钟头后,打开后台依旧亟待10秒左右。由于自己使用的是fastcgi来运转django,可能django在没有动静的时候,fastcgi就把它挂起,所以就还会去重新树立连接。假诺拔取supervisord来运转,估计不会。

     
 既然那多少个艺术非凡,这就再看一下它的源码,发现backends目录下边有mysql,oracle,postgresql_psycopg2,sqlite3等,于是选用msql进去看一下base.py文件。发现django是直接封装MySQLdb,每创立一个MySQLdb对象实际也就进展了两次连续。能不可以像线程池一样,两遍性成立四个MySQLdb对象呢?答案是一定的。sqlalchemy有个pool可以让数据库保持长连接,这就一贯把这几个文件里的Database改成sqlalchemy的pool。当然,我们不可能暴力地修改去修改源码。因为这个模块是用来确立数据库连接的,所以可以独自出来。其实很简单,只需要修改base.py
文件几处就行。实现情势如下:

       
把django/db/backends/mysql目录下的文书全体拷贝出来,放在项目标一个libs/mysql上面,然后修改base.py文件。找到

try:
    import MySQLdb as Database
except ImportError as e:
    from django.core.exceptions import ImproperlyConfigured
    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)

这段代码,在底下添加:

from sqlalchemy import pool
Database = pool.manage(Database)

基本上就可以了。假如还想再修改,就找到

self.connection = Database.connect(**kwargs)

把它注释掉,添加

            self.connection = Database.connect(
                  host=kwargs.get('host', '127.0.0.1'),
                  port=kwargs.get('port', 3306),
                  user=kwargs['user'],
                  db=kwargs['db'],
                  passwd=kwargs['passwd'],
                  use_unicode=kwargs['use_unicode'],
                  charset='utf8'
              )

再修改一下settings.py的数据库配置,把django.db.backends.mysql改为libs.mysql。至此,世界美好了累累。倘使精子上脑,可以活动至:来撸吧**,你会发现世界更美好。**

网站地图xml地图