由於測試的原因,每次都需要測多種不同類型的賬號數據,在下次測試前需要先刪除數據重新測試,才能發現問題,所以覺得很有必要寫一個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()