I've updated the pymongo and mongoengine packages, which are now 4.6.0 and 0.27.0, respectively.
After upgrading it On my Windows machine, I am trying to run celery tasks. In that celery task I have written multiple function and in which I am closing client once that particular function runs successfully, then it is calling another function which has mango client but this providing me given error:
raise InvalidOperation("Cannot use MongoClient after close") pymongo.errors.InvalidOperation: Cannot use MongoClient after close
Code: I am creating client and closing it in given way.
from pymongo import MongoClient
mongo_client = MongoClient(host=host,
port=int(port),
username=username,
password=password,
authSource=authSource_db,
maxPoolSize=15,
MaxIdleTimeMS=120000
)
mongo_client.close()
This is happening because celery is asynchronous. So the order in which the tasks are executed is not determined. In this case, one of the tasks needs the client but another task which maybe defined after the previous task is completed and you have closed the client.
This will automatically close the connection once the tasks are completed.