The way I connect to Mongo and disconnect:
class Database:
def connect(self):
self.client = MongoClient(self.uri)
def close(self):
if self.client:
self.client.close()
def __enter__(self):
if self.is_not_connected():
self.connect()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
And I use with
to open and close a connection with Mongo. I want to track the number of opened connections, every time I open and close a connection. Just a simple print will do. But how do I get to the field that contains the number of connections? I looked at dir
of self.client
but it does not have a special method method for. I want to know the number of connections in runtime. How can I do it?
One way to approach it could be to add a counter as a class variable which increments and decrements the total number of connections upon calling the open och close methods. Something like the below:
class Database:
num_of_connections = 0
def connect(self):
Database.num_of_connections += 1
self.client = MongoClient(self.uri)
def close(self):
if self.client:
Database.num_of_connections -= 1
self.client.close()
def __enter__(self):
if self.is_not_connected():
self.connect()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def active_connections(self):
print(Database.num_of_connections)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.