简体   繁体   中英

Recover from dead database connection in Django

Say we have the following code (tested on Django 1.6 with a PostgreSQL backend):

from django.db import connection
from django.db.utils import OperationalError

cursor = connection.cursor()

try:
    # kill our own database connection
    cursor.execute('SELECT pg_terminate_backend(pg_backend_pid())');
except OperationalError:
    # Is it possible to get a fresh connection here?
    cursor = connection.cursor() # not useful
    # Will result in:
    # django.db.utils.InterfaceError: connection already closed
    cursor.execute('SELECT 1;')

Obviously, this code is for example purposes only -- in the real world, I'm not purposely terminating my own connection, but my connection may be killed off by the database nonetheless (OOM killer, database administrator cleaning house, restart of the entire database, etc). Is there any way I can recover from the now-terminated database connection, somehow forcing Django to set up a new connection?

Close the connection before re-getting the cursor again. Django will try to reconnect to DB:

try:
    ...
except OperationalError:
    connection.close()
    cursor = connection.cursor()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM