1.首先封装post请求:
? ? ? ? 这里有一个小坑就是你的data数据,需要进行转换,需要安装一个demjson库,进行格式转换,如果直接传入数据没有问题的话就不用转换。这里我做了一个小小的判断,如果是表单形式的数据就不用转换数据直接使用就行。
import requests
import json
import demjson
class RunMain():
def send_post(self, url, data, header,cookie):
if type(data) == type({}): # 传入的请求体为字典类型
if header['Content-Type'] == 'application/json':
data = demjson.encode(data)
elif header['Content-Type'] == 'application/x-www-form-urlencoded':
data = data
else:
pass # 如果是其他的Content-Type类型另做处理
result = requests.post(url=url, data=data, headers=header, cookies=cookie)
re=result
try:
return re.json()
except:
return re.json()
else:
print('请求体错误,请更改请求体为字典类型')
2.获取cookies值的封装:
这里我封装的是post请求获取cookie,可以参考,cookies的值是以字典形式进行传输的,可以在下面的请求进行引用cookies。
def send_post_cookie(self,url,header,data):
res = requests.post(url=url, data=demjson.encode(data), headers=header)
return res.cookies.get_dict() #获取cookies
3.封装get,put, delete请求:
? ? ? ?get,put, delete,?get请求相对于来说就简单点,大致相同
def send_get(self, url, data, cookie):
result = requests.get(url=url, params=None, cookies=cookie)
res = result
return res.json()
def send_put(self, url, header, data, cookie):
if type(data) == type({}):
if header['Content-Type'] == 'application/json':
data =demjson.encode(data)
elif header['Content-Type'] == 'application/x-www-form-urlencoded':
data = data
else:
pass
result = requests.put(url=url, headers=header, data=data, cookies=cookie)
re = result
try:
return re.json()
except:
return re.json()
else:
print('请求体错误,请更改请求体为字典类型')
def send_put_cookie(self,url,header,data):
res = requests.put(url=url, data=demjson.encode(login_data), headers=header)
return res.cookies.get_dict() #获取cookies
def send_delete(self,url,params, cookies=None):
re= None
if cookies != None:
re = requests.delete(url=url, params=params, cookies=cookies)
else:
re = requests.delete(url=url, params=params)
return re.json()
#else:
#print('请求体错误,请更改请求体为字典类型')
4,整体封装
def run_main(self, method, url=None, data=None, header=None,cookies=None,params=None): # 定义一个run_main函数,通过传过来的method来进行不同的get或post请求
result = None
if method == 'post':
result = self.send_post(url, data, header,cookies)
elif method == 'get':
result = self.send_get(url, params, cookies,)
elif method == 'put':
result = self.send_put(url, header, data,cookies)
elif method == 'delete':
result = self.send_delete(url,data,cookies)
elif method == 'put_cookie':
result = self.send_put_cookie(url, header, data)
elif method == 'post_cookie':
result = self.send_post_cookie(url, header, data)
else:
print("method值错误!!!")
return result
|