【发布时间】: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