title: How to correctly connect to mongodb in Celery worker?
body: <p>Learning Celery, read <a href="https://denibertovic.com/posts/celery-best-practices/" rel="nofollow noreferrer">Celery Best Practices</a>, and have quite a simple question about database usage with Celery.</p>
  
  <p>Deni Bertovic says:</p>
  
  <blockquote>
    <p>You shouldn't pass Database objects (for instance your User model) to
    a background task because the serialized object might contain stale
    data.</p>
  </blockquote>
  
  <p>So, if I want to connect to the database in a worker, what is the right choice:</p>
  
  <pre><code>@app.task
  def add(x, y, collection):
      client = MongoClient('mongodb://localhost:27017/')
      db = client.wakawaka
      db[collection].insert_one({'sum':x+y})
      return True
  </code></pre>
  
  <p>or:</p>
  
  <pre><code>client = MongoClient('mongodb://localhost:27017/')
  db = client.wakawaka
  
  @app.task
  def add(x, y, collection):
      db[collection].insert_one({'sum':x+y})
      return True
  </code></pre>
  
  <p>?</p>
  
  <p><strong>UPD:</strong> I can <code>close()</code> my mongodb connection at the end of every task, so every time I need something, task will connect to fresh DB, and no resources wasted. Still, do I need to open/close database connection so many times? Or I can connect once and somehow refresh connection to retrieve fresh version of DB? </p>