http_requests.py

import json

import requests

from Common.Log_common import LOG
http=requests.session()


class Http_Requests():

def http_get(self,url,data,header):#get请求封装,两种情况,data为空和不为空,
# 这样的好处是写case时,无论data是否为空,直接填入封装的请求方法

if not url.startswith('http://'):#先加上http://
url='s%s%'%('http://',url)

try:
if data is None:
response=http.get(url=url,headers=header)
LOG.info('请求地址:%s'%(url))
LOG.info('请求入参:%s'%(data))
LOG.info('请求headers:%s' % (header))
else:
response = requests.get(url=url, params=data, headers=header)
LOG.info('请求地址:%s' % (url))
LOG.info('请求入参:%s' % (data))
LOG.info('请求headers:%s' % (header))
except requests.RequestException as e:
LOG.info('请求异常%s'%(url))
except requests.RequestsDependencyWarning as e:
LOG.info('请求异常%s' % (url))


response_dic=dict()#构造一个字典来保存response里面的内容
response_dic['code']=response.status_code
response_dic['text']=response.text
try:
response_dic['body']=response.json()
except Exception:
LOG.info('获取response body异常')
LOG.info('response body:%s'%(response_dic['body']))

return response_dic

def http_post(self,url,data,header):
#封装post请求,header中的Content-Type可能为表单或者json,
if not url.startswith('http://'):
url='%s%s' % ('http://', url)
if header["Content-Type"]=='application/json' :
data=json.dumps(data)
else:
data=data
try:
if data is None:
response=http.post(url=url,headers=header)
LOG.info('请求地址:%s' % (url))
LOG.info('请求入参:%s' % (data))
LOG.info('请求header:%s' % (header))
else:
response=http.post(url,data=data,headers=header)
LOG.info('请求地址:%s' % (url))
LOG.info('请求入参:%s' % (data))
LOG.info('请求header:%s' % (header))
except requests.RequestException as e:
LOG.info('请求异常%s'%(url))
except requests.RequestsDependencyWarning as e:
LOG.info('请求异常%s' % (url))
response_dic=dict()#构造一个字典来保存response里面的内容
response_dic['code']=response.status_code
response_dic['text']=response.text
try:
response_dic['body']=response.json()
except Exception:
LOG.info('获取response body异常')
LOG.info('response body:%s'%(response_dic['body']))

return response_dic





















posted @ 2022-03-11 12:16  我的博客16000  阅读(75)  评论(0编辑  收藏  举报