[Solved]-Closing db connection with django's persistent connection in a multi-threaded script

13👍

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()

7👍

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.

Leave a comment