Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python OOP: how to share a MongoDB connection with all classes

I'm working on a Python OOP project. I have to deal with MongoDB interaction but I don't want to use an ODM like mongoengine.

What I want is to share a main Mongo connection with all classes that have to interact with it. I think that using a main DB class could be a good idea and I have two solutions in mind.

Solution A Connection at class level

mydb.py

from pymongo import MongoClient

class MyMongoDB(object):

    _client = MongoClient('localhost', 27017)
    db = _client['name_of_the_db']

And in other classes:

from mydb import MyMongoDB

class Foo(object):

    _db_collection = MyMongoDB.db.foo_collection

    def __init__(self):
       pass

    def set_data(self, data):
       Foo._db_collection.insert_one(data)

Solution A Connection at instance level

mydb.py

from pymongo import MongoClient

class MyMongoDB(object):

    def __init__(self):
        _client = MongoClient('localhost', 27017)
        db = _client['name_of_the_db']

And in other classes:

from mydb import MyMongoDB

class Foo(object):

    _db_collection = MyMongoDB().db.foo_collection

    def __init__(self):
       pass

    def set_data(self, data):
       Foo._db_collection.insert_one(data)

In solution A I have one main connection even if I import the MongoDB class in a lot of modules.

In solution B I have one new instance for each import

I think that solution A is the proper way to do the trick. Isn't it? Are they better approaches?

like image 729
floatingpurr Avatar asked Dec 24 '16 15:12

floatingpurr


1 Answers

Python makes this simple. Have a module-level global variable:

client = MongoClient()

If that's in a module like "my_db.py" then elsewhere you can access the client like this:

from my_db import client

There's various bigotries against global variables in other programming languages, but in Python it's the simplest way to share an object throughout your program.

like image 63
A. Jesse Jiryu Davis Avatar answered Nov 01 '22 10:11

A. Jesse Jiryu Davis