标签:data class www stat col span 返回 请求超时 模块
MyRequest
import requests import nnlog class MyRequest: log_file_name = ‘MyRequest.log‘ #日志文件名 time_out = 10 #请求超时时间 def __init__(self,url,data=None,headers=None,file=None): self.url = url self.data = data self.headers = headers self.files = file def post(self): try: req = requests.post(self.url,data=self.data,headers=self.headers,files=self.files,timeout=self.time_out) except Exception as e: #请求报错 res = {‘status‘:0,‘err_msg‘:e.args} #0代表请求失败 else: #请求成功 try: res = {‘status‘:1,‘data‘:req.json()} #1 返回json类型数据 except Exception as e: res ={‘status‘:2,‘data‘:req.text} #2返回非json类型数据 log_str = ‘url: %s 请求方式:post data: %s, 返回数据:%s‘%(self.url,self.data,res) self.write_log(log_str) return res def get(self): try: req = requests.get(self.url, params=self.data, headers=self.headers,timeout=self.time_out) except Exception as e: # 请求报错 res = {‘status‘: 0, ‘err_msg‘: e.args} # 0代表请求失败 else: # 请求成功 try: res = {‘status‘: 1, ‘data‘: req.json()} # 1 返回json类型数据 except Exception as e: res = {‘status‘: 2, ‘data‘: req.text} # 2返回非json类型数据 log_str = ‘url: %s 请求方式:get data: %s, 返回数据:%s‘ % (self.url, self.data, res) self.write_log(log_str) return res @classmethod def write_log(cls,content): log = nnlog.Logger(cls.log_file_name) log.debug(content) url =‘https://www.baidu.com‘ myrequest = MyRequest(url) myrequest.post()
标签:data class www stat col span 返回 请求超时 模块
原文地址:https://www.cnblogs.com/HathawayLee/p/9977468.html