一、設(shè)計(jì)思路
1盹沈、先調(diào)接口龄章,獲取接口返回的數(shù)據(jù),以字典形式存儲(chǔ)乞封;
2做裙、通過(guò)sql語(yǔ)句查詢?cè)磾?shù)據(jù),以字典形式存儲(chǔ)肃晚;
3锚贱、查詢兩個(gè)字典的差異,以及key相同value不同的數(shù)據(jù)关串;
二拧廊、脫敏代碼
import unittest
import pymysql
import requests
class Checkdata(unittest.TestCase):
? ? @classmethod
? ? def setUpClass(cls):
? ? ? ? pass
? ? @classmethod
? ? def tearDownClass(cls):
? ? ? ? pass
? ? def test_integralList0(self):
? ? ? ? '''調(diào)取接口數(shù)據(jù)'''
? ? ? ? url ='https://xxx'
? ? ? ? r = requests.get(url=url)
? ? ? ? self.assertEqual(r.status_code, 200)? ? # 斷言接口狀態(tài)碼200
? ? ? ? data = r.json()
? ? ? ? list = data['data']['hot_gossip']
? ? ? ? dict1 = {}
? ? # 注意:key值不能重復(fù)
? ? ? ? for i in range(len(list)):
? ? ? ? ? ? ? ? id = str(list[i]['url']).split('.')[1].split('/')[3]
? ? ? ? ? ? ? ? title = list[i]['title']? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? dict1[id] = title
? ? # 連接數(shù)據(jù)庫(kù)
? ? ? ? db = pymysql.connect("host","數(shù)據(jù)庫(kù)名","用戶名","密碼")
? ? ? ? cursor = db.cursor()
? ? ? ? sql = "SELECT * FROM 表名 where + 查詢條件;"
? ? ? ? try:
? ? ? ? ? ? # 執(zhí)行sql語(yǔ)句
? ? ? ? ? ? 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()
? ? ? ? # 數(shù)據(jù)對(duì)比,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)