{"library":"pybreaker","code":"import pybreaker\nimport requests\n\n# Simulate a flaky external service\n_service_up = True\n\ndef external_service_call():\n    global _service_up\n    if _service_up:\n        print(\"Calling external service...\")\n        # Simulate a network error or service unavailability\n        if requests.get(\"http://localhost:9999/health\", timeout=0.1).status_code != 200:\n            raise requests.exceptions.ConnectionError(\"Service not reachable\")\n        return \"Service data\"\n    else:\n        print(\"Service is intentionally down (simulated).\")\n        raise requests.exceptions.ConnectionError(\"Service is down\")\n\n# Create a circuit breaker instance\n# Opens after 3 failures within 60 seconds\n# Stays open for 10 seconds before trying again (half-open)\nmy_breaker = pybreaker.CircuitBreaker(\n    fail_max=3,\n    reset_timeout=10,\n    exclude=[requests.exceptions.HTTPError] # Exclude HTTP errors that are not system failures\n)\n\n@my_breaker\ndef protected_call():\n    return external_service_call()\n\nprint(\"--- Starting Circuit Breaker Demo ---\")\n\nfor i in range(10):\n    print(f\"\\nAttempt {i+1}:\")\n    try:\n        result = protected_call()\n        print(f\"Success: {result}\")\n        _service_up = True # Reset service state on success to show circuit closing\n    except pybreaker.CircuitBreakerError:\n        print(\"Circuit OPEN! Falling back to cached data or default.\")\n        _service_up = False # Keep service down if breaker opened\n    except requests.exceptions.ConnectionError as e:\n        print(f\"Connection error: {e}. Circuit state: {my_breaker.current_state}\")\n        # Simulate service coming back up after a few failures\n        if i == 5: # Make service available after 5 attempts\n            _service_up = True\n    except Exception as e:\n        print(f\"Unexpected error: {e}\")\n\n# A real application would not typically control _service_up like this in quickstart,\n# but it illustrates the breaker's behavior.","lang":"python","description":"This quickstart demonstrates how to apply a circuit breaker to protect calls to an unreliable external service using `pybreaker.CircuitBreaker` as a decorator. It simulates service failures and shows how the circuit transitions between `CLOSED`, `OPEN`, and `HALF_OPEN` states, with appropriate error handling and a fallback mechanism.","tag":null,"tag_description":null,"last_tested":"2026-04-24","results":[{"runtime":"python:3.10-alpine","exit_code":1},{"runtime":"python:3.10-slim","exit_code":1},{"runtime":"python:3.11-alpine","exit_code":1},{"runtime":"python:3.11-slim","exit_code":1},{"runtime":"python:3.12-alpine","exit_code":1},{"runtime":"python:3.12-slim","exit_code":1},{"runtime":"python:3.13-alpine","exit_code":1},{"runtime":"python:3.13-slim","exit_code":1},{"runtime":"python:3.9-alpine","exit_code":1},{"runtime":"python:3.9-slim","exit_code":1}]}