mcpField
P
python-resilience

python-resilience

github.com/wshobson开发41.9k11.9k 次安装2 周前更新
代码仓库

关于 python-resilience

帮助 Python 开发者构建容错应用的模式指南,适用于依赖服务可能暂时失效的场景。它讲解有界重试、指数退避、抖动及按错误类型选择重试策略。

主要功能

  1. 01区分暂时性与永久性错误
  2. 02指数退避与随机抖动
  3. 03限制重试次数和总时长
  4. 04按异常类型筛选重试
  5. 05针对 HTTP 状态码重试

适用场景

  1. 01为外部服务调用添加重试
  2. 02处理限流和网络超时
  3. 03构建容错微服务

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/wshobson/agents --skill python-resilience

安装后在 Claude Code 中输入/python-resilience确认已加载。

附带文件references/details.md

详细介绍

Python 弹性模式

构建能够优雅处理瞬时故障、网络问题和服 务中断的容错 Python 应用。弹性模式让系统在依赖项不可靠时仍能持续运行。

何时使用此技能

  • 为外部服务调用添加重试逻辑
  • 为网络操作实现超时
  • 构建容错的微服务
  • 处理速率限制和背压
  • 创建基础设施装饰器
  • 设计断路器

核心概念

1. 瞬时故障与永久故障

重试瞬时错误(网络超时、临时服务问题)。不要重试永久错误(无效凭据、错误请求)。

2. 指数退避

增加重试之间的等待时间,以避免压垮正在恢复的服务。

3. 抖动

为退避添加随机性,以防止大量客户端同时重试时出现惊群效应。

4. 有界重试

同时限制尝试次数和总时长,以防止无限重试循环。

快速开始

from tenacity import retry, stop_after_attempt, wait_exponential_jitter

@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential_jitter(initial=1, max=10),
)
def call_external_service(request: dict) -> dict:
    return httpx.post("https://api.example.com", json=request).json()

基本模式

模式 1:使用 Tenacity 进行基本重试

使用 tenacity 库实现生产级重试逻辑。对于更简单的情况,可以考虑内置重试功能或轻量级自定义实现。

from tenacity import (
    retry,
    stop_after_attempt,
    stop_after_delay,
    wait_exponential_jitter,
    retry_if_exception_type,
)

TRANSIENT_ERRORS = (ConnectionError, TimeoutError, OSError)

@retry(
    retry=retry_if_exception_type(TRANSIENT_ERRORS),
    stop=stop_after_attempt(5) | stop_after_delay(60),
    wait=wait_exponential_jitter(initial=1, max=30),
)
def fetch_data(url: str) -> dict:
    """Fetch data with automatic retry on transient failures."""
    response = httpx.get(url, timeout=30)
    response.raise_for_status()
    return response.json()
模式 2:仅重试适当的错误

将特定的瞬时异常列入白名单。切勿重试:

  • ValueError、TypeError - 这些是 bug,不是瞬时问题
  • AuthenticationError - 无效凭据不会变得有效
  • HTTP 4xx 错误(429 除外)- 客户端错误是永久性的
from tenacity import retry, retry_if_exception_type
import httpx

# Define what's retryable
RETRYABLE_EXCEPTIONS = (
    ConnectionError,
    TimeoutError,
    httpx.ConnectTimeout,
    httpx.ReadTimeout,
)

@retry(
    retry=retry_if_exception_type(RETRYABLE_EXCEPTIONS),
    stop=stop_after_attempt(3),
    wait=wait_exponential_jitter(initial=1, max=10),
)
def resilient_api_call(endpoint: str) -> dict:
    """Make API call with retry on network issues."""
    return httpx.get(endpoint, timeout=10).json()
模式 3:HTTP 状态码重试

重试表示瞬时问题的特定 HTTP 状态码。

from tenacity import retry, retry_if_result, stop_after_attempt
import httpx

RETRY_STATUS_CODES = {429, 502, 503, 504}

def should_retry_response(response: httpx.Response) -> bool:
    """Check if response indicates a retryable error."""
    return response.status_code in RETRY_STATUS_CODES

@retry(
    retry=retry_if_result(should_retry_response),
    stop=stop_after_attempt(3),
    wait=wait_exponential_jitter(initial=1, max=10),
)
def http_request(method: str, url: str, **kwargs) -> httpx.Response:
    """Make HTTP request with retry on transient status codes."""
    return httpx.request(method, url, timeout=30, **kwargs)
模式 4:组合异常和状态重试

同时处理网络异常和 HTTP 状态码。

from tenacity import (
    retry,
    retry_if_exception_type,
    retry_if_result,
    stop_after_attempt,
    wait_exponential_jitter,
    before_sleep_log,
)
import logging
import httpx

logger = logging.getLogger(__name__)

TRANSIENT_EXCEPTIONS = (
    ConnectionError,
    TimeoutError,
    httpx.ConnectError,
    httpx.ReadTimeout,
)
RETRY_STATUS_CODES = {429, 500, 502, 503, 504}

def is_retryable_response(response: httpx.Response) -> bool:
    return response.status_code in RETRY_STATUS_CODES

@retry(
    retry=(
        retry_if_exception_type(TRANSIENT_EXCEPTIONS) |
        retry_if_result(is_retryable_response)
    ),
    stop=stop_after_attempt(5),
    wait=wait_exponential_jitter(initial=1, max=30),
    before_sleep=before_sleep_log(logger, logging.WARNING),
)
def robust_http_call(
    method: str,
    url: str,
    **kwargs,
) -> httpx.Response:
    """HTTP call with comprehensive retry handling."""
    return httpx.request(method, url, timeout=30, **kwargs)

详细示例和模式

详细章节(以 ## Advanced Patterns 开头)位于 references/details.md。当上方的导航摘要不够用时,请阅读该文件。

最佳实践总结

  1. 仅重试瞬时错误 - 不要重试 bug 或身份验证失败
  2. 使用指数退避 - 给服务时间恢复
  3. 添加抖动 - 防止同步重试导致的惊群效应
  4. 限制总时长 - stop_after_attempt(5) | stop_after_delay(60)
  5. 记录每次重试 - 静默重试会掩盖系统性问题
  6. 使用装饰器 - 将重试逻辑与业务逻辑分开
  7. 注入依赖 - 使基础设施可测试
  8. 处处设置超时 - 每次网络调用都需要超时
  9. 优雅降级 - 对非关键路径返回缓存/默认值
  10. 监控重试率 - 高重试率表明存在潜在问题

评论

支持 Markdown