zoukankan      html  css  js  c++  java
  • python--MyRequest请求模块封装

    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()
  • 相关阅读:
    在CMD下用java命令出现“找不到或无法加载主类”问题
    去除后台ckeditor的style="...."的样式
    php图片上传
    html图片预览
    论文阅读
    论文阅读
    论文阅读
    论文阅读
    论文阅读
    论文阅读
  • 原文地址:https://www.cnblogs.com/HathawayLee/p/9977468.html
Copyright © 2011-2022 走看看