Skip to content
This repository was archived by the owner on Aug 26, 2021. It is now read-only.

Commit 0fd7bd0

Browse files
author
Kenneth Reitz
committed
DATABASE_POOL_ARGS
Closes #1
1 parent ab15daf commit 0fd7bd0

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

README.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,14 @@ Installation
3636
Installing Django-PostgresPool is simple, with pip::
3737

3838
$ pip install django-postgrespool
39+
40+
Configuration
41+
-------------
42+
43+
Optionally, you can provide additional options to pass to SQLAlchemy's pool creation::
44+
45+
DATABASE_POOL_ARGS = {
46+
'max_overflow': 10,
47+
'pool_size': 5,
48+
'recycle': 300
49+
}

django_postgrespool/base.py

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,31 @@
11
# -*- coding: utf-8 -*-
22

3-
import sqlalchemy.pool as pool
3+
from functools import partial
44

5+
from sqlalchemy import event
6+
from sqlalchemy.pool import manage, QueuePool
7+
8+
from django.conf import settings
59
from django.db.backends.postgresql_psycopg2.base import *
610
from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as Psycopg2DatabaseWrapper
711

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'))
929

1030

1131
class DatabaseWrapper(Psycopg2DatabaseWrapper):
@@ -36,7 +56,7 @@ def _cursor(self):
3656
conn_params['host'] = settings_dict['HOST']
3757
if settings_dict['PORT']:
3858
conn_params['port'] = settings_dict['PORT']
39-
self.connection = Database_.connect(**conn_params)
59+
self.connection = db_pool.connect(**conn_params)
4060
self.connection.set_client_encoding('UTF8')
4161
tz = 'UTC' if settings.USE_TZ else settings_dict.get('TIME_ZONE')
4262
if tz:

0 commit comments

Comments
 (0)