您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)如何在Python中使用pymongo模塊對MongoDB數(shù)據(jù)庫進行操作,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
#!/usr/bin/python # coding=utf-8 #python實現(xiàn)對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的相關(guān)參數(shù) 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 #賦值屬性,通過該屬性執(zhí)行其他操作 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執(zhí)行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"}) #執(zhí)行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())
看完上述內(nèi)容,你們對如何在Python中使用pymongo模塊對MongoDB數(shù)據(jù)庫進行操作有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。