栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python:封装request请求

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python:封装request请求

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")

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/892709.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号