淺談Python接口對json串的處理方法
最近學(xué)習(xí)Python接口測試,對于接口測試完全小白。大概一周的學(xué)習(xí)成果進行總結(jié)。
1.接口測試:
目前涉及到的只是對簡單單一的接口進行參數(shù)傳遞,得到返回自。
2.關(guān)于各種概念:
2.1 http請求包含post方法、get方法。通過json串或XML傳遞,但后者未做研究
2.2 GET: 瀏覽器告訴服務(wù)器,只獲取頁面信息,并發(fā)送給我。
2.3 POST:瀏覽器告訴服務(wù)器想法不一些信息到某個網(wǎng)址,服務(wù)器需確保數(shù)據(jù)被存儲且只存儲一次。
2.4 HEAD:瀏覽器告訴服務(wù)器,給我消息頭,像get那樣被接收。
2.5 Python對數(shù)據(jù)的處理模塊可以使用urllib、urllib2模塊或requests模塊
3.urllib、urllib2實例
#coding=utf_8 import urllib2,urllib import json import unittest,time,re class APITest(): """ 接口測試類 """ def api_test(self, method, url, getparams, postparams): str1 = '' #GET方法調(diào)用 if method == 'GET': if getparams != "": for x in getparams: str1 = str1 + x + '=' + urllib2.quote(str(getparams.get(x))) if len(getparams) > 2: str1 = str1 + "&" url = url + "&" + str1 result = urllib2.urlopen(url).read() #POST方法調(diào)用 if method=='POST': if postparams != "": data = urllib.urlencode(postparams) req = urllib2.Request(data) response = urllib2.urlopen(req) result = response.read() #result轉(zhuǎn)為json數(shù)據(jù) jsdata = json.loads(result) return jsdata class APIGetRes(unittest.TestCase): def test_call(self): api = APITest() getparams={'keyword':'測試'} postparams='' data = api.api_test('GET','http://api.zhongchou.cn/deal/list?v=1',getparams,postparams) print data if (data['errno']!=""): self.assertEqual(0, data['errno']) print"接口 deal/list-------------OK!" else: print"接口 deal/list-------------Failure!" self.assertEqual(0, data['errno']) if __name__ == '__main__': unittest.main()
Requests實例
#coding=utf_8 import requests import json import unittest,time,re class APIGetAdlis(unittest.TestCase): def test_call(self): github_url='http://api.zhongchou.cn/deal/list?v=1' data = json.dumps({'keyword':'測試'}) resp = requests.post(github_url,data) print resp.json #if (data['errno']!=''): # self.assertEqual(0, data['errno']) # print"接口 deal/list-------------OK!" #else: # print"接口 deal/list-------------Failure!" # self.assertEqual(0, data['errno'])
粗略了解,待深入學(xué)習(xí)!
以上這篇淺談Python接口對json串的處理方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python讀取excel表格生成erlang數(shù)據(jù)
這篇文章主要為大家詳細介紹了python讀取excel表格生成erlang數(shù)據(jù),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08Python?matplotlib實戰(zhàn)之箱型圖繪制
箱型圖(Box?Plot),也稱為盒須圖或盒式圖,是一種用作顯示一組數(shù)據(jù)分布情況的統(tǒng)計圖,因型狀如箱子而得名,本文主要為大家介紹了如何使用Matplotlib繪制箱型圖,需要的小伙伴可以參考下2023-08-08Python中的 ansible 動態(tài)Inventory 腳本
這篇文章主要介紹了Python中的 ansible 動態(tài)Inventory 腳本,本章節(jié)通過實例代碼從mysql數(shù)據(jù)作為數(shù)據(jù)源生成動態(tài)ansible主機為入口介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2020-01-01