python3连接mongodb执行删除多数据操作

由于测试的原因,每次都需要测多种不同类型的账号数据,在下次测试前需要先删除数据重新测试,才能发现问题,所以觉得很有必要写一个mongodb删除数据的脚本~~~~

python连接mongodb

安装:pip install pymongo

 

代码部分:

def mongodata_del():

    file_path = os.path.join(p_path.data_path, config.read('excel', 'filename'))    #excel绝对路径
    sheetname=config.read('excel', 'account_sheet') #从配置文件读取表单名字
    xls = Excel(file_path, sheetname)   #实例化
    testdata=xls.read_excel()   #获取Excel数据
    # 从配置文件读取mongodb配置
    username=parse.quote_plus(config.read('mongodb','username'))    
    password=parse.quote_plus(config.read('mongodb','password'))
    host=config.read('mongodb', 'host')
    port=config.read('mongodb','port')
    uri='mongodb://{}:{}@{}:{}/admin'.format(username,password,host,port )
    client=MongoClient(uri)
    db=client[config.read('mongodb','dbname')]

 

 MongoDB连接——URI的标准格式

mongodb://[username:password@]host1[:port]

mongodb// 一个必需的前缀,用于标识这是一个字符串 标准连接格式
[username:password@]

客户端将在连接后尝试使用这些凭据登录到特定数据库。

如果用户名或密码包含at符号@, 分号 :, 斜杆 /, 或者百分号% , 请记得使用百分号编码消除歧义

host1[:port1]

运行mongod实例的主机和端口号

 

 

连接报错:ymongo.errors.InvalidURI

python使用账号密码连接mongodb报错,ymongo.errors.InvalidURI: Username and password must be escaped according to RFC 3986, use urllib.parse.quote_plus()

 

 

 

 

原因是mongodb根据RFC 3986转义用户名和密码,使用urllib.parse.quote_plus(),解决方法是:

from urllib import parse

username=parse.quote_plus(config.read('mongodb','username'))
password=parse.quote_plus(config.read('mongodb','password'))

excel处理需要删除的数据

   1、使用excel设计需要删除的账号以及关联的集合数据,方便读取进行删除,如下图:

  2、使用openpyxl进行excel操作

import openpyxl
from configparser import  RawConfigParser
from func.config_handler import config

from setting.set_path import p_path

import os
import sys
class Excel:
    def __init__(self,filename,sheetname):
        self.filename=filename
        self.sheetname=sheetname



    def open(self):
        self.wb = openpyxl.load_workbook(self.filename)
        self.sheet = self.wb[self.sheetname]


    def title(self):
        self.open()
        self.open()
        '获取表单最大行数,列数'
        rows = self.sheet.max_row
        columns = self.sheet.max_column
        self.wb.close()
        '获取第一行标题'
        headers = []
        for i in range(1, columns + 1):
            headers.append(self.sheet.cell(1, i).value)
        return headers


    def read_excel(self):
        self.open()
        '获取表单最大行数,列数'
        rows=self.sheet.max_row
        columns=self.sheet.max_column
        self.wb.close()
        '获取第一行标题'
        title=[]
        for i in range(1,columns+1):
            title.append(self.sheet.cell(1,i).value)
        '读取数据存储,使用字典格式存储一行数据,再把每行数据存储到列表'
        data=[]
        for row in range(2,rows+1):
            cell_dict = {}
            for column in range(1,columns+1):
                cell_dict[title[column-1]]=self.sheet.cell(row,column).value
            data.append(cell_dict)
        return data



    def write_excel(self,result,column):
        self.open()
        '将测试结果写入excel'
        rows=self.sheet.max_row
        for row in range(2,rows+1):
            self.sheet.cell(row,column).value=result
        self.wb.save(self.filename)
        self.wb.close()

 读取数据,进行删除数据操作

    for data_info in testdata:
        col=db[data_info['collection']] #;连接集合
        try:
            accountdata=eval(data_info['data']) #excel获取到的是字符串,需要eval获取字典
            result=col.delete_many(accountdata) #使用delete_many删除多条数据
            count = result.deleted_count    #获取删除数据的条数
            log.debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
            if count == 1:
                log.info('id为{},{}删除成功,具体详情是:{}'.format(data_info['id'],data_info['label'],result))
            else:
                log.info('id为{},{}没删除成功,数据不存在'.format(data_info['id'],data_info['label'],result))
        except Exception as e:
            log.error('id为{},{}删除报错,具体错误是'.format(data_info['id'],data_info['label'],e))
            raise e

全部代码

import openpyxl
from func.config_handler import config
from setting.set_path import p_path
from urllib import parse
from pymongo import MongoClient
from func.log_handler import log
from func.excel_handler import Excel


def mongodata_del():

    file_path = os.path.join(p_path.data_path, config.read('excel', 'filename'))    #excel绝对路径
    sheetname=config.read('excel', 'account_sheet') #从配置文件读取表单名字
    xls = Excel(file_path, sheetname)   #实例化
    testdata=xls.read_excel()   #获取Excel数据
    # 从配置文件读取mongodb配置
    username=parse.quote_plus(config.read('mongodb','username'))    
    password=parse.quote_plus(config.read('mongodb','password'))
    host=config.read('mongodb', 'host')
    port=config.read('mongodb','port')
    uri='mongodb://{}:{}@{}:{}/admin'.format(username,password,host,port )
    client=MongoClient(uri)
    db=client[config.read('mongodb','dbname')]


    for data_info in testdata:
        col=db[data_info['collection']] #;连接集合
        try:
            accountdata=eval(data_info['data']) #excel获取到的是字符串,需要eval获取字典
            result=col.delete_many(accountdata) #使用delete_many删除多条数据
            count = result.deleted_count    #获取删除数据的条数
            log.debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
            if count == 1:
                log.info('id为{},{}删除成功,具体详情是:{}'.format(data_info['id'],data_info['label'],result))
            else:
                log.info('id为{},{}没删除成功,数据不存在'.format(data_info['id'],data_info['label'],result))
        except Exception as e:
            log.error('id为{},{}删除报错,具体错误是'.format(data_info['id'],data_info['label'],e))
            raise e


if __name__ =="__main__":
    mdatadel=mongodata_del()

  

 

原文地址:https://www.cnblogs.com/nimantou/p/11850995.html