Monday, 4 June 2018

How can I force django to restart a database connection from the shell?

I have a django project on a Digital Ocean server. From my local machine, I connect to the database through ssh:

ssh -L 63333:localhost:5432 me@my.server

And change my local settings.py as:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': 63333
    }
}

And on a Jupyter QtConsole on my local machine, I follow these steps for setup:

import os
import django
os.chdir('/path/to/my/project')
os.environ['DJANGO_SETTINGS_MODULE'] = 'my_project.settings'
django.setup()

It all works fine until my ssh connection is broken by some reason. First I get this error (on a line that queries the database, say, my_model.objects.first()):

DatabaseErrorTraceback (most recent call last)
/home/ayhan/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args)
     84             else:
---> 85                 return self.cursor.execute(sql, params)
     86 

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

When I reconnect through ssh, I keep getting the following error:

InterfaceErrorTraceback (most recent call last)
/home/ayhan/anaconda3/lib/python3.6/site-packages/django/db/backends/base/base.py in _cursor(self, name)
    233         with self.wrap_database_errors:
--> 234             return self._prepare_cursor(self.create_cursor(name))
    235 

/home/ayhan/anaconda3/lib/python3.6/site-packages/django/db/backends/postgresql/base.py in create_cursor(self, name)
    211         else:
--> 212             cursor = self.connection.cursor()
    213         cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None

InterfaceError: connection already closed

The error only goes away if I restart the IPython kernel. I tried executing the same steps for the setup. I also tried from importlib import reload; reload(django) and then doing the setup again but it gives the same error no matter what.

Sometimes this happens while I have variables that I don't want to lose in the memory so I want to avoid restarting the kernel. Is there a way to recreate the database connection without it? I am using Python 3.6 and django 2.0.0.



from How can I force django to restart a database connection from the shell?

No comments:

Post a Comment