今天就跟大家聊聊有关如何在Python中使用pymongo模块对MongoDB数据库进行操作,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
#!/usr/bin/python # coding=utf-8 #python实现对MongoDB的操作 #需要安装python2、pymongo、安装pymongo可能需要pip,logging打印日志 #改脚本主要功能就是每5秒改一次mongodb中存储的ip,5秒后再改回来 import pymongo import logging import datetime import os import time import traceback import sys,gc # 初始化logging logging.basicConfig(level=logging.NOTSET, format='%(asctime)s %(filename)s[line:%(lineno)d] [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filename='clear_screenshot_based_on_db.log', filemode='a') # set to print log to console at the same time console = logging.StreamHandler() console.setLevel(logging.NOTSET) formatter = logging.Formatter('%(asctime)s %(name)s [%(levelname)s] %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) class MongoDB_Util(): #写一个类,用于实例化pymongo对象以及对mongo的增删改查 def __init__(self, user, password, host, port, database, max_pool_size=2): try: client = pymongo.MongoClient(host=host, port=port, maxPoolSize=max_pool_size) #实例化对象,需要mongo的相关参数 if client == None: logging.error( "MongoDB_Util.__init__ : Initialize mongodb client object error,host:%s port:%s" % ( host, port)) raise Exception("Initialize mongodb client object error") try: admin_db = client['admin'] #指定连接的库 admin_db.authenticate(user, password) #身份验证 self.persist_db = admin_db #赋值属性,通过该属性执行其他操作 except Exception as exp: logging.error( "MongoDB_Util.__init__ : Authtication failed,host:%s port:%s database:%s user:%s password:%s" % (host, port, database, user, password)) raise exp except Exception as exp: logging.error( "MongoDB_Util.__init__ : Exception has occured : %s" % str(sys.exc_info()[1])) raise exp def update(self): #update方法,对mongodb执行update操作 tom = None try: if self.persist_db == None: logging.error('MongoDB_Util.delete : Persist object has not been initialised') raise Exception('Persist object has not been initialised') collection = self.persist_db['fuzzing_agent.configuration'] #链接fuzzing_agent.configuration表 abc=collection.find({"default_value" : "10.10.1.179"}) #执行find命令 for i in abc: tom = i["default_value"] if tom == "10.10.1.179": #判断该值是否为179,如果是则通过update改为134 collection.update({"default_value" : "10.10.1.179"}, {'$set':{'default_value': '10.10.1.134'}}) collection.update({"default_value" : "10.10.1.179:/run/media/root/disk01/fuzzing"}, {'$set':{"default_value" :"10.10.1.134:/run/media/root/disk01/fuzzing"}}) logging.debug("179 > 134") time.sleep(5) else: collection.update({"default_value" : "10.10.1.134"}, {'$set':{'default_value': '10.10.1.179'}}) collection.update({"default_value" : "10.10.1.134:/run/media/root/disk01/fuzzing"}, {'$set':{"default_value" :"10.10.1.179:/run/media/root/disk01/fuzzing"}}) logging.debug("134 > 179") time.sleep(5) return except Exception as exp: logging.error('Mongodb_Util.delete : Exception has occured : ' + str(sys.exc_info()[1])) raise exp def change_ip(mongodb_host) : result = False try : mongo_util = MongoDB_Util('username', 'password', mongodb_host, 27017, 'admin',max_pool_size = 2) #用户名,密码,mongodb的Ip,端口,连接库,连接池 mongo_util.update() result = True except : logging.error('change_ip: Exception has occured : ' + traceback.format_exc()) finally: return result if __name__ == '__main__' : while True : try : if change_ip(mongodb_host = '127.0.0.1') : #mongodb的ip地址 logging.debug('update is done !!!') else : logging.error('not update done') except : logging.error('main : Exception has occured : ' + traceback.format_exc()) finally: logging.debug("one loop %s" %datetime.datetime.now())
看完上述内容,你们对如何在Python中使用pymongo模块对MongoDB数据库进行操作有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。