How to get hold of a (database) connection from within a thread

11 views
Skip to first unread message

Joseph Wayodi

unread,
Nov 4, 2010, 6:31:02 AM11/4/10
to django...@googlegroups.com
Hi people,

I am running some Django code that creates objects in the database. I am using PostgreSQL via psycopg2. However, I am running this code from the Django shell, and not as part of a request. I therefore have to handle a few things manually, for example, closing connections to the database. The code creates multiple threads to do the object creation, and I soon hit the maximum limit of allowed connections to the database.

How can I get hold of the connection used to create the object, from within each thread, so that each thread closes the connection that it has just used? Alternatively, how can I get a list of all the open connections that Django is using at any one time. I am using the "standard" model query API, and not executing custom SQL directly.

Thanks,

Joseph.

Jirka Vejrazka

unread,
Nov 4, 2010, 8:12:11 AM11/4/10
to django...@googlegroups.com
> How can I get hold of the connection used to create the object, from within
> each thread, so that each thread closes the connection that it has just
> used? Alternatively, how can I get a list of all the open connections that
> Django is using at any one time. I am using the "standard" model query API,
> and not executing custom SQL directly.

Hi Joseph,

I use simple:

>>> from django.db import connection
>>> connection.close()

Please note that this is pre-multidb support, so you'll probably
have to use the connections dictionary - see multi-db documentation
for details.

Cheers

Jirka

Joseph Wayodi

unread,
Nov 4, 2010, 9:17:30 AM11/4/10
to django...@googlegroups.com

Thanks a lot Jirka. Calling this from inside each thread seems to have done it for me:

>>> from django.db import connections
>>> for connection in connections.all(): connection.close()

Regards,

Joseph.
Reply all
Reply to author
Forward
0 new messages