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多个连接没有,在研究中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值