Mix
Mix

Reputation: 133

Django: how to get a fresh connection to the database

I have built a web server with django.

And use a thread to run task, which save data sent from clients to the database.

  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

The thread is long-running, but it will except a InterfaceError after a long time because the mysql server disconnect as eight-hours timeout.

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

So I want to reconnect db when connection closed in the same thread. Also Django each request gets a fresh connection.

How I can get a fresh connection to the database in the same thread? Thank you!!!

Upvotes: 6

Views: 8084

Answers (2)

knbk
knbk

Reputation: 53669

Django itself uses the function close_old_connections() to close any connections past their lifetime at the start and end of every request. This detects whether the connection is older than the MAX_AGE specified in your database settings, or is otherwise unusable. If you set your MAX_AGE lower than the database's timeout, you should never encounter an InterfaceError due to a db timeout.

from django.db import close_old_connections

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

Upvotes: 6

mhawke
mhawke

Reputation: 87074

Just close the connection in your exception handler. A new connection should be established the next time that your application attempts to communicate with the database:

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()

Upvotes: 4

Related Questions