|
1 | 1 | # -*- coding: utf-8 -*-
|
2 | 2 |
|
3 |
| -import sqlalchemy.pool as pool |
| 3 | +from functools import partial |
4 | 4 |
|
| 5 | +from sqlalchemy import event |
| 6 | +from sqlalchemy.pool import manage, QueuePool |
| 7 | + |
| 8 | +from django.conf import settings |
5 | 9 | from django.db.backends.postgresql_psycopg2.base import *
|
6 | 10 | from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as Psycopg2DatabaseWrapper
|
7 | 11 |
|
8 |
| -Database_ = pool.manage(Database) |
| 12 | +POOL_SETTINGS = 'DATABASE_POOL_ARGS' |
| 13 | + |
| 14 | +# DATABASE_POOL_ARGS should be something like: |
| 15 | +# {'max_overflow':10, 'pool_size':5, 'recycle':300} |
| 16 | +pool_args = getattr(settings, POOL_SETTINGS, {}) |
| 17 | +db_pool = manage(Database, **pool_args) |
| 18 | + |
| 19 | +log = logging.getLogger('z.pool') |
| 20 | + |
| 21 | +def _log(message, *args): |
| 22 | + log.debug('%s to %s' % (message, args[0].get_host_info())) |
| 23 | + |
| 24 | +# Only hook up the listeners if we are in debug mode. |
| 25 | +if settings.DEBUG: |
| 26 | + event.listen(QueuePool, 'checkout', partial(_log, 'retrieved from pool')) |
| 27 | + event.listen(QueuePool, 'checkin', partial(_log, 'returned to pool')) |
| 28 | + event.listen(QueuePool, 'connect', partial(_log, 'new connection')) |
9 | 29 |
|
10 | 30 |
|
11 | 31 | class DatabaseWrapper(Psycopg2DatabaseWrapper):
|
@@ -36,7 +56,7 @@ def _cursor(self):
|
36 | 56 | conn_params['host'] = settings_dict['HOST']
|
37 | 57 | if settings_dict['PORT']:
|
38 | 58 | conn_params['port'] = settings_dict['PORT']
|
39 |
| - self.connection = Database_.connect(**conn_params) |
| 59 | + self.connection = db_pool.connect(**conn_params) |
40 | 60 | self.connection.set_client_encoding('UTF8')
|
41 | 61 | tz = 'UTC' if settings.USE_TZ else settings_dict.get('TIME_ZONE')
|
42 | 62 | if tz:
|
|
0 commit comments