本文实例讲述了Python使用pymongo模块操作MongoDB的方法。分享给大家供大家参考,具体如下:
通过pymongo实现python对Mongodb的操作。
具体看python代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
#!/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程序设计有所帮助。
原文链接:http://www.cnblogs.com/ArmoredTitan/p/Mongodb.html