您好,登錄后才能下訂單哦!
都知道django每次請求都會連接數(shù)據(jù)庫和釋放數(shù)據(jù)庫連接。Django為每個請求使用新的數(shù)據(jù)庫連接。一開始這個方法行得通。然而隨著服務(wù)器上的負(fù)載的增加,創(chuàng)建/銷毀連接數(shù)據(jù)庫開始花大量的時間。要避免這個,你可以使用數(shù)據(jù)庫連接池,這里使用SQLAlchemy的連接池。使Django持久化數(shù)據(jù)庫連接。
但這種方法會改變django的代碼。對框架有侵入
方法 1
實現(xiàn)方法如下:
把django/db/backends/mysql文件夾全部拷貝出來,放在項目的一個libs/mysql下面,然后修改base.py文件。
或者把django/db/backends/mysql文件夾在django/db/backends/下面復(fù)制為mysql_pool文件夾,將base.py中所以import中的mysql替換為mysql_pool,這樣可以直接在settings.py中設(shè)置'ENGINE':'django.db.backends.mysql_pool'
找到
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[,recycle=DATABASE_WAIT_TIMEOUT-1]) #其中DATABASE_WAIT_TIMEOUT為你定義的連接超時時間,必須小于等于mysql里面的wait_timeout()
結(jié)果如下
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)
然后找到get_connection_params(self)函數(shù)代碼:
def get_connection_params(self): kwargs = { 'conv':django_conversions, 'charset':utf8 } ...
修改為:
def get_connection_params(self): kwargs = { 'charset':utf8 } ...
注意:如果不改變此處的kwargs,將會出現(xiàn):TypeError:unhashable type:'dict' 的錯誤。
原樣用kwargs傳的話,sqlalchemy的pool會報unhashable錯誤,那是因為kwargs中有個key(conv)對應(yīng)的value(django_conversions)是個字典,在pool中會把(key,value)組成元組作為新的key保存在pool中,但是因為value(django_conversions)是dict,不允許作為key的
在mysql里使用 show status 或 show processlist查看連接情況
方法 2
直接在settings.py同級目錄下的init.py文件中添加如下代碼
from django.conf import settings from django.db.utils import load_backend import sqlalchemy.pool as pool import logging pool_initialized=False def init_pool(): if not globals().get('pool_initialized', False): global pool_initialized pool_initialized = True try: backendname = settings.DATABASES['default']['ENGINE'] backend = load_backend(backendname) #replace the database object with a proxy. backend.Database = pool.manage(backend.Database) backend.DatabaseError = backend.Database.DatabaseError backend.IntegrityError = backend.Database.IntegrityError logging.info("Connection Pool initialized") except: logging.exception("Connection Pool initialization error") init_pool()
然后修改django/db/backends/mysql/base.py文件
找到get_connection_params(self)函數(shù)代碼:
修改為:
def get_connection_params(self): kwargs = { 'charset':utf8 } ...
同理,不修改kwargs將會出現(xiàn):TypeError:unhashable type:'dict' 的錯誤。
以上兩種方法都要改變django的代碼,有一定入侵性,第二種方法改變要小一點
django 1.7
python 2.7
sqlalchemy 1.0
這篇用sqlalchemy構(gòu)建Django連接池的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。