18

I have a stand-alone script that reads/writes from/to Postgre using Django ORM.

I get this error occasionally

DatabaseError: query timeout server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request.

I need to re-establish the connection and retry the processing code in the script, but can't seem to find a way. The following code raises 'InterfaceError: connection already closed' on retry, so it doesn't work.

for repeat in range(5):
    try:
        .....................PROCESSING CODE...................
    except DatabaseError, e:
        time.sleep(30)
    else:
        break
else:
    return

Any idea?

1 Answer 1

36

I have a similar need for recreating the database connection and I'm trying the following black magic to reset the connection in django 1.3:

from django.db import connection
connection.connection.close()
connection.connection = None

I don't have PostgreSQL handy to try this out, but it seems to work for MySQL and sqlite at least. Also, if you're using multi-db, you're going to have to perform this step on your specific connection from the django.db.connections dictionary.

Sign up to request clarification or add additional context in comments.

4 Comments

I am not bothered by the problem anymore. If someone else verified this answer to be correct solution, I will mark it. Thank you for answering.
@kakarukeys This works for me. (Django 1.4 and using postgresql)
Works for me as well in the same setup as seyeong jeong.
Working for me with django 1.5 and postgresql 9.3 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.