Skillpedia
واجهات API والخوادم (backend)41k · #6766

python-resilience

ما الذي تفعله

تساعد هذه المهارة على جعل تطبيقات Python أكثر موثوقية. تجعل التطبيق يعيد المحاولة تلقائيا إذا حدث خلل مؤقت، مثل مشكلة في الشبكة، ويتوقف قليلا قبل المحاولة التالية.

متى تستخدمها

  • ✓عندما يحتاج جزء من التطبيق إلى الاتصال بخدمة أخرى وقد يفشل.
  • ✓عندما تريد أن يستمر التطبيق في العمل رغم أخطاء مؤقتة بسيطة.
  • ✓عندما تريد تجنب إثقال خدمة متعثرة بمحاولات متتالية، عبر المحاولة تدريجيا.

رابط المهارة

https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-resilience/SKILL.md

انسخه والصقه في الذكاء الاصطناعي الذي تستخدمه (Claude أو ChatGPT أو Cursor) واطلب منه اتباع التعليمات.

طريقة الاستخدام

أسهل طريقة: انسخ الرسالة والصقها في الذكاء الاصطناعي الذي تستخدمه. سيقرأ المهارة وينفّذ تعليماتها.

رسالة جاهزة للصق

استخدم هذه المهارة لمساعدتي: https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-resilience/SKILL.md اقرأ ملف SKILL.md في هذا الرابط ونفّذ تعليماته لمهمتي.
تريد أن يجد الذكاء الاصطناعي مهارات مثل هذه بنفسه؟ثبّت خادم Skillpedia MCP المجاني: سطر واحد، ويبحث في 15,000+ مهارة قبل كل مهمة.ثبّته في دقيقة واحدة →

مثال على ما تطلبه من الذكاء الاصطناعي

“اجعل تطبيقي يعيد المحاولة حتى 3 مرات إذا فشل الاتصال بالموقع، مع زيادة مدة الانتظار في كل مرة.”

5 مهارات جديدة كل أسبوع. قراءة في دقيقة واحدة.

كيف تعمل

يستخدم الكود تقنية تُسمى إعادة المحاولة. إذا فشلت عملية، ينتظر لمدة تزداد مع كل محاولة، وهذا يُسمى التراجع الأُسّي (exponential backoff)، ثم يحاول من جديد، فلا ينهار التطبيق.

المحتوى التقني (ملف SKILL.md الأصلي)

النص الأصلي من المؤلف، مباشرة من GitHub.

Python Resilience Patterns

Build fault-tolerant Python applications that gracefully handle transient failures, network issues, and service outages. Resilience patterns keep systems running when dependencies are unreliable.

When to Use This Skill

  • Adding retry logic to external service calls
  • Implementing timeouts for network operations
  • Building fault-tolerant microservices
  • Handling rate limiting and backpressure
  • Creating infrastructure decorators
  • Designing circuit breakers

Core Concepts

1. Transient vs Permanent Failures

Retry transient errors (network timeouts, temporary service issues). Don't retry permanent errors (invalid credentials, bad requests).

2. Exponential Backoff

Increase wait time between retries to avoid overwhelming recovering services.

3. Jitter

Add randomness to backoff to prevent thundering herd when many clients retry simultaneously.

4. Bounded Retries

Cap both attempt count and total duration to prevent infinite retry loops.

Quick Start

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

Fundamental Patterns

Pattern 1: Basic Retry with Tenacity

Use the tenacity library for production-grade retry logic. For simpler cases, consider built-in retry functionality or a lightweight custom implementation.

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

Pattern 2: Retry Only Appropriate Errors

Whitelist specific transient exceptions. Never retry:

  • ValueError, TypeError - These are bugs, not transient issues
  • AuthenticationError - Invalid credentials won't become valid
  • HTTP 4xx errors (except 429) - Client errors are permanent
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()

Pattern 3: HTTP Status Code Retries

Retry specific HTTP status codes that indicate transient issues.

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)

Pattern 4: Combined Exception and Status Retry

Handle both network exceptions and HTTP status codes.

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

…
الأسئلة الشائعة

ما هي «الأعطال العابرة» (transient failures)؟

هي مشكلات تُصلح نفسها، مثل شبكة كانت بطيئة لحظة، أو خدمة كانت متوقفة ثم عادت للعمل.

لماذا أنتظر أكثر مع كل محاولة؟

لإعطاء الخدمة المتعثرة وقتا لتتعافى. فالمحاولات الكثيرة المتتالية قد تفاقم المشكلة.

ما هو «التشويش» (jitter)؟

هو إضافة مقدار عشوائي صغير إلى فترات الانتظار. وهذا يمنع كثيرا من التطبيقات من إعادة المحاولة في اللحظة نفسها، مما قد يُثقل الخدمة.

التفاصيل

الوصف الأصلي من المؤلف

Python resilience patterns including automatic retries, exponential backoff, timeouts, and fault-tolerant decorators. Use when adding retry logic, implementing timeouts, building fault-tolerant services, or handling transient failures.

repo: wshobson/agents

الشعبية

نجوم GitHub
41k
الترتيب
#6766
الترخيص
MIT
آخر تحديث
15‏/10‏/2026

هل هذه المهارة مفيدة؟

0

سجّل الدخول للتصويت.

التعليقات

  • …

المزيد من المهارات من هذا المستودع

مهارات مشابهة