首页 > 技术文章 > Python 基于request库的get,post,delete,封装

SunshineKimi 2019-03-15 23:45 原文

import requests
import json
from requests import session
import urllib3
import os
urllib3.disable_warnings()
conf_path = os.path.abspath("../api/request_param/params.json")


class GetParams(object):
    def __init__(self, case_name):
        with open(conf_path, "r", encoding="utf-8")as fp:
            data_set = json.load(fp)
        current_set = data_set.get(case_name)
        self.method = current_set.get("method")
        self.url = current_set.get("url")
        self.params = current_set.get("params")
        self.data = current_set.get("data")
        self.json = current_set.get("json")
        self.headers = current_set.get("headers")
        self.kwargs = current_set.get("kwargs")
        self.session = session()
        # self.session.request("post",data={username,pwd})
        self.verify = False


def api_request(case_name: str):
    # todo case_name is the name of test_case in params.json
    inst = GetParams(case_name)
    with inst.session as request:
        response=request.request(inst.method, inst.url, params=inst.params, data=inst.data, headers=inst.headers,
                                    verify=inst.verify, json=inst.json)

    # print("测试demo返回信息为:\n%s" % json.dumps(response.json(), ensure_ascii=False, indent=2))
    return json.dumps(response.json(), indent=2)

  

推荐阅读