Skip to main content

Mongo Adapter

Build Status

A python implementation of a mongo adapter.

The idea is to make a base class that handles the connection to a mongod instance. It is nice to handle the connection in the same way for different python projects that involves a mongo database.

The Mongo Adapter takes a client as init argument and then we connect to a database with setup(database), fortunately mongo_adapter can handle the client part as well.

Example:

from mongo_adapter import MongoAdapter, get_client

db_name = 'test'
client = get_client()
adapter = MongoAdapter(client, db_name)

assert adapter.db_name == db_name

Testing

The package can be used for testing as well

Example:

from mongo_adapter import MongoAdapter, get_client
import mongomock

db_name = 'test'
uri = "mongomock://"
client = get_client(uri=uri)
adapter = MongoAdapter(client, db_name)

assert isinsance(client, mongomock.MongoClient)

installation

git:

git clone https://github.com/moonso/mongo_adapter
cd mongo_adapter
pip install --editable .

pip:

pip install mongo_adapter

Intended usage

The intended usage is here illustrated with an example

from mongo_adapter import MongoAdapter, get_client

class LibraryAdapter(MongoAdapter):
    def setup(self, db_name='library'):
        """Overrides the basic setup method"""
        if self.client is None:
            raise SyntaxError("No client is available")
        if self.db is None:
            self.db = self.client[db_name]
            self.db_name = db_name

        self.books_collection = self.db.book
        self.user_collection = self.db.book

    def add_book(self, title, author):
        """Add a book to the books collection"""
        result = self.books_collection.insert_one(
            {
                'title': title,
                'author': author
            }
        )
        return result

if __name__ == '__main__':
    client = get_client()
    adapter = LibraryAdapter(client, database='library')

    adapter.add_book('Moby Dick', 'Herman Melville')

API

Client

def check_connection(client):
    """Check if the mongod process is running

    Args:
        client(MongoClient)

    Returns:
        bool
    """

def get_client(host='localhost', port=27017, username=None, password=None,
              uri=None, mongodb=None, timeout=20):
    """Get a client to the mongo database

    Args:
        host(str): Host of database
        port(int): Port of database
        username(str)
        password(str)
        uri(str)
        timeout(int): How long should the client try to connect

    Returns:
        client(pymongo.MongoClient)

    """

Adapter

class MongoAdapter(object):
    """Adapter for communicating with a mongo database"""
    def __init__(self, client=None, db_name=None):
        """
        Args:
            client(MongoClient)
            db_name(str)
        """
        self.client = client
        self.db = None
        self.db_name = None
        if (db_name and client):
            self.setup(database)

    def init_app(self, app):
        """Setup via Flask"""
        host = app.config.get('MONGO_HOST', 'localhost')
        port = app.config.get('MONGO_PORT', 27017)
        self.db_name = app.config['MONGO_DBNAME']
        self.client = app.extensions['pymongo']['MONGO'][0]
        self.db = app.extensions['pymongo']['MONGO'][1]
        LOG.info("connecting to database: %s:%s/%s", host, port, self.db_name)
		self.setup(self.db_name)

    def setup(self, db_name):
        """Setup connection to a database

        Args:
            db_name(str)
            db(pymongo.Database)
        """
        if self.client is None:
            raise SyntaxError("No client is available")
        if self.db is None:
            self.db = self.client[db_name]
            self.db_name = db_name
        LOG.info("Use database %s", self.db_name)

Release files for mongo-adapter 0.3.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mongo-adapter 0.3.3
File Size Uploaded
mongo_adapter-0.3.3.tar.gz 6.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for mongo-adapter 0.3.3
File Interpreter ABI Platform
mongo_adapter-0.3.3-py3-none-any.whl Python 3 none any Details

Total release size: 12.9 kB

Release files / mongo_adapter-0.3.3.tar.gz

Download URL mongo_adapter-0.3.3.tar.gz
Size 6.0 kB
Tags Source
SHA-256 checksum
How to use checksums
6f33891881bfce55af9bb2370d7ae143094b936f0e3730cb551f2eaa8c28fe08
BLAKE2b-256 checksum
How to use checksums
4d520c66cce3f99cddb4a24d45f0ea1b66d9099fcd530f2d7b9774a77d475a0d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.6.0 importlib_metadata/4.8.2 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.8

Release files / mongo_adapter-0.3.3-py3-none-any.whl

Download URL mongo_adapter-0.3.3-py3-none-any.whl
Size 6.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3bb8009e4f702128a64127086e1c6ebff5cc062b2d97d138a58b05570ded04bc
BLAKE2b-256 checksum
How to use checksums
e80346b7fa76cd79f06ceef0b73a526dfe6b00534317a9dee029079dc441e7d2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.6.0 importlib_metadata/4.8.2 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.8

Release history Release notifications | RSS feed

This release

0.3.3 This release

2 release files

0.3

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page