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?

Edit
Report