Skip to content

Make querying mongo DB async #169

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: develop
Choose a base branch
from
Draft

Conversation

EbiArnie
Copy link
Contributor

@EbiArnie EbiArnie commented Jun 6, 2025

Use async PyMongo
Use lifecycle to have a PyMongo object per worker
Make app async throughout

EbiArnie added 4 commits June 6, 2025 13:36
- 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
Copy link
Contributor

@bilalebi bilalebi left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(",")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants