MyRequest类
2021/7/7 23:36:44
本文主要是介绍MyRequest类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import requests import traceback from loguru import logger class MyDict(dict): def __getattr__(self, item): value = self.get(item) if type(value) == dict: value = MyDict(value) if isinstance(value,list) or isinstance(value,tuple): value = list(value) for index,v in enumerate(value): if isinstance(v,dict): value[index] = MyDict(v) return value class MyRequest: def __init__(self,url,params=None,data=None,headers=None,files=None,json=None,timeout=5): self.url = url self.params = params self.data = data self.headers = headers self.files = files self.json = json self.timeout = timeout def __get_response(self): try: ret = self.response.json() except: logger.warning("接口返回的不是json!无法转成字典!response:{}", self.response.content) return MyDict() logger.debug("接口返回数据:{}", ret) return MyDict(ret) def __request(self,method): logger.debug("url:{},params:{},data:{},json:{},files:{},headers:{}",self.url,self.params,self.data,self.json,self.files,self.headers) try: self.response = requests.request(method,url=self.url,params=self.params,data=self.data, json=self.json,headers=self.headers,files=self.files,verify=False,timeout=self.timeout) except: logger.error("接口不通,请求出错,错误信息是:{}",traceback.format_exc()) return MyDict() return self.__get_response() def get(self): return self.__request("get") def post(self): return self.__request("post") def put(self): return self.__request("put") def delete(self): return self.__request("delete") if __name__ == '__main__': data = {"file":open("myDict.py",'rb')} r = MyRequest("http://118.24.3.41/api/file/file_uploa",files=data) # result = r.get() ret1 = r.post()
这篇关于MyRequest类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-26JavaScript入门教程:从零开始学习JavaScript编程
- 2024-12-26JavaScript入门教程:从零开始学习JavaScript
- 2024-12-26JS编程入门指南:从零开始学习JavaScript
- 2024-12-25Java编程面试题详解与解答
- 2024-12-25TS基础知识详解:初学者必看教程
- 2024-12-252024面试题解析与攻略:从零开始的面试准备指南
- 2024-12-25数据结构与算法学习:新手入门教程
- 2024-12-25初学者必备:订单系统资料详解与实操教程
- 2024-12-24内网穿透资料入门教程
- 2024-12-24微服务资料入门指南