Pymongo 使用小记

发布 : 2015-11-30 分类 : Tools 浏览 :

Python 操作Mongodb库Pymongo的使用
1、安装
pip install pymongo或easy_install pymongo
详细介绍
2、使用
from pymongo import MongoClient
3、具体的代码

#!/usr/bin/python
#encoding=utf-8

import os
import sys
import time
import urllib
import argparse

from pymongo import MongoClient

def execute_repair(host,user,pwd):
    try:
        start = time.time()
        passwd = urllib.quote_plus(pwd)
        uri = 'mongodb://' + user + ':' + passwd + '@' + host
        log_uri = 'mongodb://' + user + '@' + host
        #print uri
        client = MongoClient(uri)
        #client.admin.authenticate(user,passwd)
        #print client.admin.command('buildinfo')
        db = client.log4net
        #print db.name
        result =  str(db.command("repairDatabase"))
        end = time.time()
        if result.find('ok') > 0:
            write_log(log_uri + '####OK' + '####' + str(end - start))
        else:
            write_log(log_uri + '####Error' + '####' + str(end - start))
    except Exception, e:
        write_log(user + '####' + str(e))

def write_log(text):
    log = open('/opt/repairlog.txt', 'a')
    log.write(time.strftime('%Y-%m-%d %H:%M:%S'))
    log.write('#########' + text)
    log.write('\n')
    log.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("host", help="mongod host based ip")
    parser.add_argument("user", help="mongodb admin user")
    parser.add_argument("pwd", help="mongodb admin passwd")
    #parser.add_argument("dbname", help="mongodb db name need repair")
    args = parser.parse_args()
    execute_repair(args.host,args.user,args.pwd)
本文作者 : Shiyf
原文链接 : https://www.shiyf.me/passages/pymongo-e4-bd-bf-e7-94-a8-e5-b0-8f-e8-ae-b0/
版权声明 : 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!

知识 & 情怀 | 二者兼得

微信扫一扫, 向我投食

微信扫一扫, 向我投食

支付宝扫一扫, 向我投食

支付宝扫一扫, 向我投食

留下足迹