1. 程式人生 > >使django與數據庫保持長連接

使django與數據庫保持長連接

util 一段 pen n-n follow use 項目 關於 core

最近遇到一個很蛋疼的問題,寫了一個後臺管理系統, 由於是後臺管理系統,所以使用頻率不是很高,當django程序在閑置一段時間後,再次打開後臺系統,就變得很慢,然後又好了。查了很多方面,從模板引擎到請求(request),再到django配置,nginx等等,都沒有查出原因。雖然也查過是不是數據庫的原因,但都因為查的不夠深入,沒有查出所以然。

有一次在處理權限問題時,不斷地追朔源代碼,由於我使用的是dbroute來控制權限,最後定位到了這個db(具體目錄:/usr/local/lib/python2.7/dist-packages/django/db/__init__.py),裏面的代碼有關於連接的,不看不知道,看了後菊花一緊。我去!原來django每次查詢的時候就連一次數據庫,而且查詢完成之後就立馬關掉,真搞不懂作者是怎麽想的。每次查詢建一次連接不是很耗時間嗎?源代碼如下:

  1. from django.conf import settings
  2. from django.core import signals
  3. from django.core.exceptions import ImproperlyConfigured
  4. from django.db.utils import (ConnectionHandler, ConnectionRouter,
  5. load_backend, DEFAULT_DB_ALIAS, DatabaseError, IntegrityError)
  6. __all__ = (‘backend‘, ‘connection‘, ‘connections‘, ‘router‘, ‘DatabaseError‘,
  7. ‘IntegrityError‘, ‘DEFAULT_DB_ALIAS‘)
  8. if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
  9. raise ImproperlyConfigured("You must define a ‘%s‘ database" % DEFAULT_DB_ALIAS)
  10. connections = ConnectionHandler(settings.DATABASES)
  11. router = ConnectionRouter(settings.DATABASE_ROUTERS)
  12. # `connection`, `DatabaseError` and `IntegrityError` are convenient aliases
  13. # for backend bits.
  14. # DatabaseWrapper.__init__() takes a dictionary, not a settings module, so
  15. # we manually create the dictionary from the settings, passing only the
  16. # settings that the database backends care about. Note that TIME_ZONE is used
  17. # by the PostgreSQL backends.
  18. # We load all these up for backwards compatibility, you should use
  19. # connections[‘default‘] instead.
  20. class DefaultConnectionProxy(object):
  21. """
  22. Proxy for accessing the default DatabaseWrapper object‘s attributes. If you
  23. need to access the DatabaseWrapper object itself, use
  24. connections[DEFAULT_DB_ALIAS] instead.
  25. """
  26. def __getattr__(self, item):
  27. return getattr(connections[DEFAULT_DB_ALIAS], item)
  28. def __setattr__(self, name, value):
  29. return setattr(connections[DEFAULT_DB_ALIAS], name, value)
  30. connection = DefaultConnectionProxy()
  31. backend = load_backend(connection.settings_dict[‘ENGINE‘])
  32. # Register an event that closes the database connection
  33. # when a Django request is finished.
  34. def close_connection(**kwargs):
  35. # Avoid circular imports
  36. from django.db import transaction
  37. for conn in connections:
  38. # If an error happens here the connection will be left in broken
  39. # state. Once a good db connection is again available, the
  40. # connection state will be cleaned up.
  41. transaction.abort(conn)
  42. connections[conn].close()
  43. signals.request_finished.connect(close_connection)
  44. # Register an event that resets connection.queries
  45. # when a Django request is started.
  46. def reset_queries(**kwargs):
  47. for conn in connections.all():
  48. conn.queries = []
  49. signals.request_started.connect(reset_queries)
  50. # Register an event that rolls back the connections
  51. # when a Django request has an exception.
  52. def _rollback_on_exception(**kwargs):
  53. from django.db import transaction
  54. for conn in connections:
  55. try:
  56. transaction.rollback_unless_managed(using=conn)
  57. except DatabaseError:
  58. pass
  59. signals.got_request_exception.connect(_rollback_on_exception)

發現它是接收到了一個關閉信號後就立馬關閉,其實也就是每一次django請求,它就連接一次和查詢一次。網上查了下資料,有個人是這樣解決的:

在django項目中的__init__.py文件中加入如下代碼來實現:

  1. from django.core import signals
  2. from django.db import close_connection
  3. # 取消信號關聯,實現數據庫長連接
  4. 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)

這段代碼,在下面添加:

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


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

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

把它註釋掉,添加

  1. self.connection = Database.connect(
  2. host=kwargs.get(‘host‘, ‘127.0.0.1‘),
  3. port=kwargs.get(‘port‘, 3306),
  4. user=kwargs[‘user‘],
  5. db=kwargs[‘db‘],
  6. passwd=kwargs[‘passwd‘],
  7. use_unicode=kwargs[‘use_unicode‘],
  8. charset=‘utf8‘
  9. )


再修改一下settings.py的數據庫配置,把django.db.backends.mysql改為libs.mysql。至此,世界美好了很多。如果精蟲上腦,可以移步至:來擼吧,你會發現世界更美好。

使django與數據庫保持長連接