Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Building an Async API Client | Asyncio in Practice
Python Asyncio in Depth
Seksjon 3. Kapittel 5
single

single

Challenge: Building an Async API Client

Sveip for å vise menyen

You are building a rate-limited API client that fetches comment data from jsonplaceholder.typicode.com. The client must limit concurrency to avoid overwhelming the server, apply a per-request timeout, and collect results without failing on individual errors.

The endpoint https://jsonplaceholder.typicode.com/comments/{comment_id} returns a JSON object with the following fields:

  • postId: the ID of the post the comment belongs to;
  • name: the comment title;
  • email: the commenter's email address.
Oppgave

Sveip for å begynne å kode

  1. Define an async function fetch_comment(client, semaphore, comment_id) that:
    • Uses the provided semaphore to limit concurrency;
    • Fetches the comment with a 3.0 second timeout using asyncio.wait_for();
    • Returns a formatted string: "[Post {postId}] {name} by {email}";
    • Returns "Comment {comment_id} failed" if a TimeoutError or Exception occurs.
  2. Define an async function main() that:
    • Creates an asyncio.Semaphore with a limit of 5;
    • Fetches comments with IDs 1 through 15 concurrently using asyncio.gather();
    • Prints each result on a separate line.
  3. Run main() using asyncio.run().

Løsning

Switch to desktopBytt til skrivebordet for virkelighetspraksisFortsett der du er med et av alternativene nedenfor
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 5
single

single

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt