淺談Python接口對json串的處理方法
最近學習Python接口測試,對于接口測試完全小白。大概一周的學習成果進行總結(jié)。
1.接口測試:
目前涉及到的只是對簡單單一的接口進行參數(shù)傳遞,得到返回自。
2.關于各種概念:
2.1 http請求包含post方法、get方法。通過json串或XML傳遞,但后者未做研究
2.2 GET: 瀏覽器告訴服務器,只獲取頁面信息,并發(fā)送給我。
2.3 POST:瀏覽器告訴服務器想法不一些信息到某個網(wǎng)址,服務器需確保數(shù)據(jù)被存儲且只存儲一次。
2.4 HEAD:瀏覽器告訴服務器,給我消息頭,像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'])
粗略了解,待深入學習!
以上這篇淺談Python接口對json串的處理方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
在 Linux/Mac 下為Python函數(shù)添加超時時間的方法
這篇文章主要介紹了在 Linux/Mac 下為Python函數(shù)添加超時時間,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02
python實現(xiàn)可將字符轉(zhuǎn)換成大寫的tcp服務器實例
這篇文章主要介紹了python實現(xiàn)可將字符轉(zhuǎn)換成大寫的tcp服務器,通過tcp服務器端實現(xiàn)針對字符的轉(zhuǎn)換與返回功能,具有一定參考借鑒價值,需要的朋友可以參考下2015-04-04
python?chinesecalendar報錯:"no?available?data?for?ye
這篇文章主要介紹了python?chinesecalendar報錯:“no?available?data?for?year?{},?only?year?between?[{},?{}]?supported“的相關知識,需要的朋友可以參考下2023-03-03
Python中asyncore異步模塊的用法及實現(xiàn)httpclient的實例
asyncore即是一個異步的socket封裝,特別是dispatcher類中包含了很多異步調(diào)用的socket操作方法,非常犀利,下面我們就來講解Python中asyncore異步模塊的用法及實現(xiàn)httpclient的實例2016-06-06

