python - 如果丢失,强制 Django 重新打开数据库连接

标签 python django postgresql

在我的 Python-Django 网络应用程序中,有时数据库会断开连接(与我的测试环境相关的问题,不太稳定......)并且我的网络应用程序给我这个错误:

  File "/usr/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 222, in create_cursor,
django.db.utils.InterfaceError: connection already closed,
    cursor = self.connection.cursor()

现在,我如何告诉 Django 重试打开连接并继续?似乎 django 仍然停留在这一点上......

谢谢。

最佳答案

没有办法告诉 Django 它应该重试连接错误。相反,它被设计为简单地在那个请求上失败。来自 the documentation :

If any database errors have occurred while processing the requests, Django checks whether the connection still works, and closes it if it doesn’t. Thus, database errors affect at most one request; if the connection becomes unusable, the next request gets a fresh connection.

但是,如果您遵循文档中的建议,这应该不是问题:

If your database terminates idle connections after some time, you should set CONN_MAX_AGE to a lower value, so that Django doesn’t attempt to use a connection that has been terminated by the database server.

关于python - 如果丢失,强制 Django 重新打开数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55091455/

相关文章:

postgresql - Postgresql 中列的唯一行

postgresql - 未使用 Postgres GIN 索引,始终进行 SEQ 扫描

python - 在 Python 中使用函数作为 re.sub 的参数?

python - 在 pandas 数据透视表上应用多个过滤器

python - Tornado Facebook 获取请求。如何移至下一页

python - 读取文件时Python中的UnicodeDecodeError,如何忽略错误并跳转到下一行?

sql - 更新无法使用 with 子句

javascript - 将第三方网站的表单数据 POST 到 Django

python - 更新 JsonField django 中的数据

Django Rest Framework 'RelatedManager' 对象没有属性