Skip to main content

Singleton MongoDB client for AWS Lambda and serverless environments

Project description

actvalue.mongo-client

PyPI version Python versions License

Singleton client for MongoDB connection

Install

pip install actvalue.mongo-client

Or with uv:

uv add actvalue.mongo-client

Client Usage

The client is used to create and share MongoDB connection pool.

import asyncio
import os
from mongo_client import MongoDbConnection

# Initialize your connection parameters and optionally set pool size
os.environ['MONGO_URL'] = 'mongodb+srv://<your-connection>/database'
os.environ['MONGO_POOL_SIZE'] = '5'  # default value

# Create a singleton instance at module level
mongo = MongoDbConnection()

async def main():
    # Create connection pool if not existing already
    db = await mongo.get_db()
    users = db["users"]
    await users.insert_one({"username": "test123", "password": "test123"})
    
    # Some other time, some other place in code
    # Connection pool is reused
    db = await mongo.get_db()
    user = await users.find_one({"username": "test123"})
    print(user)

asyncio.run(main())

AWS Lambda Usage

Perfect for serverless environments where connection reuse is critical:

import os
from mongo_client import MongoDbConnection

# Set environment variables (typically from Lambda configuration)
os.environ['MONGO_URL'] = 'mongodb+srv://...'
os.environ['MONGO_POOL_SIZE'] = '5'

async def lambda_handler(event, context):
    # IMPORTANT: Initialize within handler due to Python asyncio event loop limitations
    # Each Lambda invocation may create a new event loop, and AsyncMongoClient
    # is bound to the event loop it was created on
    mongo = MongoDbConnection()
    
    db = await mongo.get_db()
    collection = db["my_collection"]
    
    result = await collection.find_one({"_id": event["id"]})
    return {"statusCode": 200, "body": result}

⚠️ Python Lambda Note: Unlike the TypeScript version, the Python client should be initialized inside the handler function. This is because Python's AsyncMongoClient binds to the asyncio event loop at creation time. AWS Lambda may create new event loops between invocations, causing "Cannot use AsyncMongoClient in different event loop" errors if the instance is created at module level.

Features

  • 🚀 Async/await support with PyMongo 4.0+
  • 🔄 Singleton pattern for connection reuse
  • 🔒 Thread-safe connection initialization
  • ⚙️ Environment-based configuration
  • 📦 Connection pooling optimized for serverless
  • ⏱️ Configurable timeouts and pool size
  • 🎯 Designed for AWS Lambda and similar platforms

Environment Variables

  • MONGO_URL: MongoDB connection string (required)
  • MONGO_POOL_SIZE: Connection pool size (optional, default: "5")

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

actvalue_mongo_client-1.0.0.tar.gz (41.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

actvalue_mongo_client-1.0.0-py3-none-any.whl (4.0 kB view details)

Uploaded Python 3

File details

Details for the file actvalue_mongo_client-1.0.0.tar.gz.

File metadata

  • Download URL: actvalue_mongo_client-1.0.0.tar.gz
  • Upload date:
  • Size: 41.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for actvalue_mongo_client-1.0.0.tar.gz
Algorithm Hash digest
SHA256 4dea4b42c5d69235f0cdea862747b0916f2fba0592c61c0296566b1461b85638
MD5 8dabcc8fb37037a4ab2e569dd2f91152
BLAKE2b-256 3c754c975b4f746f2531ead0cbe38d47be72077bf071d764bf0cb975dbffae47

See more details on using hashes here.

File details

Details for the file actvalue_mongo_client-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for actvalue_mongo_client-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2a277d23cc3165973e0bb0622d434b7140525f103c1379e719e36475b1e45272
MD5 b2af8362ec921c3de9bae6a224306762
BLAKE2b-256 db42859a0b4e86e207c30e181ac4a049ef064d430d7705f672915a2cec26fb2c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page