- # 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)
来源: http://www.bubuko.com/infodetail-2988975.html