1 #@File : mongoDB_Insert.py
2 #@Time : 2018/12/13 10:28
3 importos,time,configparser4 from pymongo importMongoClient5
6 classMongoDB():7
8 def __init__(self):9 '''
10 初始化操作11 :param host:MongoDB Ip12 :param port: MongoDB Port13 :param db_name: MongoDB Name14 :param collection: MongoDB Collection Name15 '''
16 self.conf_path =Config().get_config_path()17 self.host = Config().read_config(self.conf_path,"MONGODB_CONF","host")18 self.port = int(Config().read_config(self.conf_path,"MONGODB_CONF","port"))19 self.db_name = Config().read_config(self.conf_path,"MONGODB_CONF","db_name")20 self.collection = Config().read_config(self.conf_path,"MONGODB_CONF","collection_name")21 self.insert_data = Config().read_config(self.conf_path,"INSERT_DATA","insert_data")22 self.insert_num =int((Config().read_config(self.conf_path,"INSERT_NUM","insert_num")))23 self.insert_time =int((Config().read_config(self.conf_path,"INSERT_TIME","insert_time")))24
25 defconnecting(self):26 '''
27 DB连接28 :return: my_collection29 '''
30 try:31 conn = MongoClient(host=self.host,port=self.port)32 my_db =conn[self.db_name]33 my_collection =my_db[self.collection]34 returnmy_collection35 exceptException as e:36 print('连接失败!错误原因:{}'.format(e))37 raisee38
39 defstart_insert_num(self):40 '''
41 插入数据,配置共插入多少数据42 :return:None43 '''
44 my_set =self.connecting()45 try:46 i =047 start_time = int(time.time() * 1000)48 whileTrue:49 my_set.insert((eval((self.insert_data))))50 i += 1
51 print('插入{}条数据。'.format(i))52 if i ==self.insert_num:53 break
54 end_time = int(time.time() * 1000)55 print('插入数据成功。共插入{}条数据,耗时{}ms。'.format(self.insert_num,end_time -start_time))56 input('按回车键结束程序......')57 exceptException as e:58 print('插入数据失败!失败原因:{}'.format(e))59 raisee60
61 defstart_insert_time(self):62 '''
63 插入数据,配置共运行时间64 :return:None65 '''
66 my_set =self.connecting()67 try:68 i =069 start_time = int(time.time() * 1000)70 whileTrue:71 my_set.insert((eval((self.insert_data))))72 i += 1
73 print('插入{}条数据。'.format(i))74 if int(time.time()*1000) >= (start_time+self.insert_time):75 break
76 print('插入数据成功。共插入{}条数据,耗时{}ms。'.format(i,self.insert_time))77 input('按回车键结束程序......')78 exceptException as e:79 print('插入数据失败!失败原因:{}'.format(e))80 raisee81
82 classConfig():83 '''
84 读取配置文件类85 '''
86
87 defget_config_path(self):88 '''
89 获取配置文件的绝对路径90 :return: 配置文件的绝对路径91 '''
92 try:93 conf_path = os.path.split(os.path.realpath(__file__))[0] + r"\DB.conf"
94 returnconf_path95 exceptException as e:96 print('出错啦!!!错误原因:{}'.format(e))97 raisee98
99 defread_config(self,conf_path,section,option):100 '''
101 读取配置文件102 :param conf_path:配置文件绝对路径103 :param section:104 :param option:105 :return: 配置文件内的value106 '''
107 try:108 cf =configparser.ConfigParser()109 cf.read(conf_path)110 value = cf.get(section=section, option=option)111 returnvalue112 exceptException as e:113 print('读取配置文件失败!失败原因:{}'.format(e))114 raisee115
116 if __name__ == '__main__':117 #两种不同的运行方式
118 #MongoDB().start_insert_num()
119 MongoDB().start_insert_time()