MySQL Connection Pooling with Django and SQLAlchemy
1. 安装SQLAlchemy
下载地址:http://www.sqlalchemy.org/download.html
python setup.py install
2. 创建mysql_pool:
拷贝一份/django/db/backends/mysql的mysql文件,放入/django/db/backends改名为"mysql_pool"
在项目文件setting.py中添加:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql_pool', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'mysql_pool', 'sqlite3' or 'oracle'.
'NAME': 'test', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': '1', # Not used with sqlite3.
'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
}
}
3. settings.py and database settings
在项目文件settings.py中添加:
DATABASE_WAIT_TIMEOUT = 120
数据库:
show GLOBAL variables;
set global wait_timeout = 120;
4. 修改mysql_pool下base.py文件:
a. 在最上方加入:
try:
from settings import DATABASE_WAIT_TIMEOUT
except ImportError:
print u'DATABASE_WAIT_TIMEOUT not in settings.py, defaulting to 120.'
DATABASE_WAIT_TIMEOUT = 120
import sqlalchemy.pool as pool
b. 在import MySQLdb as Database下方加入
Database = pool.manage(Database, recycle=DATABASE_WAIT_TIMEOUT-1) # must match or be less than wait_timeout in mysql
c. 替换self.connection = Database.connect(**kwargs)
if settings.DATABASE_HOST.startswith('/'):
self.connection = Database.connect(port=kwargs['port'], unix_socket=kwargs['unix_socket'], user=kwargs['user'], db=kwargs['db'], passwd=kwargs['passwd'], use_unicode=kwargs['use_unicode'], charset='utf8')
else:
self.connection = Database.connect(host=kwargs['host'], port=kwargs['port'], user=kwargs['user'], db=kwargs['db'], passwd=kwargs['passwd'], use_unicode=kwargs['use_unicode'], charset='utf8')
5. 完成!
6. 问题
查看mysql connect只有一个连接
connect pool多个连接没有,在研究中