import requests,json
import traceback
#初始headers

class http():
    def __init__(self,ip):
        self.ip = ip
        self.request = requests.Session()

    """
    url：接口地址
    params : 参数, type：dict，默认为None
    file_path : 文件路径，type: str ，默认为None
    method : 默认是GET 
    POST
    POST_FILE 上传文件的 post 请求
    """
    def request_Met(self,url, params = None,file_path = None, method = 'GET',cookies = None):

        method = str(method).upper()
        try :
            if method == 'GET':
                response = self.request.get(self.ip + url, params = params,cookies = cookies)
            elif method == 'POST':
                # print(self.ip,url,params)
                response = self.request.post(self.ip + url, params = params,cookies = cookies)

            elif method == 'POST_FILE':
                try :
                    files = {'file':open(file_path,'rb')}
                except IOError:
                    self.request_Except("检查读取的文件是否存在")
                response = self.request.post(self.ip + url,files = files)
            else:
                self.request_Except("请选择正确的接口类型")
        except requests.RequestException as e :
            # print('接口 %s 调用异常: '%(url) , e)
            return str(e)+url

        else:
            # print('接口 %s 通过: '%(url))
            return response

    # def get_Cookies(self,response):
    #     if response:
    #         keys = []
    #         values = []
    #         # print(response)
    #         for item in response.cookies:
    #             keys.append(item.name)
    #             values.append(item.value)
    #             cookies = dict(zip(keys,values))
    #         return cookies
    #     else:
    #         self.request_Except("没有接口返回的信息")

    """
    Set headers
    """
    def set_hearder(self,headers = None):
        self.request.headers.update(headers)

    def get_hearder(self):
        """
        Set cookies
        """
        return self.request.headers

    def set_cookies(self,cookies = {}):
        self.request.cookies = cookies

    def get_cookies(self):
        return self.request.cookies

    def getJson(self,response):
        try:
            json = response.json()
        except Exception as e:
            print(e.args,'接口返回json 出错')
        else:
            return json

    def getText(self,response):
        if response:
            try:
                text = response.text
                return text
            except Exception as e:
                print(e.args,'接口返回 text 出错')
        else:return None

    def request_Except(self,prt):
        raise Exception(prt)

