Django 1.6 introduces a Persistent Connections feature. However I've noticed that exiting a script that uses django's ORM leaves at least some of the connections open on the db side.
Setup: django 1.6.0, postgres 9.2 and psycopg2 2.5.1.
How do you gracefully close the connection to the database from a script?
The caveats section mentions that django opens a connection per thread, so in a multi-threaded script, does django create a connection per thread, even for threads that do not access the db?
Does each thread need to close the db connection separately?
If the answer to both questions above is yes, what can you do with daemon threads (e.g. for comm) which do not join on script exit?
I ran into the same issue just now...
Solved it by calling the following code when my thread exits:
from django.db import close_old_connections
close_old_connections()
I just upgraded and had this come up and close_old_connections
in the main process before launching the sub processes does not work like the old close_connections
did to give each process their own connection. But if you looked at what close_connections
use to do you can recreate it docs.
So I do this in my main process before creating my sub processes.
from django.db import connections
for conn in connections.all():
conn.close()
And it works great. The new close_old_connections
will only close the connection if it has expired or has gone away.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With