Learning Celery, read Celery Best Practices, and have quite a simple question about database usage with Celery.
Deni Bertovic says:
You shouldn't pass Database objects (for instance your User model) to a background task because the serialized object might contain stale data.
So, if I want to connect to the database in a worker, what is the right choice:
@app.task
def add(x, y, collection):
client = MongoClient('mongodb://localhost:27017/')
db = client.wakawaka
db[collection].insert_one({'sum':x+y})
return True
or:
client = MongoClient('mongodb://localhost:27017/')
db = client.wakawaka
@app.task
def add(x, y, collection):
db[collection].insert_one({'sum':x+y})
return True
?
UPD: I can close()
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?