# coding=utf-8
import json
import requests
class TestApi(object):
"""
/*
@param: @session ,@cookies
the request can be divided into session request and cookie request according to user's own choice
however,url and header is must ,other parameters are given by user to make it is None or not
*/
"""
def get(self,url,param,header,cookie=None,session=None,**kwargs):
if session:
return session.request("GET",url,param,headers=header,**kwargs)
elif cookie:
return requests.get(url,params=param,headers=header,cookies=cookie,**kwargs)
"""
/*
@param: @session ,@cookies
传入的是dict类型 python object 对象
header is form data: application/x-www-urlencoded
transfer data to data directly ,finally requests's submit will be like 'aa=dd&bb=ff' formation
header is json :application/json
due to the data can be 'str','dict'and tuple and so on ,so when we choose data and
data is given by dict,we must transfer it to json str,but when is json type str ,we must must
transfer python object dict to json str with json.dumps(),
finally the request submit data format is str like:
'aa=dd&bb=ff',but when choose json the submit will become like {'a': 'cc' ,'b': 'dd'} ,
data and json cant not be used in the requests at the same time
*/
"""
def post_data(self,url,type,data,header,cookie=None,session=None,**kwargs):
if cookie:
if type is "data":
return requests.post(url,data=data,headers=header,cookies=cookie,**kwargs)
elif type is "json":
return requests.post(url,data=json.dumps(data),headers=header,cookies=cookie,**kwargs)
elif session:
if type is "data":
return session.request("POST",url,data=data,headers=header,cookies=cookie,**kwargs)
elif type is "json":
return session.request("POST",url,data=json.dumps(data),headers=header,cookies=cookie,**kwargs)
"""
/*
@:param:@json object
json的value为传入的json对象
请求header默认:ContentType: application/json
*/
"""
def post_json(self,url,header,json,cookie=None,session=None,**kwargs):
if cookie:
return requests.post(url,headers=header,json=json,cookies=cookie,**kwargs)
elif session:
return session.request("POST",url,headers=header,json=json,**kwargs)
"""
/*
@:param: @url,@data,@**kwargs
Tip: header you need to according to your api to be given in **kwargs position
*/
"""
def put(self,url,data,cookie=None,session=None,**kwargs):
if cookie:
return requests.put(url,data,cookies=cookie,**kwargs)
elif session:
return session.request("PUT",url,data,**kwargs)
"""
/*
@:param: @url,@data,@**kwargs
Tip: header you need to according to your api to given in **kwargs position
*/
"""
def delete(self,url,data,cookie=None,session=None,**kwargs):
if cookie:
return requests.delete(url,data,cookies=cookie,**kwargs)
elif session:
return session.request("DELETE",url,data,**kwargs)
接口请求封装get,post增,put修改,delete封装入cookie,session两种模式
最新推荐文章于 2024-01-11 16:11:02 发布