# coding=utf8
from .config import Config
from .utils.client import HTTPClient
from .log import logger
from .extractor import extract


class PRequest(object):
    def __init__(self, base_url=None, conf='config.yml', host='host_url'):
        self.conf = conf
        self.host = host
        self.base_url = Config(self.conf).get(self.host, index=0) if not base_url else base_url
        self.headers = {}
        # self.headers = {"cookie": Config("data/cookies").raw_get()}

    def send_request(self, api_url, method='POST', status='PASS', params=None, data=None, json=None, files=None,
                     extractor=None):
        """请求定制封装"""

        # 建立http连接，发送请求
        client = HTTPClient(url=(self.base_url + api_url), method=method, headers=self.headers)
        response = client.send(params=params, json=json, data=data, files=files)
        try:
            # 有效用例和无效用例的最基本断言（针对status_code）
            if status == 'PASS':
                assert response.status_code in [200]
            elif status == 'FAIL':
                assert response.status_code not in [200]

            # 提取json值
            if status == 'PASS' and extractor is not None:
                response = extract(extractor, response.text)
                logger.info("数据处理: 提取{}的值为{} ".format(extractor, response))
        except Exception as e:
            logger.error(e)
        client.close()
        return response

