如何强制django从shell重启数据库连接?

时间:2018-01-18 20:21:48

标签: python django

我在Digital Ocean服务器上有一个django项目。从我的本地计算机,我通过ssh连接到数据库:

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

将我的本地settings.py更改为:

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

在本地计算机上的Jupyter QtConsole上,我按照以下步骤进行设置:

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

一切正常,直到我的ssh连接因某种原因被破坏。首先我得到这个错误(在查询数据库的行上,比如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.

当我通过ssh重新连接时,我不断收到以下错误:

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

如果我重新启动IPython内核,错误就会消失。我尝试执行相同的设置步骤。我还尝试了from importlib import reload; reload(django),然后再次进行设置,但无论如何都会出现相同的错误。

有时会发生这种情况,而我有一些我不想在内存中丢失的变量,所以我想避免重启内核。有没有办法在没有它的情况下重新创建数据库连接?我使用的是Python 3.6和django 2.0.0。

2 个答案:

答案 0 :(得分:7)

您可以使用以下内容

from django.db import connections
conn = connections['default']
conn.connect()

from django.db import connection
connection.connect()

答案 1 :(得分:3)

from django.db import connections, connection
for conn in connections.all():
    conn.close_if_unusable_or_obsolete()

然后调用connection.cursor将获得一个新的连接, django源代码:

def _cursor(self, name=None):
    self.ensure_connection()
    with self.wrap_database_errors:
        return self._prepare_cursor(self.create_cursor(name))