Django没有重新连接到数据库?

b09cbbtk  于 2023-05-30  发布在  Go
关注(0)|答案(1)|浏览(224)

我正在使用Django通道,一旦数据库连接被关闭,它会继续为消费者中的后续事件返回以下错误:

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

我的问题是为什么Django不尝试自动重新连接到数据库服务器。如果我必须处理,我应该在哪里处理?
我是否应该将try except Package 在整个代码中,并在发生此错误时重新连接。
我在中间使用pgbouncer层,我的数据库配置如下所示:

'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'db_pgbouncer',
'USER': '<user_name>',
'PASSWORD': '<password>',
'HOST': '<ip>',
'PORT': '6432',
'CONN_MAX_AGE': None

编辑1:

回溯

File "/home/server/proj/env/lib/python3.6/site-packages/django/db/models/query.py", line 274, in __iter__
    self._fetch_all()
  File "/home/server/proj/env/lib/python3.6/site-packages/django/db/models/query.py", line 1242, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/server/proj/env/lib/python3.6/site-packages/django/db/models/query.py", line 55, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/home/server/proj/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1097, in execute_sql
    cursor.execute(sql, params)
  File "/home/server/proj/env/lib/python3.6/site-packages/sentry_sdk/integrations/django/__init__.py", line 396, in execute
    return real_execute(self, sql, params)
  File "/home/server/proj/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/server/proj/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/server/proj/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/server/proj/env/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/server/proj/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.
2eafrhcq

2eafrhcq1#

您是否正在使用异步消费者?如果是这样,请确保使用database_sync_to_async将所有数据库调用 Package 在任何异步上下文中。此上下文中的数据库连接将被清除。示例代码见这里的文档

相关问题