#!/usr/bin/env python3 """
Example of using retry middleware with aiohttp client.
This example shows how to implement a middleware that automatically retries
failed requests with exponential backoff. The middleware can be configured with custom retry statuses, maximum retries, and backoff parameters.
This example includes a test server that simulates various HTTP responses and can return different status codes on sequential requests. """
import asyncio import logging from http import HTTPStatus from typing import TYPE_CHECKING, Dict, List, Set, Union
from aiohttp import ClientHandlerType, ClientRequest, ClientResponse, ClientSession, web
async def handle_status(self, request: web.Request) -> web.Response: """Return the status code specified in the path."""
status = int(request.match_info["status"]) return web.Response(status=status, text=f"Status: {status}")
async def handle_status_sequence(self, request: web.Request) -> web.Response: """Return different status codes on sequential requests."""
path = request.path
# Initialize counter for this path if needed if path notin self.request_counters:
self.request_counters[path] = 0
# Get the status sequence for this path
sequence_name = request.match_info["name"] if sequence_name notin self.status_sequences: return web.Response(status=404, text="Sequence not found")
sequence = self.status_sequences[sequence_name]
# Get the current status based on request count
count = self.request_counters[path] if count < len(sequence):
status = sequence[count] else: # After sequence ends, always return the last status
status = sequence[-1]
# Increment counter for next request
self.request_counters[path] += 1
return web.Response(
status=status, text=f"Request #{count + 1}: Status {status}"
)
async with ClientSession(middlewares=(retry_middleware,)) as session: # Reset counters before tests
await session.post("http://localhost:8080/reset")
# Test 1: Request that succeeds immediately
print("=== Test 1: Immediate success ===")
async with session.get("http://localhost:8080/sequence/immediate-ok") as resp:
text = await resp.text()
print(f"Final status: {resp.status}")
print(f"Response: {text}")
print("Success - no retries needed\n")
# Test 2: Request that eventually succeeds after retries
print("=== Test 2: Eventually succeeds (500->503->502->200) ===")
async with session.get("http://localhost:8080/sequence/eventually-ok") as resp:
text = await resp.text()
print(f"Final status: {resp.status}")
print(f"Response: {text}") if resp.status == 200:
print("Success after retries!\n") else:
print("Failed after retries\n")
# Test 3: Request that always fails
print("=== Test 3: Always fails (500->500->500->500) ===")
async with session.get("http://localhost:8080/sequence/always-error") as resp:
text = await resp.text()
print(f"Final status: {resp.status}")
print(f"Response: {text}")
print("Failed after exhausting all retries\n")
# Test 4: Flaky service (fails once then succeeds)
print("=== Test 4: Flaky service (503->200) ===")
await session.post("http://localhost:8080/reset") # Reset counters
async with session.get("http://localhost:8080/sequence/flaky") as resp:
text = await resp.text()
print(f"Final status: {resp.status}")
print(f"Response: {text}")
print("Success after one retry!\n")
# Test 5: Non-retryable status
print("=== Test 5: Non-retryable status (404) ===")
async with session.get("http://localhost:8080/status/404") as resp:
print(f"Final status: {resp.status}")
print("Failed immediately - not a retryable status\n")
# Test 6: Delayed response
print("=== Test 6: Testing with delay endpoint ===") try:
async with session.get("http://localhost:8080/delay/0.5") as resp:
print(f"Status: {resp.status}")
data = await resp.json()
print(f"Response received after delay: {data}\n") except asyncio.TimeoutError:
print("Request timed out\n")
async def main() -> None: # Start test server
server = await run_test_server()
¤ Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.0.5Bemerkung:
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.