Osio 3. Luku 5
single
Challenge: Building an Async API Client
Pyyhkäise näyttääksesi valikon
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.
Tehtävä
Pyyhkäise aloittaaksesi koodauksen
- Define an async function
fetch_comment(client, semaphore, comment_id)that:- Uses the provided
semaphoreto limit concurrency; - Fetches the comment with a
3.0second timeout usingasyncio.wait_for(); - Returns a formatted string:
"[Post {postId}] {name} by {email}"; - Returns
"Comment {comment_id} failed"if aTimeoutErrororExceptionoccurs.
- Uses the provided
- Define an async function
main()that:- Creates an
asyncio.Semaphorewith a limit of5; - Fetches comments with IDs
1through15concurrently usingasyncio.gather(); - Prints each result on a separate line.
- Creates an
- Run
main()usingasyncio.run().
Ratkaisu
Oliko kaikki selvää?
Kiitos palautteestasi!
Osio 3. Luku 5
single
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme