HTTSleep

0.3.1 · maintenance · verified Fri Apr 17

HTTSleep is a Python library designed for polling HTTP endpoints with built-in features like exponential backoff and retries. It leverages `requests` for HTTP operations and `backoff` for robust retry logic. The current version is 0.3.1. Development appears to be in maintenance mode, with no new releases or significant commits since early 2021.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `HTTSleep` to poll an endpoint until a specific condition is met. The `simulate_api_call` function acts as a mock HTTP service, returning 'pending' status a few times before eventually returning 'completed'. The `check_func` defines the condition for successful polling. The poller will retry with exponential backoff until the condition is met or the `timeout` is reached.

import time
from httsleep import HTTSleep
import requests # To create a mock response for the example
import json

# Simulate a remote service that eventually returns 'completed'
# In a real scenario, this would be your actual API endpoint.
mock_response_count = 0
def simulate_api_call(url=None, **kwargs):
    nonlocal mock_response_count
    mock_response_count += 1

    mock_resp = requests.Response()
    if mock_response_count < 3:
        mock_resp.status_code = 202 # Accepted (still processing)
        mock_resp._content = b'{"status": "pending", "detail": "processing..."}'
        mock_resp.request = requests.Request('GET', url or 'http://mock.api/status').prepare()
    else:
        mock_resp.status_code = 200 # OK
        mock_resp._content = b'{"status": "completed", "result": "success!"}'
        mock_resp.request = requests.Request('GET', url or 'http://mock.api/status').prepare()
    
    # Monkey-patch json method for simplicity
    def json_method():
        return json.loads(mock_resp._content.decode('utf-8'))
    mock_resp.json = json_method
    return mock_resp

# Create an HTTSleep instance
poller = HTTSleep(
    http_get_func=simulate_api_call, # Pass the mock function that makes HTTP calls
    check_func=lambda resp: resp.json().get("status") == "completed",
    timeout=20, # Total timeout for polling in seconds
    interval=1, # Initial interval in seconds
    max_interval=5, # Max interval between retries
    factor=2, # Exponential backoff factor
    logger=None # Suppress default logging for clean quickstart output
)

print("Starting polling for a 'completed' status...")
try:
    final_response = poller.poll()
    print(f"Polling successful! Final status: {final_response.json().get('status')}")
    print(f"Total attempts: {mock_response_count}")
except Exception as e:
    print(f"Polling failed after timeout: {e}")

# Reset count for potential re-runs in an interactive environment
mock_response_count = 0

view raw JSON →