python - 如何强制 django 从 shell 重新启动数据库连接?

标签 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。

最佳答案

你可以使用类似下面的东西

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

from django.db import connection
connection.connect()

关于python - 如何强制 django 从 shell 重新启动数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48329685/

相关文章:

django - 在 Django 中显示准确的当前时间和日期的最佳方法是什么?

python - 如何在Django View 中知道并引发确切异常

python - celery 、kombu 和 django - 导入错误

python - Django 中 Python 日志记录的优雅设置

python - 如何在 Python 中编写没有标题的 XML 文件?

python - 找不到 scrapyd-client 命令

python - 如何阻止命令提示符在 python 中关闭?

Filemaker Pro 中的 Python

将 Django 项目部署到 Heroku 时,python manage.py collectstatic --noinput 错误

python - 根据当前登录的用户自定义 Django 表单