Skip to main content

A python interface to handle connection to a mongod instance

Project description


# Mongo Adapter

[![Build Status][travis-img]][travis-url]

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:**

```python
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:**

```python
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:**

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

**pip:**
```bash
pip install mongo_adapter
```


## Intended usage

The intended usage is here illustrated with an example

```python
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

```python

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

```python
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)

```



[travis-url]: https://travis-ci.org/moonso/mongo_adapter
[travis-img]: https://img.shields.io/travis/moonso/mongo_adapter/master.svg?style=flat-square



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

mongo_adapter-0.2.1.tar.gz (5.9 kB view details)

Uploaded Source

Built Distribution

mongo_adapter-0.2.1-py2.py3-none-any.whl (8.2 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file mongo_adapter-0.2.1.tar.gz.

File metadata

  • Download URL: mongo_adapter-0.2.1.tar.gz
  • Upload date:
  • Size: 5.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.12.4 setuptools/27.2.0 requests-toolbelt/0.8.0 tqdm/4.25.0 CPython/3.5.2

File hashes

Hashes for mongo_adapter-0.2.1.tar.gz
Algorithm Hash digest
SHA256 75d2e88d33d49632f9dd7bc34cd12304a7b8082c71d981e02c7903517d4db8f8
MD5 b4fbb44b18eaf1d23b5c90bf4c57985d
BLAKE2b-256 48046a8b6389a2b235f4fa0ee4ce18cdfae3c4c3ad6cfd9f8872d42e13e5a786

See more details on using hashes here.

File details

Details for the file mongo_adapter-0.2.1-py2.py3-none-any.whl.

File metadata

  • Download URL: mongo_adapter-0.2.1-py2.py3-none-any.whl
  • Upload date:
  • Size: 8.2 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.12.4 setuptools/27.2.0 requests-toolbelt/0.8.0 tqdm/4.25.0 CPython/3.5.2

File hashes

Hashes for mongo_adapter-0.2.1-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 78b3d07f0852c626a126ba17801cf8ca24ad520c764df319f0db5c44f048e96e
MD5 318481df7ce445a0fafebab6a38c1b86
BLAKE2b-256 67efe8e475b30221391088a90d8dc9b8189b71c286fe45c356ec02e2f612dab8

See more details on using hashes here.

Supported by

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