一、设计思路
1、先调接口,获取接口返回的数据,以字典形式存储;
2、通过sql语句查询源数据,以字典形式存储;
3、查询两个字典的差异,以及key相同value不同的数据;
二、脱敏代码
import unittest
import pymysql
import requests
class Checkdata(unittest.TestCase):
@classmethod
def setUpClass(cls):
pass
@classmethod
def tearDownClass(cls):
pass
def test_integralList0(self):
'''调取接口数据'''
url ='https://xxx'
r = requests.get(url=url)
self.assertEqual(r.status_code, 200) # 断言接口状态码200
data = r.json()
list = data['data']['hot_gossip']
dict1 = {}
# 注意:key值不能重复
for i in range(len(list)):
id = str(list[i]['url']).split('.')[1].split('/')[3]
title = list[i]['title']
dict1[id] = title
# 连接数据库
db = pymysql.connect("host","数据库名","用户名","密码")
cursor = db.cursor()
sql = "SELECT * FROM 表名 where + 查询条件;"
try:
# 执行sql语句
cursor.execute(sql)
result = cursor.fetchall()
dict2 = {}
for row in result:
dao_id = str(row[0])
dao_title=str(row[4])
dict2[dao_id] = dao_title
except Exception as e:
print("Error:unable to fecth data.Error info:%s" % e)
finally:
db.close()
# 数据对比,differ为所有差异
differ = set(dict1.items()) ^ set(dict2.items())
# diff_vals为key相同value不同
diff = dict1.keys()&dict2
diff_vals = [(k, dict1[k], dict2[k]) for k in diff if dict1[k] != dic2[k]]
if __name__ == '__main__':
unittest.main(verbosity=2)