Middle+
import aiohttp import asyncio async def fetch_all_tickets(self, ticket_ids: list, max_concurrent_requests: int =10): semaphore = asyncio.Semaphore(max_concurrent_requests) async with aiohttp.ClientSession() as session: tasks = [self._get_ticket(ticket_id, session, semaphore) for ticket_id in ticket_ids] tickets = [] for task in tasks: ticket = await task if ticket is not None: tickets.append(ticket) return tickets
sobes.tech AI
Answer from AI
The provided code uses asyncio.Semaphore to limit the number of concurrently executing asynchronous API requests (via aiohttp). This prevents server or client overload.
Main idea:
- A semaphore is created with a maximum number of concurrent requests
max_concurrent_requests. - For each
ticket_id, a task_get_ticketis created, which should use the semaphore (viaasync with semaphore:) to limit parallelism. - All tasks are started simultaneously, but the semaphore ensures that no more than
max_concurrent_requestsare running at the same time. - Results are collected sequentially via
await task.
Example of using a semaphore inside _get_ticket:
async def _get_ticket(self, ticket_id, session, semaphore):
async with semaphore:
async with session.get(f'https://api.example.com/tickets/{ticket_id}') as resp:
if resp.status == 200:
return await resp.json()
return None
This approach allows for efficient and safe multiple requests without exceeding server limits and without creating too many concurrent connections.