python:封装request请求
python:封装request请求import requestsimport jsonpathdef send_method(method, url, headers=None, params=None, data=None, files=None):global responseif params and not data:if isinstance(params, dict):respons
·
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")
更多推荐
已为社区贡献12条内容
所有评论(0)