python连接mongodb副本集-插入测试数据脚本

[root@node250 python_scripts]# cat Mongodb_insert_data.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pymongo
from pymongo import MongoClient
from pymongo import ReadPreference
import time
import argparse
# 定义执行时长装饰器函数
def warps(*args):
    def deco(func):
        def _deco(*args, **kwargs):
            # 记录开始时间
            start = time.clock()
            # 回调原函数
            func(*args, **kwargs)
            # 记录结束时间
            end = time.clock()
            # 计算执行时长
            delat = end - start
            # 转换成ms输出
            print("delay:%sms" % (int(delat*1000)))
        return _deco
    return deco


# 连接副本集
def get_mongo_conn_url_replicaset(ip_port_list, user=None, pwd=None, set_name=None):
    url = 'mongodb://'
    if user is not None:
        if pwd is None:
            pwd = user
        url += '%s:%s@' % (user, pwd)
    url += ','.join(ip_port_list)
    if set_name is not None:
        url += '/?replicaSet=%s' % set_name
    return url
ip_port_list = ['172.16.1.250:27017', '172.16.1.251:27017', '172.16.1.252:27017']
conn_url = get_mongo_conn_url_replicaset(ip_port_list, "root", "root123.", "rs0")
conn = MongoClient(conn_url)
# 读写分离
db = conn.get_database('test', read_preference=ReadPreference.SECONDARY_PREFERRED)
# 定义连接的集合
collection = db.student


# 创建插入数据函数
def data_insert(num):
    try:
        for i in range(1, num):
            collection.insert({"name": "student"+str(i), "age": (i % 100), "city": "FuZhou"})
            print ("Insert data:",i)
    except Exception as e:
        print("insert data:", e)
# 创建查询数据函数,引用装饰器函数




@warps()
def data_select(num):
    try:
        count = collection.find().count()
        while count != num - 1:
            count = collection.find().count()
    except Exception as e:
        print("select data:", e)
# 创建删除数据函数
def data_delete():
    try:
        collection.remove({})
    except Exception as e:
        print("delete data:", e)
# 创建计算延迟时长函数




def data_delay(num):
    data_insert(num)
    data_select(num)


if __name__ == '__main__':
    # 定义脚本需要传入插入的数据量,默认值为1000,通过-n传入参数
    parser = argparse.ArgumentParser(description='insert data to mongodb number')
    parser.add_argument('-n', action='store', dest='num', type=int, required=False, default=1000)
    given_args = parser.parse_args()
    num = given_args.num
    data_insert(num)        #测试批量插入功能
    #data_delete()                #测试数据延迟脚本
    # data_delay(num)        #测试数据延迟脚本


使用方法:
[root@node250 python_scripts]# ./Mongodb_Delay_data_data.py -n 1000


分割线
感谢打赏
江西数库信息技术有限公司
YWSOS.COM 平台代运维解决方案
 评论
 发表评论
姓   名:

Powered by AKCMS