mongo-adapter


Namemongo-adapter JSON
Version 0.3.3 PyPI version JSON
download
home_pagehttps://github.com/moonso/mongo_adapter
SummaryA python interface to handle connection to a mongod instance
upload_time2021-11-15 16:39:34
maintainer
docs_urlNone
authorMåns Magnusson
requires_python
licenseMIT
keywords
VCS
bugtrack_url
requirements pymongo pytest mongomock
Travis-CI
coveralls test coverage No coveralls.
            
# 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




            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/moonso/mongo_adapter",
    "name": "mongo-adapter",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "M\u00e5ns Magnusson",
    "author_email": "mans.magnusson@scilifelab.se",
    "download_url": "https://files.pythonhosted.org/packages/4d/52/0c66cce3f99cddb4a24d45f0ea1b66d9099fcd530f2d7b9774a77d475a0d/mongo_adapter-0.3.3.tar.gz",
    "platform": "",
    "description": "\n# Mongo Adapter\n\n[![Build Status][travis-img]][travis-url]\n\nA python implementation of a mongo adapter.\n\nThe idea is to make a base class that handles the connection to a mongod instance.\nIt is nice to handle the connection in the same way for different python projects that involves a mongo database.\n\nThe Mongo Adapter takes a client as init argument and then we connect to a database with `setup(database)`, \nfortunately `mongo_adapter` can handle the client part as well.\n\n**Example:**\n\n```python\nfrom mongo_adapter import MongoAdapter, get_client\n\ndb_name = 'test'\nclient = get_client()\nadapter = MongoAdapter(client, db_name)\n\nassert adapter.db_name == db_name\n```\n\n## Testing\n\nThe package can be used for testing as well\n\n**Example:**\n\n```python\nfrom mongo_adapter import MongoAdapter, get_client\nimport mongomock\n\ndb_name = 'test'\nuri = \"mongomock://\"\nclient = get_client(uri=uri)\nadapter = MongoAdapter(client, db_name)\n\nassert isinsance(client, mongomock.MongoClient)\n```\n\n## installation\n\n**git:**\n\n```bash\ngit clone https://github.com/moonso/mongo_adapter\ncd mongo_adapter\npip install --editable .\n```\n\n**pip:**\n```bash\npip install mongo_adapter\n```\n\n\n## Intended usage\n\nThe intended usage is here illustrated with an example\n\n```python\nfrom mongo_adapter import MongoAdapter, get_client\n\nclass LibraryAdapter(MongoAdapter):\n    def setup(self, db_name='library'):\n        \"\"\"Overrides the basic setup method\"\"\"\n        if self.client is None:\n            raise SyntaxError(\"No client is available\")\n        if self.db is None:\n            self.db = self.client[db_name]\n            self.db_name = db_name\n\n        self.books_collection = self.db.book\n        self.user_collection = self.db.book\n\n    def add_book(self, title, author):\n        \"\"\"Add a book to the books collection\"\"\"\n        result = self.books_collection.insert_one(\n            {\n                'title': title,\n                'author': author\n            }\n        )\n        return result\n\nif __name__ == '__main__':\n    client = get_client()\n    adapter = LibraryAdapter(client, database='library')\n\n    adapter.add_book('Moby Dick', 'Herman Melville')\n\n```\n\n## API\n\n### Client\n\n```python\n\ndef check_connection(client):\n    \"\"\"Check if the mongod process is running\n\n    Args:\n        client(MongoClient)\n\n    Returns:\n        bool\n    \"\"\"\n\ndef get_client(host='localhost', port=27017, username=None, password=None,\n              uri=None, mongodb=None, timeout=20):\n    \"\"\"Get a client to the mongo database\n\n    Args:\n        host(str): Host of database\n        port(int): Port of database\n        username(str)\n        password(str)\n        uri(str)\n        timeout(int): How long should the client try to connect\n\n    Returns:\n        client(pymongo.MongoClient)\n\n    \"\"\"\n\n```\n\n### Adapter\n\n```python\nclass MongoAdapter(object):\n    \"\"\"Adapter for communicating with a mongo database\"\"\"\n    def __init__(self, client=None, db_name=None):\n        \"\"\"\n        Args:\n            client(MongoClient)\n            db_name(str)\n        \"\"\"\n        self.client = client\n        self.db = None\n        self.db_name = None\n        if (db_name and client):\n            self.setup(database)\n\n    def init_app(self, app):\n        \"\"\"Setup via Flask\"\"\"\n        host = app.config.get('MONGO_HOST', 'localhost')\n        port = app.config.get('MONGO_PORT', 27017)\n        self.db_name = app.config['MONGO_DBNAME']\n        self.client = app.extensions['pymongo']['MONGO'][0]\n        self.db = app.extensions['pymongo']['MONGO'][1]\n        LOG.info(\"connecting to database: %s:%s/%s\", host, port, self.db_name)\n\t\tself.setup(self.db_name)\n\n    def setup(self, db_name):\n        \"\"\"Setup connection to a database\n\n        Args:\n            db_name(str)\n            db(pymongo.Database)\n        \"\"\"\n        if self.client is None:\n            raise SyntaxError(\"No client is available\")\n        if self.db is None:\n            self.db = self.client[db_name]\n            self.db_name = db_name\n        LOG.info(\"Use database %s\", self.db_name)\n\n```\n\n\n\n[travis-url]: https://travis-ci.org/moonso/mongo_adapter\n[travis-img]: https://img.shields.io/travis/moonso/mongo_adapter/master.svg?style=flat-square\n\n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A python interface to handle connection to a mongod instance",
    "version": "0.3.3",
    "project_urls": {
        "Homepage": "https://github.com/moonso/mongo_adapter"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "e80346b7fa76cd79f06ceef0b73a526dfe6b00534317a9dee029079dc441e7d2",
                "md5": "670d12a2933c4b3e0ff35f6444f26db2",
                "sha256": "3bb8009e4f702128a64127086e1c6ebff5cc062b2d97d138a58b05570ded04bc"
            },
            "downloads": -1,
            "filename": "mongo_adapter-0.3.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "670d12a2933c4b3e0ff35f6444f26db2",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 6864,
            "upload_time": "2021-11-15T16:39:33",
            "upload_time_iso_8601": "2021-11-15T16:39:33.573257Z",
            "url": "https://files.pythonhosted.org/packages/e8/03/46b7fa76cd79f06ceef0b73a526dfe6b00534317a9dee029079dc441e7d2/mongo_adapter-0.3.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4d520c66cce3f99cddb4a24d45f0ea1b66d9099fcd530f2d7b9774a77d475a0d",
                "md5": "0f390cc4c22242369827ccacbddc3129",
                "sha256": "6f33891881bfce55af9bb2370d7ae143094b936f0e3730cb551f2eaa8c28fe08"
            },
            "downloads": -1,
            "filename": "mongo_adapter-0.3.3.tar.gz",
            "has_sig": false,
            "md5_digest": "0f390cc4c22242369827ccacbddc3129",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 6013,
            "upload_time": "2021-11-15T16:39:34",
            "upload_time_iso_8601": "2021-11-15T16:39:34.935592Z",
            "url": "https://files.pythonhosted.org/packages/4d/52/0c66cce3f99cddb4a24d45f0ea1b66d9099fcd530f2d7b9774a77d475a0d/mongo_adapter-0.3.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2021-11-15 16:39:34",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "moonso",
    "github_project": "mongo_adapter",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "pymongo",
            "specs": []
        },
        {
            "name": "pytest",
            "specs": []
        },
        {
            "name": "mongomock",
            "specs": []
        }
    ],
    "lcname": "mongo-adapter"
}
        
Elapsed time: 0.31771s