1、request安装
1)pip安装,直接pip install requests
2)下载离线包安装,加压后,命令行进入路径,执行python setup.py install
2、创建工程
注意勾选Inherit global sit-packages,否则引用requests包时会报错
3、类封装及调用如下
# coding=utf-8import requestsimport jsonclass SendMain: # SendMain构造函数 def __init__(self,url,method,data=None): self.res = self.send_main(url, method, data) # 发送post请求 def send_post(self,url, data): res = requests.post(url=url, data=data).json() # 返回结果格式化 return json.dumps(res, indent=2, sort_keys=True) # 发送get请求 def send_get(self,url, data): res = requests.get(url, data).json() # 返回结果格式化 return json.dumps(res, indent=2, sort_keys=True) # 既能发get又能发post请求 def send_main(self,url, method, data=None): res = None if method == 'GET': res = self.send_get(url, data) else: res = self.send_post(url, data) return resif __name__ == '__main__': #接口数据 postData = { 'username': 'wangling', 'password': '123456'} getData = { 'username': 'wl', 'mobile': '13066990001', 'data': 'haha'} postUrl = 'http://127.0.0.1:8000/postDataHandle/' getUrl = 'http://127.0.0.1:8000/getDataHandle/' runPost = SendMain(postUrl,'POST',postData) runGet = SendMain(getUrl,'GET',getData) print runGet.res print runPost.res