将get和post封装到一起,根据请求方式不同,决定调用的方法。调用的时候只调用一个就可以了。
import requests import json class Interface(): ‘‘‘练习接口测试‘‘‘ def send_post(self, url, data): ‘‘‘封装post请求‘‘‘ result = requests.post(url, data) assign = result.json() return json.dumps(assign, indent=4, sort_keys=True, ensure_ascii=False) def send_get(self, url, data): ‘‘‘封装get请求‘‘‘ result = requests.get(url, data) assign = result.json() return json.dumps(assign, indent=4, sort_keys=True, ensure_ascii=False) def run_main(self, url, method, data=None): ‘‘‘根据请求方式调用方法执行‘‘‘ res = None if method == ‘GET‘: res = self.send_get(url, data=None) else: res = self.send_post(url, data) return res if __name__ == ‘__main__‘: ‘‘‘调用执行‘‘‘ api = Interface() url = ‘https://api.apishop.net/common/weather/get15DaysWeatherByArea‘ data = { "apiKey": ‘chgaxvsf88f3858a15fa4426f4cbdd4d2a02b92ee0747f3‘, "area": ‘重庆‘, } print(api.run_main(url, ‘POST‘,data))
较为容易理解的写法:
import requests import json def send_post(url,data): ‘‘‘封装post请求‘‘‘ result = requests.post(url,data) assign = result.json() return json.dumps(assign,indent=4,sort_keys=True,ensure_ascii=False) def send_get(url,data): ‘‘‘封装get请求‘‘‘ result = requests.get(url,data) assign = result.json() return json.dumps(assign,indent=4,sort_keys=True,ensure_ascii=False) def main(url,method,data=None): ‘‘‘根据请求方式调用方法执行‘‘‘ if method == ‘GET‘: return send_get(url,data) else: return send_post(url,data) url = ‘https://api.apishop.net/common/weather/get15DaysWeatherByArea‘ data = { "apiKey":‘chgaxvsf88f3858a15fa4426f4cbdd4d2a02b92ee0747f3‘, "area":‘重庆‘, } #url = ‘https://mgapp.sitezt.cn/api/info/mgapp/index/getindexbanner‘ print(main(url,‘POST‘,data))
原文地址:https://www.cnblogs.com/xiamaojjie/p/11614630.html
时间: 2024-10-09 16:29:18