You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中为requests.post()封装重试逻辑时传递不同参数的优雅方式

优雅封装带重试功能的requests.post方法

直接通过**kwargs透传所有参数是最简洁优雅的方案,完全兼容原生requests.post的参数格式,调用者无需额外标记或修改原有代码逻辑。

方案一:手动实现重试逻辑

import requests
import time
from requests.exceptions import RequestException

def http_post(endpoint, headers=None, **kwargs):
    max_retries = 3  # 可自定义重试次数
    retry_interval = 1  # 重试间隔(秒)
    
    for retry_count in range(max_retries):
        try:
            # 直接透传所有参数,自动适配data/json等参数
            response = requests.post(endpoint, headers=headers, **kwargs)
            # 可选:如果需要非2xx状态码也触发重试,添加这行
            response.raise_for_status()
            return response
        except RequestException:
            if retry_count == max_retries - 1:
                # 最后一次重试失败,抛出异常
                raise
            # 重试前等待
            time.sleep(retry_interval)

方案二:用tenacity库简化重试逻辑

如果需要更灵活的重试策略(比如指数退避),可以用tenacity装饰器,代码更简洁:

import requests
from requests.exceptions import RequestException
from tenacity import retry, stop_after_attempt, wait_exponential

@retry(
    stop=stop_after_attempt(3),  # 最多重试3次
    wait=wait_exponential(multiplier=1, min=2, max=10)  # 指数退避等待:2s,4s,8s...最多10s
)
def http_post(endpoint, headers=None, **kwargs):
    response = requests.post(endpoint, headers=headers, **kwargs)
    response.raise_for_status()
    return response

调用示例

两种方案的调用方式和原生requests.post完全一致,无需额外适配:

  • 用data参数发送表单数据:
http_post(
    "https://example.com/api/form",
    headers={"Content-Type": "application/x-www-form-urlencoded"},
    data={"username": "test", "password": "123456"}
)
  • 用json参数发送JSON数据:
http_post(
    "https://example.com/api/json",
    headers={"Content-Type": "application/json"},
    json={"username": "test", "password": "123456"}
)

这种方案的优势在于:

  • 完全兼容原生API,调用者零学习成本
  • 无需额外标记位或复杂逻辑,代码简洁易维护
  • 重试逻辑和业务参数解耦,扩展性强

内容的提问来源于stack exchange,提问作者PassoGiau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 17:42:34