Make querying mongo DB async#169
Draft
EbiArnie wants to merge 4 commits into
Draft
Conversation
- Use the async connection from PyMongo - Manage connections in a lifespan manager. This ensures each worker gets an own AsyncPyMongoClient object - Adapt code to be async
- Some debug code to override the used mongo collection slipped through. Removed
bilalebi
requested changes
Jun 12, 2025
bilalebi
left a comment
Contributor
There was a problem hiding this comment.
This looks good to me, I suggested some minor changes, mainly related to error handling
| return self | ||
|
|
||
| async def __aexit__(self, *args): | ||
| print("DB exit") |
Contributor
There was a problem hiding this comment.
Suggested change
| print("DB exit") | |
| print("DB exit") | |
| await self.close() |
|
|
||
| @contextlib.asynccontextmanager | ||
| async def lifespan(app: Starlette) -> AsyncIterator[State]: | ||
| async with MongoDbClient(os.environ) as client: |
Contributor
There was a problem hiding this comment.
Suggested change
| async with MongoDbClient(os.environ) as client: | |
| try: | |
| async with MongoDbClient(os.environ) as client: | |
| logger.info("Lifespan start: MongoDbClient connected") | |
| yield {"db_client": client} | |
| logger.info("Lifespan end: MongoDbClient closing") | |
| except Exception as exc: | |
| logger.error("Error during lifespan: %s", exc, exc_info=True) | |
| raise |
| print("DB enter") | ||
| await self | ||
|
|
||
| host = self.config.get("MONGO_HOST").split(",") |
Contributor
There was a problem hiding this comment.
Suggested change
| host = self.config.get("MONGO_HOST").split(",") | |
| try: | |
| host = self.config.get("MONGO_HOST").split(",") | |
| port = int(self.config.get("MONGO_PORT")) | |
| user = self.config.get("MONGO_USER") | |
| password = self.config.get("MONGO_PASSWORD") | |
| client = AsyncMongoClient( | |
| host=host, | |
| port=port, | |
| username=user, | |
| password=password, | |
| ) | |
| self.mongo_client = client | |
| await client.aconnect() | |
| logger.info("Successfully connected to MongoDB at %s:%s", host, port) | |
| return self | |
| except Exception as exc: | |
| logger.error("Failed to connect to MongoDB at %s:%s - %s", host, port, exc, exc_info=True) | |
| raise RuntimeError(f"Could not connect to MongoDB at {host}:{port}") from exc |
This file contains hidden or 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Use async PyMongo
Use lifecycle to have a PyMongo object per worker
Make app async throughout