安装依赖
在开始使用前,需先安装工具依赖的第三方库。打开终端(命令行),执行以下命令:
pip install requests tenacity
核心功能说明
1. 类与方法概览
类/方法 | 功能描述 |
---|---|
apiresponse 类 | 响应数据包装类,提供状态检查、数据获取等便捷方法 |
nethelper 类 | 核心请求封装类,支持初始化配置、多 http 方法调用 |
get()/post()/put()/delete() | 对外暴露的快捷方法,分别对应 get/post/put/delete 请求 |
2.nethelper类初始化参数
初始化 nethelper
实例时,需传入以下参数(均为可选,有默认值):
参数名 | 类型 | 说明 |
---|---|---|
base_url | str | 基础 url(如 https://api.example.com),请求路径会自动拼接至此 url |
headers | dict[str, str] | 默认请求头(会被单次请求的头覆盖) |
timeout | int | 请求超时时间(秒,默认 15 秒) |
verify_ssl | bool | 是否验证 ssl 证书(生产环境建议设为 true,测试环境可设为 false) |
3.apiresponse类属性与方法
apiresponse
用于包装接口响应数据,提供以下核心功能:
属性/方法 | 类型 | 说明 |
---|---|---|
data | any | 响应体解析后的数据(json 自动转为字典,非 json 为文本/二进制) |
status_code | int | http 状态码(如 200、404) |
error | optional[str] | 错误信息(仅当状态码非 2xx 或发生异常时存在) |
is_success() | bool | 检查请求是否成功(状态码 2xx 且无错误信息时返回 true) |
使用实例
步骤 1:导入工具类
from net_helper import nethelper, apiresponse # 假设工具保存为 net_helper.py
步骤 2:初始化nethelper实例
请求头和基础 url 配置:
# 初始化 nethelper client = nethelper( base_url="https://com.text.com", headers={ "accept": "application/json, text/plain, */*", "content-type": "application/json;charset=utf-8", }, )
步骤 3:发送登录请求
使用 post()
方法发送 post 请求,传入请求体和参数:
response = client.post( url="/login", json={ "name": "bin", "pwd": "123456", } )
步骤 4:处理响应结果
根据 apiresponse
的属性判断请求是否成功,并获取数据:
if response.is_success(): print("登录成功!") print("响应数据:", response.data) print("状态码:", response.status_code) else: print(f"登录失败!错误信息: {response.error}") print("状态码:", response.status_code) print("原始响应:", response.data)
五、源码
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging import json as jsonlib from typing import dict, optional, union, any import requests from tenacity import ( retry, stop_after_attempt, wait_exponential, retry_if_exception_type, ) logging.basicconfig( level=logging.info, format="%(asctime)s [%(levelname)s] %(message)s", datefmt="%y-%m-%d %h:%m:%s" ) logger = logging.getlogger(__name__) class apiresponse: """api响应包装类""" def __init__(self, data: any, status_code: int = 200, error: optional[str] = none): self.data = data self.status_code = status_code self.error = error self.message = data.get('message', '') if isinstance(data, dict) else '' def is_success(self) -> bool: """检查请求是否成功""" return 200 <= self.status_code < 300 and self.error is none class nethelper: def __init__(self, base_url: str, headers: optional[dict[str, str]], timeout: int = 15, verify_ssl: bool = true): self.base_url = base_url.rstrip("/") self.default_headers = headers self.timeout = timeout self.verify_ssl = verify_ssl @retry( stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10), retry=retry_if_exception_type(( requests.exceptions.connectionerror, requests.exceptions.timeout )), reraise=true ) def _send_request( self, method: str = "get", url: str = "", headers: optional[dict[str, str]] = none, json: optional[union[dict[str, any], str]] = none, data: optional[union[dict[str, any], str, bytes]] = none, params: optional[dict[str, any]] = none ) -> apiresponse: """内部请求方法""" # 拼接完整url full_url = f"{self.base_url}/{url.lstrip('/')}" # 合并请求头 merged_headers = {**self.default_headers, **(headers or {})} # 移除空值头 merged_headers = {k: v for k, v in merged_headers.items() if v is not none} try: # 打印请求体 print("请求方法:", method.upper()) print("请求url:", full_url) if params: print("请求参数:") print(jsonlib.dumps(params, ensure_ascii=false, indent=2)) if json: print("请求json数据:") print(jsonlib.dumps(json, ensure_ascii=false, indent=2)) if data: print("请求表单数据:") if isinstance(data, (dict, list)): print(jsonlib.dumps(data, ensure_ascii=false, indent=2)) else: print(data) # 发送请求 response = requests.request( method=method.upper(), url=full_url, headers=merged_headers, json=json, data=data, params=params, timeout=self.timeout, verify=self.verify_ssl ) # 解析响应 try: result_data = response.json() except valueerror: result_data = response.text if response.encoding else response.content print("响应数据:") print(jsonlib.dumps(result_data, ensure_ascii=false, indent=2)) # 检查http状态码 if 200 <= response.status_code < 300: return apiresponse(result_data, response.status_code) else: error_msg = f"http错误: 状态码 {response.status_code}" logger.error(f"{error_msg}, 响应: {result_data}") return apiresponse(result_data, response.status_code, error_msg) except requests.exceptions.connectionerror as e: logger.error(f"连接失败: 无法连接到 {full_url}") return apiresponse({}, 0, str(e)) except requests.exceptions.timeout as e: logger.error(f"请求超时: 超过 {self.timeout} 秒") return apiresponse({}, 0, str(e)) except exception as e: logger.error(f"未知错误: {str(e)}") return apiresponse({}, 0, str(e)) def post(self, url: str, data: optional[any] = none, params: optional[dict[str, any]] = none) -> apiresponse: return self._send_request(method="post", url=url, json=data, params=params) def get(self, url: str, params: optional[dict[str, any]] = none) -> apiresponse: return self._send_request(method="get", url=url, params=params) def put(self, url: str, data: optional[any] = none, params: optional[dict[str, any]] = none) -> apiresponse: return self._send_request(method="put", url=url, json=data, params=params) def delete(self, url: str, params: optional[dict[str, any]] = none) -> apiresponse: return self._send_request(method="delete", url=url, params=params)
到此这篇关于python实现简单封装网络请求的示例详解的文章就介绍到这了,更多相关python封装网络请求内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论