【數(shù)據(jù)準(zhǔn)確性】接口數(shù)據(jù)與數(shù)據(jù)庫(kù)數(shù)據(jù)對(duì)比

一、設(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)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容