base_request.py 3.53 KB
import json
import random
import string
import requests
import yaml
from jsonpath import jsonpath
from login_session_function import LoginFunction
# from pymysql import OperationalError

import path_setting


class BaseRequest:
    params = {}

    @classmethod
    def format(cls, r):
        cls.r = r
        print(json.dumps(json.loads(r.text), indent=2, ensure_ascii=False))

    # 封装yaml文件读取
    @classmethod
    def yaml_load(cls, path) -> list:
        with open(path, encoding='utf-8') as f:
            return yaml.safe_load(f)

    # 调用yaml加载文件API加载
    def api_load(self, path: object) -> object:
        return self.yaml_load(path)

    def jsonpath(self, path, r=None, **kwargs):
        if r is None:
            r = self.r.json()
        return jsonpath(r, path)

    def api_send(self, req: object) -> object:
        host = self.api_load(path_setting.HOSTYAML_CONFIG)

        # 获取调用该方法的路径
        import inspect
        ins_file = inspect.stack()[1].filename
        ins_dir = ins_file.split('/')[-2]
        host_service = ins_dir.split('_')[1]
        # default: backend
        if host_service not in host['develop_host']:
            host_service = 'backend'
        url_host = host['develop_host'][host_service]

        # if host["develop_host"].get("doctor") is not None:
        #     url_host = host['develop_host']['doctor']
        # elif host["develop_host"].get("backend") is not None:
        #     url_host = host['develop_host']['backend']

        raw = yaml.dump(req)  # 将一个python对象生成为yaml文档
        for key, value in self.params.items():
            raw = raw.replace(f"${{{key}}}", repr(value))
        req = yaml.safe_load(raw)
        print('req:', req)

        s = requests
        if req.get('isLogin'):
            s = LoginFunction().get_session(host_service)

        # 调用具体case的url
        r = s.request(
            req['method'],
            url=url_host + req['url'],
            params=req.get('params'),
            # headers=user_headers,
            data=req.get('data'),
            json=req.get('json'),
            # verify=False
            # proxies={"http":"172.30.9.226:8888"}

        )
        print("0000000",r)
        # return r.json()
        try:
            content_type = r.headers.get("content-type").split(";")[0]
        except:
            content_type = "application/json"
        if content_type == 'application/json':
            return r.json()

        return r.text

    # 随机生成trace_id
    def trace_id(self):
        return ''.join(random.sample(string.ascii_lowercase + string.digits, 32))

    '''
       def get_cookie(self, req: dict):

           host = self.api_load(path_setting.HOSTYAML_CONFIG)
           print(host)
           r = requests.request(
               req['method'],
               url=host['develop_host']['url'] + req['url'],
               params=req['params'],
               headers=req['headers'],
               data=req['data'],
               json=req['json']
           )
           dict = {}
           for i in r.cookies:
               dict[i.name] = i.value
           headers = '_gtid={};sessionid={}'.format(dict["_gtid"], dict["sessionid"])
           return headers

       def read_header(self):
           with open("../in_common/get_cookie.txt", 'r', encoding='utf-8') as f:
               cookies = f.read()
           headers = {"cookie": cookies}
           return headers
       '''

if __name__ == '__main__':
    # BaseRequest().api_load("../api/api.yaml")
    print(BaseRequest().trace_id())