掌握了前面幾節(jié)的的內(nèi)容,就可以做一些簡(jiǎn)單的http協(xié)議接口的請(qǐng)求發(fā)送了,但是這些還不夠。HTTP協(xié)議是一個(gè)無(wú)狀態(tài)的應(yīng)用層協(xié)議,也就是說(shuō)前后兩次請(qǐng)求是沒(méi)有任何關(guān)系的,那如果我們測(cè)試的接口之前有相互依賴關(guān)系怎么辦呢(比如我要在博客園發(fā)文章,是需要先登錄的),這時(shí)我們就要用到cookie和session技術(shù)來(lái)保持客戶端與服務(wù)器端連接的狀態(tài),這也就是本節(jié)要介紹的內(nèi)容:
一、Cookie: 1、獲取cookie: # -*- coding:utf-8 -*- #獲取cookie import requests import json url = "https://www.baidu.com/" r = requests.get(url) #將RequestsCookieJar轉(zhuǎn)換成字典 c = requests.utils.dict_from_cookiejar(r.cookies) print r.cookies print c for a in r.cookies: print a.name,a.value 輸出: <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]> {'BDORZ': '27315'} BDORZ 27315
二、發(fā)送cookie: # -*- coding:utf-8 -*- #發(fā)送cookie到服務(wù)器 import requests import json host = "http:///" endpoint = "cookies"
二、Session 1、保持會(huì)話同步: # -*- coding:utf-8 -*- import requests import json host = "http:///" endpoint = "cookies" url = ''.join([host,endpoint]) url1 = "http:///cookies/set/sessioncookie/123456789" r = requests.get(url) print r.text 輸出:
2、保存會(huì)話信息: # -*- coding:utf-8 -*- import requests import json host = "http:///" endpoint = "headers" url = ''.join([host,endpoint]) header1 = {"testA":"AAA"} header2 = {"testB":"BBB"} s = requests.session() #初始化一個(gè)session對(duì)象 s.headers.update(header1) #已經(jīng)存在于服務(wù)中的信息 r = s.get(url,headers=header2) #發(fā)送新的信息 print r.text 輸出: { "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Host": "", "Testa": "AAA", "Testb": "BBB", "User-Agent": "python-requests/2.18.1" } }
3、刪除已存在的會(huì)話信息,保存為None # -*- coding:utf-8 -*- import requests import json host = "http:///" endpoint = "headers" url = ''.join([host,endpoint]) header1 = {"testA":"AAA"} header2 = {"testB":"BBB"} s = requests.session() #初始化一個(gè)session對(duì)象 s.headers.update(header1) #已經(jīng)存在于服務(wù)中的信息 r = s.get(url,headers=header2) #發(fā)送新的信息 print r.text print '--------' s.headers['testA'] = None #刪除會(huì)話里的信息testA r1 = s.get(url,headers = header2) print r1.text { "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Host": "", "Testa": "AAA", "Testb": "BBB", "User-Agent": "python-requests/2.18.1" } } -------- { "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Host": "", "Testb": "BBB", "User-Agent": "python-requests/2.18.1" } }
4、提供默認(rèn)數(shù)據(jù): s = requests.Session() s.auth = ('user', 'pass') s.headers.update({'x-test': 'true'}) # both 'x-test' and 'x-test2' are sent s.get('http:///headers', headers={'x-test2': 'true'})
參考: |
|