python:封装request请求

1 前言

安装库前先添加国内镜像源:

https://pypi.douban.com/simple/

python interpreter->双击如pip->Manage Repositories->添加国内镜像源
在这里插入图片描述

python库安装:
在这里插入图片描述
在这里插入图片描述

2 工具方法封装

import requests
import jsonpath


def send_method(method, url, headers=None, params=None, data=None, files=None):
    if method.lower() == "post" and params is not None and data is None:
        raise ValueError("post请求传参是data,请检查数据参数")
    global response
    if params and not data:
        if isinstance(params, dict):
            response = requests.request(method, url, params=params, headers=headers)
            return response.json()
        else:
            print("params should be dict type!")
    elif not params:
        if files:
            response = requests.post(url, data, headers=headers, files=files)
        elif files and data:
            response = requests.request(method, url, json=data, headers=headers, files=files)
        elif not files and data:
            response = requests.request(method, url, json=data, headers=headers)
        else:
            response = requests.request(method, url, headers=headers)
        return response.json()
    else:
        print("request maybe is wrong.")


def get_key_value(data, pattern):
    if isinstance(data, dict):
        if pattern.startswith("$"):
            return jsonpath.jsonpath(data, pattern)
        else:
            print("pattern must start with '$'")
    else:
        print("use jsonpath, data must be dict type")

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐