'How to close MongoDB connection in Python?
Consider a python script like below which has many if else conditions and many try except blocks. I want to close the MongoDB connection after the MongoDB operations. Is the below mentioned way a proper way to close the connection?
def temp_fun():
try:
client = MongoClient(DB_NAME) # from PyMongo
if some_condition:
# code
if client:
client.close()
return True
elif some_condition:
# code
if client:
client.close()
return True
else some_condition:
# code
if client:
client.close()
return True
except:
if client:
client.close()
return None
Solution 1:[1]
You could try finally, as it's always executed regardless of the possible exceptions generated in code.
Solution 2:[2]
You don't need to close pymongo connections, python and pymongo handles all the clean-up for you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dnorambu 98 |
| Solution 2 | Belly Buster |
