Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.43 KB | None | 0 0
  1. import pymongo
  2.  
  3.  
  4. class Client:
  5.  
  6. def __init__(self, uri, dbname, collection=None):
  7. self.client = pymongo.MongoClient(uri)
  8. self.db = self.client[dbname]
  9. self.collection = collection
  10.  
  11.  
  12. def __enter__(self):
  13. if self.collection:
  14. obj = getattr(self.db, self.collection)
  15. else:
  16. obj = self.db
  17.  
  18. return obj
  19.  
  20.  
  21. def __exit__(self, *args, **kwargs):
  22. self.client.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement