Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Fetching Data Concurrently | Tasks and Scheduling
Python Asyncio in Depth
Sektion 2. Kapitel 7
single

single

Challenge: Fetching Data Concurrently

Stryg for at vise menuen

You are building a data aggregation script that pulls information about users and their posts from jsonplaceholder.typicode.com. Your goal is to fetch all the data concurrently and produce a summary report.

The following endpoints are available:

  • https://jsonplaceholder.typicode.com/users/{user_id} – returns a user object with name and email fields;
  • https://jsonplaceholder.typicode.com/posts?userId={user_id} – returns a list of posts for a given user.
Opgave

Swipe to start coding

  1. Define an async function fetch_user(client, user_id) that fetches the user object and returns a dict with keys name and email.
  2. Define an async function fetch_post_count(client, user_id) that fetches the posts list for a user and returns the number of posts as an integer.
  3. Define an async function fetch_user_summary(client, user_id) that:
    • calls fetch_user() and fetch_post_count() concurrently using asyncio.gather();
    • returns a formatted string: "{name} ({email}) – {post_count} posts".
  4. Define an async function main() that:
    • fetches summaries for user IDs 1 through 5 concurrently using asyncio.gather();
    • prints each summary on a separate line.
  5. Run main() using asyncio.run().

Løsning

Switch to desktopSkift til skrivebord for at øve i den virkelige verdenFortsæt der, hvor du er, med en af nedenstående muligheder
Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 7
single

single

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

some-alt