pymongo的使用方法

Posted 铠甲巨人

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pymongo的使用方法相关的知识,希望对你有一定的参考价值。

通过pymongo实现python对Mongodb的操作。

 

具体看python代码

#!/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())

 

以上是关于pymongo的使用方法的主要内容,如果未能解决你的问题,请参考以下文章

Pymongo 排序错误

MongoDB pymongo模块

使用 flask_pymongo 时身份验证失败

pymongo 无法检索文件

Pymongo:使用 $setOnInsert 错误进行批量更新

无法使用 pymongo 删除 mongodb 文档