2023-02-05 16:40:22 +00:00
|
|
|
import pymongo
|
2023-02-08 18:46:05 +00:00
|
|
|
import pymongo.errors
|
2023-02-05 16:40:22 +00:00
|
|
|
import contextlib
|
|
|
|
import typing as t
|
|
|
|
import logging
|
|
|
|
|
|
|
|
from ..config import MONGO_HOST, MONGO_PORT
|
|
|
|
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
@contextlib.contextmanager
|
|
|
|
def mongo_client_from_config() -> t.ContextManager[pymongo.MongoClient]:
|
|
|
|
"""
|
|
|
|
Create a new MongoDB client and yield it.
|
|
|
|
"""
|
2023-02-08 18:46:05 +00:00
|
|
|
log.debug("Creating MongoDB client...")
|
2023-02-05 16:40:22 +00:00
|
|
|
client: pymongo.MongoClient = pymongo.MongoClient(
|
|
|
|
host=MONGO_HOST.__wrapped__,
|
|
|
|
port=MONGO_PORT.__wrapped__,
|
|
|
|
)
|
2023-02-08 18:46:05 +00:00
|
|
|
log.debug("Created MongoDB client!")
|
2023-02-05 16:40:22 +00:00
|
|
|
|
|
|
|
yield client
|
|
|
|
|
|
|
|
log.info("Closing connection to MongoDB...")
|
|
|
|
client.close()
|
|
|
|
log.debug("Closed connection to MongoDB!")
|
|
|
|
|
|
|
|
|
|
|
|
__all__ = (
|
|
|
|
"mongo_client_from_config",
|
|
|
|
)
|