MongoClient对象作为全局变量

时间:2019-04-24 14:09:08

标签: python mongodb pymongo

我想为MongoDb创建一个数据访问层,但是我确实找到了两个不同的示例。第一个带有类:

class ProjectsDal:

    def __init__(self):
        # initializing the MongoClient, this helps to 
        # access the MongoDB databases and collections 
        self.client = MongoClient(host='localhost', port=27017)
        self.database = self.client['projects']


    def create(self, project):
        if project is not None:
            self.database.projects.insert(project.get_as_json())            
        else:
            raise Exception("Nothing to save, because project parameter is None")


    def read(self, project_id=None):
        if project_id is None:
            return self.database.projects.find({})
        else:
            return self.database.projects.find({"_id":project_id})

第二个是带有全局函数和全局变量的

#mdb_dal.py file

from pymongo import MongoClient, errors as mgex

try:
    _MDB_CLIENT = MongoClient('localhost', 27017)
    _MDB_DB = _MDB_CLIENT['db_test']

except mgex.PyMongoError as err:
    print('Ocorreu um erro ao tentar conectar-se à base de dados\n', err)
    raise


def single_insert_doc(collect: str, doc: dict):

    try:
        coll = _MDB_DB[collect]
        return coll.insert_one(doc).inserted_id

    except mgex.PyMongoError as err:
        print('Ocorreu um erro ao tentar persistir os dados\n', err)
        raise

我关心的是第二个示例中的全局变量_MDB_CLIENT_MDB_DB,因为它们是全局变量,因此它们的生存期很长。因此,应用程序将不断维护与数据库的开放连接。

这会给我带来麻烦吗?最推荐两种方法中的哪一种?

0 个答案:

没有答案