【问题标题】:context manger for mongo connection gives query result even after closing the connectionmongodb 连接的上下文管理器即使在关闭连接后也会给出查询结果
【发布时间】:2021-01-12 12:54:11
【问题描述】:

我正在使用 python3 为 mongoDB 连接编写上下文管理器。下面是代码。

from pymongo import MongoClient


class MongoDBConnectionManager(object):
    def __init__(self, db, collection):
        self.db = db
        self.collection = collection
        self.connection = None

    def __enter__(self):
        self.connection = MongoClient('localhost', '27017')
        self.collection.closed()  # closing it to see if i get the error or not
        db = self.connection[self.db]
        collection_connect = db[self.collection]
        return collection_connect

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.connection.close()


with MongoDBConnectionManager('my_db', 'my_collection') as mongo:
    data = mongo.find_one({'_id': 1}) 
    print(data)

我的问题是,在__enter__ method 之后self.connection = MongoClient('localhost', '27017') 我写了self.collection.closed(),不是假设关闭连接并在db = self.connection[self.db] 中给出错误。或者它会再次创建新的连接?

我做错了吗?它是为 mongoDB 创建和关闭连接的正确方法吗?还有如何确认连接已关闭?

我知道 MongoClient 也可用作上下文管理器。但我想知道自定义上下文管理器。

任何帮助将不胜感激!

提前致谢!

【问题讨论】:

    标签: python python-3.x mongodb


    【解决方案1】:

    您无需担心任何这些; MongoClient 在数据库级别为您处理连接池。无需打开和关闭与数据库、集合或任何东西的多个连接;只是:

    client = MongoClient('localhost', 27017)
    my_db = client['my_db']
    data = my_db.my_collection.find_one({'_id': 1})
    print(data)
    

    【讨论】:

    • 但是为什么在 self.collection.closed() 之后。它没有抛出错误
    • 老实说你的代码没有意义,所以我不能添加任何其他内容。
    • 在多线程环境中使用代码很有意义
    • 不,这没有任何意义。它甚至不运行。它没有在任何地方提到多线程。
    猜你喜欢
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 2012-09-29
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多