




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
第Python接口自動化淺析requests請求封裝原理目錄以下主要介紹如何封裝請求將常用的get、post請求封裝起來get請求源碼:post請求源碼:再來研究下request源碼:直接調(diào)用request函數(shù)在上一篇Python接口自動化測試系列文章:Python接口自動化淺析Token應(yīng)用原理,介紹token基本概念、運(yùn)行原理及在自動化中接口如何攜帶token進(jìn)行訪問。
以下主要介紹如何封裝請求
還記得我們之前寫的get請求、post請求么?
大家應(yīng)該有體會,每個請求類型都寫成單獨(dú)的函數(shù),代碼復(fù)用性不強(qiáng)。
接下來將請求類型都封裝起來,自動化用例都可以用這個封裝的請求類進(jìn)行請求
將常用的get、post請求封裝起來
importrequests
classRequestHandler:
defget(self,url,**kwargs):
"""封裝get方法"""
#獲取請求參數(shù)
params=kwargs.get("params")
headers=kwargs.get("headers")
try:
result=requests.get(url,params=params,headers=headers)
returnresult
exceptExceptionase:
print("get請求錯誤:%s"%e)
defpost(self,url,**kwargs):
"""封裝post方法"""
#獲取請求參數(shù)
params=kwargs.get("params")
data=kwargs.get("data")
json=kwargs.get("json")
try:
result=requests.post(url,params=params,data=data,json=json)
returnresult
exceptExceptionase:
print("post請求錯誤:%s"%e)
defrun_main(self,method,**kwargs):
判斷請求類型
:parammethod:請求接口類型
:paramkwargs:選填參數(shù)
:return:接口返回內(nèi)容
ifmethod=='get':
result=self.get(**kwargs)
returnresult
elifmethod=='post':
result=self.post(**kwargs)
returnresult
else:
print('請求接口類型錯誤')
if__name__=='__main__':
#以下是測試代碼
#get請求接口
url='https://api.apiopen.top/getJokepage=1count=2type=video'
res=RequestHandler().get(url)
#post請求接口
url2=':8000/user/login/'
payload={
"username":"vivi",
"password":"123456"
res2=RequestHandler().post(url2,json=payload)
print(res.json())
print(res2.json())
請求結(jié)果如下:
'message':'成功!',
'result':[{'sid':'31004305',
'text':'羊:師傅,理個發(fā),稍微修一下就行',
'type':'video',
'thumbnail':'/picture/2025/0410/5e8fbf227c7f3_wpd.jpg',
'video':'/video/2025/0410/5e8fbf227c7f3_wpd.mp4',
'images':None,
'up':'95',
'down':'1',
'forward':'0',
'comment':'25',
'uid':'23189193',
'name':'青川小舟',
'header':'/profile/large/2025/12/24/5e01934bb01b5_mini.jpg',
'top_comments_content':None,
'top_comments_voiceuri':None,
'top_comments_uid':None,
'top_comments_name':None,
'top_comments_header':None,
'passtime':'2025-04-1201:43:02'},
{'sid':'30559863',
'text':'機(jī)器人女友,除了不能生孩子,其他的啥都會,價(jià)格239000元',
'type':'video',
'thumbnail':'/picture/2025/0306/5e61a41172a1b_wpd.jpg',
'video':'/video/2025/0306/5e61a41172a1b_wpd.mp4',
'images':None,'up':'80','down':'6',
'forward':'3',
'comment':'20',
'uid':'23131273',
'name':'水到渠成',
'header':'/profile/large/2025/07/04/5d1d90349cd1a_mini.jpg',
'top_comments_content':'為游戲做的秀',
'top_comments_voiceuri':'',
'top_comments_uid':'10250040',
'top_comments_name':'不得姐用戶',
'top_comments_header':'/profile',
'passtime':'2025-04-1120:43:49'}]}
{'token':'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6InZpdmkiLCJleHAiOjE1ODY4NTc0MzcsImVtYWlsIjoidml2aUBxcS5jb20ifQ.k6y0dAfNU2o9Hd9LFfxEk1HKgczlQfUaKE-imPfTsm4',
'user_id':1,
'username':'vivi'}
這樣就完美了嗎,no,no,no。
以上代碼痛點(diǎn)如下:
代碼量大:只是封裝了get、post請求,加上其他請求類型,代碼量較大;
缺少會話管理:請求之間如何保持會話狀態(tài)。
我們再來回顧下get、post等請求源碼,看下是否有啥特點(diǎn)。
get請求源碼:
defget(url,params=None,**kwargs):
r"""SendsaGETrequest.
:paramurl:URLforthenew:class:`Request`object.
:paramparams:(optional)Dictionary,listoftuplesorbytestosend
inthequerystringforthe:class:`Request`.
:param\*\*kwargs:Optionalargumentsthat``request``takes.
:return::class:`ResponseResponse`object
:rtype:requests.Response
kwargs.setdefault('allow_redirects',True)
returnrequest('get',url,params=params,**kwargs)
post請求源碼:
defpost(url,data=None,json=None,**kwargs):
r"""SendsaPOSTrequest.
:paramurl:URLforthenew:class:`Request`object.
:paramdata:(optional)Dictionary,listoftuples,bytes,orfile-like
objecttosendinthebodyofthe:class:`Request`.
:paramjson:(optional)jsondatatosendinthebodyofthe:class:`Request`.
:param\*\*kwargs:Optionalargumentsthat``request``takes.
:return::class:`ResponseResponse`object
:rtype:requests.Response
returnrequest('post',url,data=data,json=json,**kwargs)
仔細(xì)研究下,發(fā)現(xiàn)get、post請求返回的都是request函數(shù)。
再來研究下request源碼:
defrequest(method,url,**kwargs):
"""Constructsandsendsa:class:`RequestRequest`.
:parammethod:methodforthenew:class:`Request`object.
:paramurl:URLforthenew:class:`Request`object.
:paramparams:(optional)Dictionary,listoftuplesorbytestosend
inthequerystringforthe:class:`Request`.
:paramdata:(optional)Dictionary,listoftuples,bytes,orfile-like
objecttosendinthebodyofthe:class:`Request`.
:paramjson:(optional)AJSONserializablePythonobjecttosendinthebodyofthe:class:`Request`.
:paramheaders:(optional)DictionaryofHTTPHeaderstosendwiththe:class:`Request`.
:paramcookies:(optional)DictorCookieJarobjecttosendwiththe:class:`Request`.
:paramfiles:(optional)Dictionaryof``'name':file-like-objects``(or``{'name':file-tuple}``)formultipartencodingupload.
``file-tuple``canbea2-tuple``('filename',fileobj)``,3-tuple``('filename',fileobj,'content_type')``
ora4-tuple``('filename',fileobj,'content_type',custom_headers)``,where``'content-type'``isastring
definingthecontenttypeofthegivenfileand``custom_headers``adict-likeobjectcontainingadditionalheaders
toaddforthefile.
:paramauth:(optional)AuthtupletoenableBasic/Digest/CustomHTTPAuth.
:paramtimeout:(optional)Howmanysecondstowaitfortheservertosenddata
beforegivingup,asafloat,ora:ref:`(connecttimeout,read
timeout)timeouts`tuple.
:typetimeout:floatortuple
:paramallow_redirects:(optional)Boolean.Enable/disableGET/OPTIONS/POST/PUT/PATCH/DELETE/HEADredirection.Defaultsto``True``.
:typeallow_redirects:bool
:paramproxies:(optional)DictionarymappingprotocoltotheURLoftheproxy.
:paramverify:(optional)Eitheraboolean,inwhichcaseitcontrolswhetherweverify
theserver'sTLScertificate,orastring,inwhichcaseitmustbeapath
toaCAbundletouse.Defaultsto``True``.
:paramstream:(optional)if``False``,theresponsecontentwillbeimmediatelydownloaded.
:paramcert:(optional)ifString,pathtosslclientcertfile(.pem).IfTuple,('cert','key')pair.
:return::class:`ResponseResponse`object
:rtype:requests.Response
Usage::
importrequests
req=requests.request('GET','/get')
Response[200]
#Byusingthe'with'statementwearesurethesessionisclosed,thuswe
#avoidleavingsocketsopenwhichcantriggeraResourceWarninginsome
#cases,andlooklikeamemoryleakinothers.
withsessions.Session()assession:
returnsession.request(method=method,url=url,**kwargs)
源碼看起來很長,其實(shí)只有三行,大部分是代碼注釋。
從源碼中可以看出,不管是get還是post亦或其他請求類型,最終都是調(diào)用request函數(shù)。
既然這樣,我們可以不像之前那樣,在類內(nèi)定義get方法、post方法,而是定義一個通用的方法
直接調(diào)用request函數(shù)
看起來有點(diǎn)繞,用代碼實(shí)現(xiàn)就清晰了。
importrequests
classRequestHandler:
def__init__(self):
"""session管理器"""
self.session=requests.session()
defvisit(self,method,url,params=None,data=None,json=None,headers
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 社保合同協(xié)議書范本下載
- 中高端餐飲創(chuàng)業(yè)計(jì)劃書范文
- 機(jī)器承包使用合同協(xié)議書
- 建筑行業(yè)市場深度分析及發(fā)展策略研究報(bào)告2025年
- 文博會展策劃書模板3
- 合同協(xié)議書匯編四篇范文
- 2025年金屬爐料項(xiàng)目投資分析及可行性報(bào)告
- 建筑合同責(zé)任解除協(xié)議書
- 創(chuàng)新生態(tài)系統(tǒng)的界定、特征及其構(gòu)建
- 鋼結(jié)構(gòu)分包合同協(xié)議書
- (完整PPT)上海英文介紹
- 2025年日歷日程表含農(nóng)歷可打印
- 銳意進(jìn)取開拓新市場
- 《電力工程電纜設(shè)計(jì)規(guī)范》
- 人工挖孔樁計(jì)算書及相關(guān)圖紙
- 穿脫隔離衣操作考核評分標(biāo)準(zhǔn)
- 吉林省工程竣工驗(yàn)收報(bào)告
- 手外傷及斷肢(指)再植(講稿)
- DB32/T 4444-2023 單位消防安全管理規(guī)范-高清版
- 初三物理滑輪習(xí)題
- 東南大學(xué)醫(yī)學(xué)三基考試外科選擇題及答案
評論
0/150
提交評論