import requests
import json

class HandleRequest:
    param_type_dict = {
        'form': 'application/x-www-form-urlencoded',
        'data': 'application/x-www-form-urlencoded',
        'json': 'application/json',
        'file': 'multipart/form-data',
        'files': 'multipart/form-data',
        'params': 'query string',
        'param': 'query string',
        None: 'NoneType',}

    def init(self):
        # 创建会话对象
        self.session = requests.Session()

    def handle_param(self, param_value):
        if isinstance(param_value, str):
            try:
                param_value = json.loads(param_value)
            except Exception:
                param_value = eval(param_value)
        return param_value

    def send(self, url, method="POST", param_type=None, param_data=None, **kwargs):
        """
        :param url: 请求url
        :param method: 请求方法
        :param_type: q请求参数类型
        :param kwargs: headers请求头字典, cookies等其他可变参数
        :return: Response对象
        """
        # 如果param_type为字符串,那么转化为小写,否则赋值为None
        param_type = param_type.lower() if isinstance(param_type, str) else None
        # 判断param_type是否为param_type_dict中的键值
        if param_type not in self.param_type_dict :
            raise Exception(f"param_type值错误")
        if param_type == "json":
            kwargs["json"] = self.handle_param(param_data)
        elif param_type in ["file", "files"]:
            kwargs["files"] = self.handle_param(param_data)
        elif param_type in ["data", "form"]:
            kwargs["data"] = self.handle_param(param_data)
        elif param_type in ["params", "param"]:
            kwargs["params"] = self.handle_param(param_data)

        if method is None:
            method = "POST"
        return self.sesson.requests(method=method, url=url, **kwargs)

    def handle_return(self, response):
        if re.match(r'^2', str(response.status_code)):
            res = AttrDict(**json.loads(response.text))
            return res
        else:
            raise Exception(f"请求错误,请求响应为{response.status.code}")

if __name__ == '__main__':
    a = HandleRequest()
    res = a.send(url, method, param_type, param_data)
    res = a.handle_return(res)
    if res['ret']:
        print('成功')
    else:
        print(f"失败:{res['errMsg']}")