title: Python and Django OperationalError (2006, 'MySQL server has gone away')
body: <p>Original: I have recently started getting MySQL OperationalErrors from some of my old code and cannot seem to trace back the problem. Since it was working before, I thought it may have been a software update that broke something. I am using python 2.7 with django runfcgi with nginx. Here is my original code:</p>
  
  <p><strong>views.py</strong></p>
  
  <pre><code>DBNAME = "test"
  DBIP = "localhost"
  DBUSER = "django"
  DBPASS = "password"
  db = MySQLdb.connect(DBIP,DBUSER,DBPASS,DBNAME)
  cursor = db.cursor()
  
  def list(request):
      statement = "SELECT item from table where selected = 1"
      cursor.execute(statement)
      results = cursor.fetchall()
  </code></pre>
  
  <p>I have tried the following, but it still does not work:</p>
  
  <p><strong>views.py</strong></p>
  
  <pre><code>class DB:
      conn = None
      DBNAME = "test"
      DBIP = "localhost"
      DBUSER = "django"
      DBPASS = "password"
  def connect(self):
      self.conn = MySQLdb.connect(DBIP,DBUSER,DBPASS,DBNAME)
  def cursor(self):
      try:
          return self.conn.cursor()
      except (AttributeError, MySQLdb.OperationalError):
          self.connect()
          return self.conn.cursor()
  
  db = DB()
  cursor = db.cursor()
  
  def list(request):
      cursor = db.cursor()
      statement = "SELECT item from table where selected = 1"
      cursor.execute(statement)
      results = cursor.fetchall()
  </code></pre>
  
  <p>Currently, my only workaround is to do <code>MySQLdb.connect()</code> in each function that uses mysql. Also I noticed that when using django's <code>manage.py runserver</code>, I would not have this problem while nginx would throw these errors. I doubt that I am timing out with the connection because <code>list()</code> is being called within seconds of starting the server up. Were there any updates to the software I am using that would cause this to break/is there any fix for this?</p>
  
  <p>Edit: I realized that I recently wrote a piece of middle-ware to daemonize a function and this was the cause of the problem. However, I cannot figure out why. Here is the code for the middle-ware</p>
  
  <pre><code>def process_request_handler(sender, **kwargs):
      t = threading.Thread(target=dispatch.execute,
          args=[kwargs['nodes'],kwargs['callback']],
          kwargs={})
      t.setDaemon(True)
      t.start()
      return
  process_request.connect(process_request_handler)
  </code></pre>