标签:
前言:由于项目需求做的接口测试有上传文件这一要求,在查资料时候发现用requests来做上传文件很简单,所以下了这个库来完成。后续有时候会看看能不能用传统地urllib2来做。
首先你要有个requests:
https://github.com/kennethreitz/requests
然后把它import进来
接着:
def post(self,url,param_dict,param_header,file = ‘‘,param_type = ‘x-www-form-urlencode‘):
‘‘‘
@功能:封装post方式
@paramType:指传入参数类型,可以是form-data、x-www-form-urlencode、json
‘‘‘
respone_code = None
respone = None
try:
if param_type == ‘x-www-form-urlencode‘:
params = param_dict
elif param_type == ‘json‘:
params = json.dumps(param_dict)
if file == ‘‘ :
ret = requests.post(self.Server+url, data=params, headers=param_header)
else:
files = {‘file‘:open(file,‘rb‘)}
ret = requests.post(self.Server+url, data=params, headers=param_header,files = files)
respone_code = ret.status_code
respone = ret.text
except requests.HTTPError, e:
respone_code = e.getcode()
respone = e.read().decode("utf-8")
return respone_code,respone
另外附上http://blog.csdn.net/iloveyin/article/details/21444613,这个博客很详细地介绍了requests这个库的使用方法
标签:
原文地址:http://www.cnblogs.com/tanliyu/p/4460767.html