Created
February 26, 2020 20:33
-
-
Save eindiran/529a6b14b2029254d9b3313de3ac5638 to your computer and use it in GitHub Desktop.
A context manager to handle a MongoDB Collection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
A context manager for handling a PyMongo driver MongoDB connection | |
to access a collection. | |
''' | |
from contextlib import contextmanager | |
from pymongo import MongoClient | |
import traceback | |
@contextmanager | |
def mongo_collection(uri: str, timeout_ms: int, collection: str, db_name=None): | |
'''Open up a MongoDB connection, grab a db, then get a collection.''' | |
try: | |
mongo_client = MongoClient(uri, timeout_ms) | |
if db_name is not None: | |
db = mongo_client[db_name] | |
else: | |
db = mongo_client.get_default_database() | |
yield db.get_collection(collection) | |
except BaseException as err: | |
traceback.print_exc() | |
finally: | |
mongo_client.close() | |
# Example: | |
# with mongo_collection(uri, 1000, collection) as c: | |
# results = c.find_all('{foo.bar}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment