Django:如何获得到数据库的新连接

2024-09-24 00:26:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我用django构建了一个web服务器。在

并使用一个线程来运行任务,该任务将客户机发送的数据保存到数据库中。在

  while True:
      ...
      try:  
          self.dbTarget, created = ClientMonitor.objects.get_or_create(Machine_code=own_MachC)

          data = self.workQueue.get()  #from client sent

          self.dbTarget.setValue(data) #Custom method assigning
          self.dbTarget.save()         #django ORM
      except InterfaceError as ee:
          pass

线程是长时间运行的,但是很长一段时间后会出现接口错误,因为mysql服务器断开连接,超时8小时。在

Especially it can not auto-reconnect to the db. Creating a new thread will be OK, but it will increase resource occupation.

所以当连接在同一线程中关闭时,我想重新连接db。另外,Django每个请求都会得到一个新的连接。在

如何在同一线程中重新连接到数据库? 谢谢您!!!在


Tags: 数据djangoself服务器web数据库dbdata
2条回答

Django本身使用函数^{}在每个请求的开始和结束时关闭超过其生存期的任何连接。这将检测连接是否早于数据库设置中指定的MAX_AGE,或者是否不可用。如果将MAX_AGE设置为低于数据库的超时值,则不会因为db超时而遇到InterfaceError。在

from django.db import close_old_connections

while True:
    try:  
        ...
    finally:
        close_old_connections()

只需关闭异常处理程序中的连接。下次应用程序尝试与数据库通信时,应建立新的连接:

import logging
from django.db import connection

try:  
    self.dbTarget, created = ClientMonitor.objects.get_or_create(Machine_code=own_MachC)
    ...
except InterfaceError as ee:
    logging.warning(ee)    # make sure that you log these events
    connection.close()

相关问题 更多 >