问题
import datetime
import pymongo
def get_yesterday():
"""
获取昨天的日期
"""
today = datetime.date.today()
oneday = datetime.timedelta(days=1)
yesterday = today - oneday
return str(yesterday)
class MongoUtil:
def __init__(self, host, port, database, table):
self.__client = pymongo.MongoClient(host=host, port=port)
self.__table = self.__client[database][table]
def __del__(self):
print("关闭连接")
self.__client.close()
def get_top10(self, day: str):
"""
# 2. 访问数据库, 取出top10
db.getCollection('tb_time_dirs').find({"day": "2021-09-09"}).sort({"visit_nums": -1}).limit(10)
"""
top = self.__table.find({"day": day}, {"_id": 0, "ips": 0}).sort("visit_nums", -1).limit(2)
for t in top:
print(t)
if __name__ == '__main__':
yester = get_yesterday()
mu = MongoUtil("172.31.162.41", 27017, "except_dir", "tb_time_dirs")
mu.get_top10(yester)
此时会打印出 “关闭连接” 但是程序不终止!!!
解决方法一: 手动销毁对象
import datetime
import pymongo
def get_yesterday():
"""
获取昨天的日期
"""
today = datetime.date.today()
oneday = datetime.timedelta(days=1)
yesterday = today - oneday
return str(yesterday)
class MongoUtil:
def __init__(self, host, port, database, table):
self.__client = pymongo.MongoClient(host=host, port=port)
self.__table = self.__client[database][table]
def __del__(self):
print("关闭连接")
self.__client.close()
def get_top10(self, day: str):
"""
# 2. 访问数据库, 取出top10
db.getCollection('tb_time_dirs').find({"day": "2021-09-09"}).sort({"visit_nums": -1}).limit(10)
"""
top = self.__table.find({"day": day}, {"_id": 0, "ips": 0}).sort("visit_nums", -1).limit(2)
for t in top:
print(t)
if __name__ == '__main__':
yester = get_yesterday()
mu = MongoUtil("172.31.162.41", 27017, "except_dir", "tb_time_dirs")
mu.get_top10(yester)
del mu
解决方法二: 使用上下文管理器
import datetime
import pymongo
def get_yesterday():
"""
获取昨天的日期
"""
today = datetime.date.today()
oneday = datetime.timedelta(days=1)
yesterday = today - oneday
return str(yesterday)
class MongoUtil:
def __init__(self, host, port, database, table):
self.__client = pymongo.MongoClient(host=host, port=port)
self.__table = self.__client[database][table]
# def __del__(self):
# print("__del__")
# self.__client.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('关闭数据库连接')
self.__client.close()
def get_top10(self, day: str):
"""
# 2. 访问数据库, 取出top10
db.getCollection('tb_time_dirs').find({"day": "2021-09-09"}).sort({"visit_nums": -1}).limit(10)
"""
top = self.__table.find({"day": day}, {"_id": 0, "ips": 0}).sort("visit_nums", -1).limit(2)
for t in top:
print(t)
if __name__ == '__main__':
yester = get_yesterday()
mu = MongoUtil("172.31.162.41", 27017, "except_dir", "tb_time_dirs")
with mu:
mu.get_top10(yester)
具体原因
不明
猜测与内存管理有关
源码的解释
def close(self):
"""Cleanup client resources and disconnect from MongoDB.
On MongoDB >= 3.6, end all server sessions created by this client by
sending one or more endSessions commands.
Close all sockets in the connection pools and stop the monitor threads.
If this instance is used again it will be automatically re-opened and
the threads restarted unless auto encryption is enabled. A client
enabled with auto encryption cannot be used again after being closed;
any attempt will raise :exc:`~.errors.InvalidOperation`.
.. versionchanged:: 3.6
End all server sessions created by this client.
"""